Loading

Java之AWT、Swing编程

Java之AWT、Swing编程

AWT

AWT简介

抽象的窗口工具

AWT中包含了很多元素,窗口、按钮、文本框等。

这些都是一个组件(component),其中包括按钮(button),文本域(TextArea),文字内容(Label)还有输入框等。

这些组件都需要存放在容器(container)里。容器有窗口(window)和面板(panel),其中window中分为窗口(frame)和弹窗(dialog)

组件和容器

Frame 窗口

Frame 是一个带有标题和边框的顶级窗口,可以向其中添加自定义的组件

public class FrameDemo {
    public static void main(String[] args) {
				// 窗口title
        Frame frame = new Frame("First Frame");
				// 背景色
        frame.setBackground(Color.CYAN);
       //  frame.setIconImage();
      	 //窗口大小
        frame.setSize(400,400);
      	// 窗口位置,距离左上角
        frame.setLocation(100,100);
       // 可拉伸性
        frame.setResizable(true);
      // 可见性
        frame.setVisible(true);

    }
}

其中

//窗口大小
frame.setSize(400,400);
// 窗口位置,距离左上角
frame.setLocation(100,100);
可用
setBounds方法替换

Panel 面板

Panel不能单独存在,需要放在容器里面(比如Frame),可以看作是自己开辟的一小块空间

在Frame中添加Panel组件

这里注意设置布局为null,不为null时拉伸Frame会使Panel充满整个Frame

public class FrameDemo {
    public static void main(String[] args) {

        Frame frame = new Frame("First Frame");

        frame.setBackground(Color.GRAY);
       //  frame.setIconImage();
        frame.setSize(400,400);
        frame.setLocation(100,100);
        frame.setResizable(true);
        frame.setVisible(true);
        // 设置布局为null
        frame.setLayout(null);

        Panel panel = new Panel();
        panel.setBackground(Color.CYAN);
        panel.setBounds(50,50,100,100);
        //panel.setVisible(true);
        frame.add(panel);
      
       // 窗口点击关闭监听事件
        frame.addWindowListener(new WindowAdapter() {
          @Override
          public void windowClosing(WindowEvent e) {
            System.exit(0);
          }
        });

    }
}

布局管理器 Layout

有3种布局

  1. 流式布局 FlowLayout
  2. 东西南北中 BorderLayout
  3. 表格布局

流式布局 FlowLayout

FlowLayout类中有几个属性,分别为LEFT,CENTER,RIGHT,LEADING,TRAILING ,默认为center,

public class FlowLayout implements LayoutManager, java.io.Serializable {

    public static final int LEFT        = 0;

    public static final int CENTER      = 1;

    public static final int RIGHT       = 2;

    public static final int LEADING     = 3;

