Java GUI 编程学习笔记(2)
程序员文章站
2022-05-29 19:33:49
...
1 文本框的数据放到文本域显示
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
// -Dfile.encoding=GB18030
public class TextAreaTest {
public static void main(String[] args) {
Frame f = new Frame("文本域");
f.setBounds(400,200,400,300);
f.setLayout(new FlowLayout());
TextField tf = new TextField(20);
Button bu = new Button("数据搬迁");
TextArea ta = new TextArea(10,40);
f.add(tf);
f.add(bu);
f.add(ta);
// 窗口关闭
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// 按钮添加事件
bu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// 获取文本框的值
String tf_str = tf.getText().trim();
// 清空
tf.setText("");
//设置文本域
ta.append(tf_str + "\r\n");
// 文本框获取光标
tf.requestFocus();
}
});
f.setVisible(true);
}
}
2 鼠标移动到按钮上改变背景色
import java.awt.*;
import java.awt.event.*;
public class MouseColor {
public static void main(String[] args) {
Frame f = new Frame("鼠标移动改颜色");
f.setBounds(400, 200, 400, 300);
f.setLayout(new FlowLayout());
Button redButton = new Button("Red");
f.add(redButton);
// 设置窗体关闭
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// 动作监听
/*redButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
f.setBackground(Color.red);
}
});
*/
// 对按钮添加鼠标监听
redButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
f.setBackground(Color.RED);
}
@Override
public void mouseExited(MouseEvent e) {
f.setBackground(Color.WHITE);
}
});
f.setVisible(true);
}
}
3 限制文本框只能输入数字
import java.awt.*;
import java.awt.event.*;
// -Dfile.encoding=GB18030
public class Demo7 {
public static void main(String[] args) {
Frame f = new Frame("按钮测试");
f.setBounds(400, 200, 400, 300);
//设置流式布局
f.setLayout(new FlowLayout());
Label label = new Label("输入 QQ 号码(阿拉伯数字)");
TextField tf = new TextField(20);
f.add(label);
f.add(tf);
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// 文本框添加事件
tf.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
char ch = e.getKeyChar();
if (!(ch >= '0' && ch <= '9')) {
e.consume();
}
}
});
f.setVisible(true);
}
}