Java AWT组件

本文最后更新于:2024年3月18日 凌晨

Java AWT组件

AWT部件概述

  • AWT部件层次关系如下图所示,Component类处于GUI部件类层次的顶层,其直接子类有Container(容器)和其他8个基本部件。

  • Component类为一个抽象类,其中定义了所有GUI部件普遍适用的方法,以下为若干常用方法:
    • void add(PopupMenu popup):给部件加入弹出菜单。
    • Color getBackground():获取部件的背景色。
    • Font getFont():获取部件的显示字体。
    • Graphics getGraphics():获取部件的画笔(Graphocs对象)
    • void repaint(int x,int y, int width,int height):在部件的指定区域重新绘图。
    • void setBackground(Color c):设置部件的背景。
    • void setEnabled(boolean b):是否让部件功能有效,在无效情况下部件将变成灰色。
    • void setFont(Font f):设置部件的显示字体。
    • void setSize(int width,int height):设置部件的大小。
    • void setVisible(boolean b):设置部件是否可见。
    • void setForeground(Color c):设置部件的前景色。
    • void requestFocus():让部件获得焦点。
    • Toolkit getToolkit():取得部件的工具集(Toolkit),利用Toolkitbeep()方法可让计算机发出鸣叫声。
    • FontMetrics getFontMetrics(Font font):取得某字体对应的FontMerics对象。

窗体容器

  • 在图形用户界面中经常用到窗体。
  • Java Application程序中窗体是图形界面设计所必须的容器。
  • Java Applet分有边框的Window子类和无边框的Panel子类。
  • FrameApplet分别是WindowPanel的子类。

Frame

  • Frame的常用构造方法为Frame(String title),其中参数title指定窗体标题,新创建的Frame是不可见的。
    • setVisible(true)方法或show()方法让窗体可见。
    • setSize(width,heiight)方法为窗体设置大小。
    • pack()方法让布局管理器根据部件的大小来调整确定窗体的尺寸。
    • setResizable(flase)方法固定窗体的大小。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class FrameTest {
public static void main(String[] args) {
// 创建容器并初始化标题。
Frame frame = new Frame("Frame");
// 设置容器可见性。
frame.setVisible(true);
// 设置容器大小。
frame.setSize(400, 400);
// 初始位置。
frame.setLocation(200, 200);
// 同时设置容器大小和初始位置。
frame.setBounds(200, 200, 400, 400);
// 设置背景颜色。
frame.setBackground(Color.gray);
// 设置大小固定。
frame.setResizable(false);
}
}

paint

  • 通过重写Frame的paint(Graphics g)方法,可以实现获得画笔Graphics
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class TestPaint extends Frame {

public TestPaint() {
setBounds(200, 200, 600, 500);
setVisible(true);
}

@Override
public void paint(Graphics g) {
super.paint(g);
}

public static void main(String[] args) {
new TestPaint();
}
}
Graphics
  • 设置画笔的属性。
1
2
public abstract void setColor(Color c);
public abstract void setFont(Font font);
  • 通过画笔绘制图形。
1
2
3
4
5
6
7
public abstract void drawLine(int x1, int y1, int x2, int y2);
public abstract void fillRect(int x, int y, int width, int height);
public void drawRect(int x, int y, int width, int height) ;
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle);
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle);
public abstract void drawOval(int x, int y, int width, int height);
public abstract void fillOval(int x, int y, int width, int height);
  • 通过画笔绘制文本。
1
public abstract void drawString(AttributedCharacterIterator iterator, int x, int y);

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class TestPaint extends Frame {

public TestPaint() {
setBounds(200, 200, 600, 500);
setVisible(true);
// 重新绘制,即重新执行paint方法。
repaint();
}

@Override
public void paint(Graphics g) {
// 设置画笔颜色。
g.setColor(Color.red);
// 空心圆。
g.drawOval(100,100,100,100);
// 实心矩形。
g.fillRect(150,200,200,200);
// 设置字体。
Font titleFont = new Font("宋体", Font.BOLD, 40);
g.setFont(titleFont);
// 用于文本对齐。
FontMetrics fontMetrics = g.getFontMetrics(titleFont);
String text = "测试文本";
// 绘制文本。
g.drawString(text, mainPosition.x + (mainWidth - fontMetrics.stringWidth(text)) / 2, mainPosition.y + ((mainHeight - fontMetrics.getHeight()) / 2) + fontMetrics.getAscent());
}

public static void main(String[] args) {
new TestPaint();
}
}

Panel

  • Panel需要放置在Frame中,可以在同一个Frame中放置多个。
  • Panel与Frame都可以放置其他组件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class PanelTest {
public static void main(String[] args) {
Frame frame = new Frame("Frame");
Panel panel = new Panel();
// 配置frame
frame.setLayout(null);
frame.setBounds(300, 300, 500, 500);
frame.setBackground(Color.gray);
frame.setVisible(true);
// 配置panel
panel.setBounds(50, 50, 400, 400);
panel.setBackground(Color.BLUE);
// 将panel加入到frame中。
frame.add(panel);
}
}

加入交互部件

  • add()方法将指定的GUI部件加入到容器中,GUI部件在容器中如何排列取决于布局选择。

Button

1
Button btn = new Button("按钮名");