    public static final int TRAILING = 4;

public class FlowLayoout {
    public static void main(String[] args) {
        Frame frame = new Frame("Flow Layout Frame");
        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.setLayout(new FlowLayout());
        frame.setBounds(100,100,400,400);
        frame.setVisible(true);
        frame.setResizable(true);

        // 窗口点击关闭监听事件
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

BorderLayout

public class BorderLayoutDemo {
    public static void main(String[] args) {

        Frame frame = new Frame("Boder Layout");

        Button east = new Button("East");
        Button west = new Button("West");
        Button south = new Button("South");
        Button north = new Button("North");
        Button center = new Button("Center");

        frame.add(east,BorderLayout.EAST);
        frame.add(west,BorderLayout.WEST);
        frame.add(south,BorderLayout.SOUTH);
        frame.add(north,BorderLayout.NORTH);
        frame.add(center,BorderLayout.CENTER);

        frame.setResizable(true);
        frame.setVisible(true);
        frame.setSize(400,400);

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

表格布局 GridLayout

public class GridLayoutDemo {
    public static void main(String[] args) {

        Frame frame = new Frame("GridLayout");

        Button button1 = new Button("button1");
        Button button2 = new Button("button2");
        Button button3 = new Button("button3");
        Button button4 = new Button("button4");
        Button button5 = new Button("button5");
        Button button6 = new Button("button6");

        frame.add(button1);
        frame.add(button2);
        frame.add(button3);
        frame.add(button4);
        frame.add(button5);
        frame.add(button6);

        frame.setLayout(new GridLayout(3,2));
        frame.pack();
        frame.setVisible(true);
        frame.setSize(400,400);
        frame.setResizable(true);

        // 窗口点击关闭监听事件
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
}

事件监听

AWT事件监听器接口有很多

以下是常用事件侦听器的列表。

Sr. No. 控制和描述
1 ActionListener此接口用于接收动作事件。
2 ComponentListener此接口用于接收组件事件。
3 ItemListener此接口用于接收项目事件。
4 KeyListener该接口用于接收密钥事件。
5 MouseListener该接口用于接收鼠标事件。
6 TextListener此接口用于接收文本事件。
7 WindowListener该接口用于接收窗口事件。
8 AdjustmentListener该接口用于接收adjusmtent事件。
9 ContainerListener此接口用于接收容器事件。
10 MouseMotionListener该接口用于接收鼠标运动事件。
11 FocusListener该接口用于接收焦点事件。

监听器需要继承ActionListener接口,并在actionPerformed方法中实现触发事件的逻辑。如果组件是button的话可以通过addActionListener方法添加时间监听。

 static class MyListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                Runtime.getRuntime().exec("open -a Calculator");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

ActionEvent类中的一些方法

SN 方法和描述
1 java.lang.String getActionCommand()返回与此操作关联的命令字符串。
2 int getModifiers()返回此动作事件期间按下的修饰键。
3 long getWhen()返回此事件发生的时间戳。
4 java.lang.String paramString()返回标识此操作事件的参数字符串。

按钮事件监听

public class TestActionListenerEvent {

    public static void main(String[] args) {
        Frame frame = new Frame("ActionListener");

        Button calc = new Button("calc");
        MyListener myListener = new MyListener();
        calc.addActionListener(myListener);
        frame.add(calc);
        frame.setSize(400,400);
        frame.setVisible(true);
        frame.setResizable(true);
        frame.pack();
        WindowsClose(frame);


    }

    static class MyListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                Runtime.getRuntime().exec("open -a Calculator");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

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

}

输入框事件监听

public class TestTextFieldListenerEvent {

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

    static class MyFrame extends Frame {

        public MyFrame(){
            TextField textField = new TextField();
            // 监听输入框中输入的内容,按enter触发事件
            MyListener myListener = new MyListener();
            textField.addActionListener(myListener);
            add(textField);


            setVisible(true);
            setResizable(true);
            setSize(400,400);
            pack();
            Util.WindowsClose(this);

        }


    }

    static class MyListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            TextField source = (TextField) e.getSource();
            //获取输入框中的文本
            System.out.println(source.getText());
        }
    }
}

TextField#setEchoChar()可以设置gui中显示的内容,比如密码部分设置为*

简易calc


public class TestCalc {
    public static TextField a ;
    public static TextField b ;
    public static TextField c ;

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


    static class CalcFrame extends Frame {
        public CalcFrame(){

            // button =
            Button button1 = new Button("=");

            // textfield1
            TextField textField1 = new TextField(10);

            // Label + 
            Label label = new Label("+");

            // textfield2
            TextField textField2 = new TextField(10);


            // textfield3
            TextField textField3 = new TextField(20);


            equalListener equalListener = new equalListener(textField1,textField2,textField3);

            button1.addActionListener(equalListener);
            textField1.addActionListener(equalListener);
            textField1.addActionListener(equalListener);
            textField1.addActionListener(equalListener);

            add(textField1);
            add(label);
            add(textField2);
            add(button1);
            add(textField3);
            // 布局界面设置
            setLayout(new FlowLayout());
            setSize(400,400);
            setVisible(true);
            Util.WindowsClose(this);
        }


    }

    static class equalListener implements ActionListener{
        public equalListener(TextField textField1,TextField textField2,TextField textField3){
             a = textField1;
             b = textField2;
             c = textField3;


        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // 计算结果并输入到下一个textfield
            int num1 = Integer.parseInt(a.getText());
            int num2 = Integer.parseInt(b.getText());
            c.setText(String.valueOf((num1+num2)));
            a.setText("");
            b.setText("");
        }
    }
}

Swing

Swing提供许多比AWT更好的屏幕显示元素。它们用纯Java写成,所以同Java本身一样可以跨平台运行,这一点不像AWT。它们是JFC的一部分。它们支持可更换的面板和主题(各种操作系统默认的特有主题),然而不是真的使用原生平台提供的设备,而是仅仅在表面上模仿它们。这意味着你可以在任意平台上使用Java支持的任意面板。轻量级元件的缺点则是执行速度较慢,优点就是可以在所有平台上采用统一的行为。

Swing中封装好了很多的东西,方便代码的编写,可以让代码看起来没那么的臃肿

JFrame

Swing中的窗体由JFrame类实现,该类继承了Frame

下面是最简单的一个demo

WindowConstants中有多个属性,其中用的多的是

public static final int EXIT_ON_CLOSE = 3;	//关闭窗口
 public static final int HIDE_ON_CLOSE = 1;	//隐藏窗口

Demo

public class JframeDemo {

    public void init(){
        JFrame jFrame_demo = new JFrame("JFrame Demo");
        jFrame_demo.setVisible(true);
        jFrame_demo.setSize(400,400);

        // 窗口关闭事件
        jFrame_demo.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new JframeDemo().init();
    }
}

在Swing中有容器(container)这样的概念,所有的组件最好是都放到容器内,之前用到的Panel就是Container的子类

public class JframeDemo {

    public void init(){
        JFrame jFrame_demo = new JFrame("JFrame Demo");
        // 添加组件
        //new JLabel("text Jlabel", SwingConstants.CENTER)
        JLabel text_jlabel = new JLabel("text Jlabel");

        JButton jbutton = new JButton("Jbutton");

        JTextField jTextField = new JTextField(10);


        //jframe 获取 容器 container
        Container container = jFrame_demo.getContentPane();
        // 将组件添加到容器中
        container.add(text_jlabel);
        container.add(jbutton);
        container.add(jTextField);
        container.setLayout(new FlowLayout(FlowLayout.LEFT));


        jFrame_demo.pack();
        jFrame_demo.setVisible(true);
        jFrame_demo.setSize(400,400);

        // 窗口关闭事件
        jFrame_demo.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new JframeDemo().init();
    }
}

面板 JPanel

与Panel类 类似,可以设置layout等

public class JPanelDemo extends JFrame {

    public JPanelDemo (){
        Container contentPane = this.getContentPane();


        contentPane.setLayout(new GridLayout(2,1,10,10)); // 后2个参数为间距

        JPanel jPanel1 = new JPanel(new GridLayout(1,2));
        JPanel jPanel2 = new JPanel(new GridLayout(2,1));
        JPanel jPanel3 = new JPanel(new GridLayout(2,2));
        JPanel jPanel4 = new JPanel(new GridLayout(1,2));

        jPanel1.add(new JButton("1"));
        jPanel1.add(new JButton("1"));
        jPanel2.add(new JButton("2"));
        jPanel2.add(new JButton("2"));
        jPanel3.add(new JButton("3"));
        jPanel3.add(new JButton("3"));
        jPanel4.add(new JButton("4"));
        jPanel4.add(new JButton("4"));

        contentPane.add(jPanel1);
        contentPane.add(jPanel2);
        contentPane.add(jPanel3);
        contentPane.add(jPanel4);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }


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

弹窗 Dialog

public class DialogDemo {

    public static void main(String[] args) {
        new DialogDemo().init();

    }


    public void init(){
        JFrame jFrame = new JFrame();
        jFrame.setSize(500,500);
        // 设置窗口关闭事件
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        // 获取当前JFrame的容器
        Container container = jFrame.getContentPane();
        // 设置绝对布局
        container.setLayout(null);
        JButton jButton = new JButton("Click Dialog");
        jButton.setBounds(30,50,200,100);
        // 设置点击事件
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new MyDialog();
            }
        });
        container.add(jButton);

        jFrame.setVisible(true);

    }

    // 弹窗类实现
    static class MyDialog extends JDialog{

        public MyDialog(){
            setVisible(true);
            // 弹框中文本内容设置剧中
            JLabel dialog_jLabel = new JLabel("Dialog JLabel", SwingConstants.CENTER);
            Container container = this.getContentPane();
            container.setBackground(Color.CYAN);
            container.add(dialog_jLabel);

        }
    }

}

图标 Icon

public class ImageIconDemo extends JFrame {

