java GUI(一)

监听退出

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

布局管理器

  1. 流式布局
  2. 东西南北中布局
  3. 网格布局

监听:当某个事件发生的时候干什么


public class gui {
    
    
    public static void main(String[] args) {
    
    
        Frame frame = new Frame("kafens");
        Button but1 = new Button("click!");
        frame.add(but1);
        frame.setVisible(true);
        myButtonListener my = new myButtonListener();
        but1.addActionListener(my);
        closeWindow(frame);

    }

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

    }
}

class  myButtonListener implements ActionListener{
    
    
    @Override
    public void actionPerformed(ActionEvent e) {
    
    
        System.out.println("kafen");
    }


}

监听的复用


public class gui {
    
    
    public static void main(String[] args) {
    
    
        Frame frame = new Frame();
        Button but1 = new Button("start");
        Button but2 = new Button("stop");
        frame.add(but1,BorderLayout.NORTH);
        frame.add(but2,BorderLayout.SOUTH);
        but1.setActionCommand("but1");//可以设置标识符
        but2.setActionCommand("but2");//可以设置标识符

        myAction ma = new myAction();
        but1.addActionListener(ma);
        but2.addActionListener(ma);
        
        frame.setVisible(true);



    }
}
class myAction implements ActionListener{
    
    
    @Override
    public void actionPerformed(ActionEvent e) {
    
    
        if(e.getActionCommand().equals("but1")){
    
    
            System.out.println("this is but1");
        }
        else{
    
    
            System.out.println("this is but2");
        }
    }
}

文本框


public class gui {
    
    
    public static void main(String[] args) {
    
    
        myFrame mf = new myFrame();

    }
}

class myFrame extends Frame{
    
    
    public myFrame(){
    
    
    TextField tf1 = new TextField();
    add(tf1);
    myActionListener ma = new myActionListener();
    tf1.addActionListener(ma);

    pack();
    tf1.setEchoChar('*');
    setVisible(true);

    }
}

class myActionListener implements ActionListener{
    
    
    @Override
    public void actionPerformed(ActionEvent e) {
    
    
        TextField field = (TextField)e.getSource();//get some source,return a object
        System.out.println(field.getText());; //get the text imformation
        field.setText("");
    }
}

//看到第八集

猜你喜欢

转载自blog.csdn.net/KafenWong/article/details/121498274