Button的事件响应

  • 可以监听按钮被点击的事件。
  • 当多个按钮被同一个监听器监听是,可以通过getActionCommand()获取按钮名。

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class MyFrame extends Frame implements ActionListener {
Button btn1;
Button btn2;

public MyFrame() {
btn1 = new Button("开始");
btn2 = new Button("关闭");
add(btn1);
add(btn2);
btn1.addActionListener(this);
btn2.addActionListener(this);
setSize(300, 200);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {
// 判断动作事件的事件源需要将按钮的命令名与"关闭”字符串进行相等比较,采用String类的equals()方法进行比较。
if (e.getActionCommand().equals("关闭")) {
dispose();
}
}

public static void main(String[] args) {
new MyFrame();
}
}

TextField与TextArea

TextField

  • 文本框只能编辑一行数据,由TextField类实现,其构造方法有如下4种:
    • TextField():构造一个单行文本输入框。
    • TextField(int columns):构造一个指定长度的单行文本输入框。
    • TextField(String text):构造一个指定初始内容的单行文本输入框。
    • TextField(String text,int columns):构造一个指定长度,指定初始内容的单行文本输入框。
  • 在某种情况下,用户可能希望自己的输入不被别人看到,这时可以用TextField类中的setEchoChar()方法设置回显字符,使用户的输入全部以某个特殊字符显示在屏幕上,例如,以下设置密码输入框的回显字符为*
1
2
TextField pass = new TextField(8);
pass.setEchoChar('*');

TextArea

  • 文本域也称多行文本输入框,其特点是可以编辑多行文字,文本域由TextArea类实现,其构造方法有如下4种:
    • TextArea():构造一个文本域。
    • TextArea(int rows,int columns):构造一个指定行数和列数的文本域。
    • TextArea(String text):构造一个显示指定文字的文本域。
    • TextArea(String text,int rows,int columns):按指定行数,列数和默认值构造多行文本域。
  • 例如:
1
TextArea t1 = new TextArea(10,45);

文本部件的常用方法

数据的写入与读取

  • 文本框与文本域均是TextComponent类的子类,在这个父类中定义了对文本输入部件的公共方法,其中最常用的是数据的写入与读取。
    • String getText():获取输入框中的数据。
    • void setText(String text):想输入框中写入数据。
    • boolean isEditable():判断输入框是否可编辑,非编辑状态下,不能通过键盘操作输入数据。

指定和获取文本区域中"选定状态”文本

  • 本文输入部件中的文本可以进行选定操作,以下方法用于指定和获取文本区域中"选定状态”文本。
    • void select(int start,int end):选定由开始和结束位置指定的文本。
    • void selectAll():选定所有文本。
    • void setSelectStart(int start):设置选定开始位置。
    • void setSelectEnd(int end):设置选定结束位置。
    • int getSelectionStart():获取选定开始位置。
    • int getSelectionEnd():获取选定结束位置。
    • String getSelectedText():获取选定的文本数据。

屏蔽回显

  • 屏蔽回显只适用于文本框,以下为相关方法。
    • void setEchoChar(char c):设置回显字符。
    • boolean echoCharIsSet():确认当前输入框是否处于不回显状态。
    • char getEchoChar():获取回显屏蔽字符。

添加数据

  • 以下方法只限于文本域,可以在已有内容的基础上添加新数据,具体方法如下:
    • void append(String s):将字符串添加到文本域的末尾。
    • void insert(String s,int pos):将字符串插入到文本域的指定位置。

文本部件的事件响应

  • 在文本框中按回车键时,将引发动作事件,事件的注册于处理程序的编写方法与按钮的动作事件相同。
  • 当用户对文本输入部件进行任何操作更改操作(如添加,修改和删除)时将引发TextEvent事件,为了响应该事件,可以通过addTextListener()方法注册监听者,在TextListener接口中定义了如下方法来处理事件。
1
public void textValueChanged(TextEvent e);

[例11-7]:在图形界面中,安排一个文本框和文本域,将在文本框中输入的字符同时显示在文本域中,即同步显示,在文本框上按回车键将文本框中内容清空。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Textln extends Frame implements TextListener, ActionListener {
TextField tf;
TextArea ta;
String pre = "";// 记录文本域的先前内容。

public Textln() {
tf = new TextField(20);
ta = new TextArea(8, 20);
add("South", tf);
add("Center", ta);
tf.addTextListener(this);// 在文本框有内容变化触发文本改变事件。
tf.addActionListener(this);// 在文本框按Enter键后将触发动作事件。
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

// 在文本框中输入字符时通过文本事件执行。
public void textValueChanged(TextEvent e) {
// 引入变量pre记下文本域中前面行输入的内容
String s = tf.getText();
// 将pre记录的内容与文本框的内容拼接写入文本域。
ta.setText(pre + s);
}

// 文本框中按Enter键时通过动作事件执行该方法。
public void actionPerformed(ActionEvent e) {
tf.setText("");// 清空文本框。
ta.append("\n");// 添加一个换行符。
pre = ta.getText();// 更新pre变量,记下文本域前面各行内容。
}

public static void main(String[] args) {
Frame m = new Textln();
m.setSize(300, 300);
m.setVisible(true);
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!