Java GUI编程(AWT)

301 阅读1分钟

Frame布局

东西南北中布局:

Frame frame = new Frame("标题");

Button north = new Button("north");
frame.add(north BorderLayout.NORRTH);

frame.setSize(200, 200);
frame.servisible(true);

实例:

//总Frame
Frame frame = new Frame();

frame.setSize(400, 300);
frame.setLocation(300, 400);
frame.setBackground(Color.WHITE);
frame.setVisible(true);
frame.serLayout(new GridLayout(2, 1));

//4个面板
Panel p1 = new Panel(new BorderLayout());
Panel p2 = new Panel(new GridLayout(2, 1));
Panel p3 = new Panel(new BorderLayout());
Panel p4 = new Panel(new GridLayout(2, 2));

//上面
p1.add(new Button("East-1"), BorderLayout.EAST);
p1.add(new Button("West-1"), 
BorderLayout.WEST);
p2.add(new Button("p2-btn-1"));
p2.add(new Button("p2-btn-2"));
p1.add(p2, BorderLayout.CENTER);

//下面
p3.add(new Button("East-2"), BorderLayout.EAST);
p3.add(new Button("West-2"), 
BorderLayout.WEST);
for(int i = 0;i < 4; i++) {
    p4.add(new Button("for-"+i));
}
p3.add(p4, BorderLayout.CENTER);

frame.add(p1);
frame.add(p3);

事件

\\按下按钮,触发一些事件
public static void main(String args[]){
    Frame frame = new Frame();
    Button button = new Button();

    //因为addActionListener()需要一个ActionListener, 所以我们需要构造一个ActionListener
    MyActionListener myActionListener = new MyActionListener(); 
    button.addActionListener(myActionListener);
    
    frame.add(button, BorderLayout.CENTER);
    
    windowClose(frame); //关闭窗口
    frame.setVisible(true);
}

private static void windowClose(Frame frame) {
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
}

//事件监听
class MyActionListener implements ActionListener {
    public void actionPerformed(AcitonEvent e) {
        xxxx;
    }
}

文本框

class MyFrame implements Frame{
    public MyFrame() {
        TextField textField = new TextField();
        add(textField);
        
        //监听这个文本框输入的数字
        MyActionLisener2 myActionListener2 = new MyActionListener2();
        //按下enter 就会触发这个输入框的事件
        textField.addActionListener(myActionListener2);
        
        //设置替换编码
        textField.setEchoChar('*');
        
        setVisible(true);
    }
}

class MyAcitonListener2 implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField field = (TextField) e.getSource(); // 获得一些资源,返回一个对象
        System.out.println(field.getText()); //获得输入框的文本
        field.setText(""); 
    }
}

学习资源

www.bilibili.com/video/av776…