    public ImageIconDemo() {
        //获取resources目录下图片url
        URL url = getClass().getClassLoader().getResource("colo.png");
      	// 读取图片变为ImageIcon,ImageIcon继承自Icon
        ImageIcon imageIcon = new ImageIcon(url);
        JLabel jLabel = new JLabel();
      	// 图片放入JLabel中
        jLabel.setIcon(imageIcon);
      // 设置居中
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);
        Container container = getContentPane();
        container.add(jLabel);


        setVisible(true);
        setBounds(100,100,400,400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }



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

JScrollPane 面板

JScrollPane,一般结合文本域(textarea)一起食用,带滚动条

public class JScrollPaneDemo extends JFrame {

    public JScrollPaneDemo(String title){
        super(title);
        Container contentPane = this.getContentPane();

        TextArea textArea = new TextArea(20,50); //设置文本域 行 列
        textArea.setText("this is JSCrollPaneDemo");    // 设置默认内容

        JScrollPane jScrollPane = new JScrollPane(textArea);

        contentPane.add(jScrollPane);

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

JRadioButton 单选框

new JRadioButton对象并加入buttongroup里即可实现单选框

public class JButtonDemo1 extends JFrame {


    public JButtonDemo1(String title) throws HeadlessException {

        super(title);

        Container contentPane = this.getContentPane();

        JRadioButton button1 = new JRadioButton("button1");
        JRadioButton button2 = new JRadioButton("button2");
        JRadioButton button3 = new JRadioButton("button3");

        ButtonGroup buttonGroup = new ButtonGroup();
        buttonGroup.add(button1);
        buttonGroup.add(button2);
        buttonGroup.add(button3);

        contentPane.add(button1);
        contentPane.add(button2);
        contentPane.add(button3);

        contentPane.setLayout(new GridLayout(3,1));
        pack();

        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

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

JCheckBox 多选框

不需要buttongroup,直接通过JCheckBox即可实现

public class JCheckBoxDemo extends JFrame {

    public JCheckBoxDemo(String title) throws HeadlessException {
        super(title);

        Container contentPane = this.getContentPane();

        JCheckBox button1 = new JCheckBox("button1");
        JCheckBox button2 = new JCheckBox("button2");

        contentPane.add(button1);
        contentPane.add(button2);

        setLayout(new FlowLayout());


        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }


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

Reference

https://iowiki.com/awt/awt_action_event.html

posted @ 2022-09-18 22:50  Zh1z3ven  阅读(191)  评论(0编辑  收藏  举报