Java from entry to the master Chapter 13 Swing Programming

table of Contents

Common Swing components

Common Forms

Components and icon labels

Common layout manager

Common panel

Button component

List of components

Text Component

Common listens for events


Common Swing components

Common Forms

Form Swing components typically associated with components and containers, so after JFrame objects created, you need to call the getContentPane () method to convert the form into a container, then adding components or layout manager is provided in the container. The vessel used to contain and display components, using the Container.add () method was added to the container assembly. Use Container.remove () remove components.

  • JFrame Form class inherits JFrame
    • Construction method
    • JFrame (); initialization is not visible, no title
    • JFrame (String title); is not visible, there is the title, use setVisible (true); visible
    • Type form is closed
    • DO_NOTHING_ON_CLOSE
    • DISPOSE_ON_CLOSE
    • HIDE_ON_CLOSE
    • EXIT_ON_CLOSE
  • JDialog form, inheriting JDialog class
    • Construction method
    • JDialog (); no title and the parent form
    • JDialog (Frame f); specified parent dialog window
    • JDialog (Frame f, boolean model); specify the parent form and the specified type of dialog box 
    • JDialog (Frame f, String title); specify the parent form and title 
    • JDialog (Frame f, String title, boolean model); specified parent form, titles and genres
package ex13_Swing;

import javax.swing.*;
import java.awt.*;

public class Example1 extends JFrame {  //定义一个类继承JFrame
    public void CreateJFrame(String title) {  //定义一个CreateJFrame方法
        JFrame jf = new JFrame(title);  //实例化一个JFrame对象
        Container container = jf.getContentPane();  //获取一个容器
        JLabel jl = new JLabel("这是一个JFrame窗体");  //创建一个JLabel标签
        jl.setHorizontalAlignment(SwingConstants.CENTER);  //使标签上的文字居中
        container.add(jl);  //将标签添加到容器中
        container.setBackground(Color.white);  //设置容器的背景颜色
        jf.setVisible(true);  //使窗体可见
        jf.setSize(200, 150);  //设置窗体大小
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);  //设置窗体关闭方式
    }

    public static void main(String[] args) {
        new Example1().CreateJFrame("创建一个JFrame窗体");
    }

}
package ex13_Swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyJDialog extends JDialog {  //创建新类继承JDialog
    public MyJDialog() {  //构造方法
        super(new MyFrame(), "第一个JDialog窗体", true);  //实例化一个JDialog对象,指定对话框的父窗体,窗体标题和类型
        Container container = getContentPane();  //创建一个容器
        container.add(new JLabel("这是一个对话框"));  //在容器中添加标签
        setSize(100, 100);
    }

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

class MyFrame extends JFrame {

    public MyFrame() {
        Container container = getContentPane();  //创建一个容器
        container.setLayout(null);
        JLabel jl = new JLabel("这是一个JFrame窗体");  //在窗体中设置标签
        jl.setHorizontalAlignment(SwingConstants.CENTER);  //设置标签的位置
        container.add(jl);
        JButton bl = new JButton("弹出对话框");  //定义一个按钮
        bl.setBounds(10, 10, 100, 21);
        bl.addActionListener(new ActionListener() {  //为按钮添加鼠标单击事件
            @Override
            public void actionPerformed(ActionEvent e) {
                new MyJDialog().setVisible(true);
            }
        });
        container.add(bl);  //将按钮添加到容器中
        container.setBackground(Color.white);  //设置容器的背景颜色
        setSize(200, 200);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setVisible(true);
    }
}

Components and icon labels

  • JLabel constructor
    • JLabel (); without icons and text
    • JLabel (Icon icon); with icons
    • JLabel (Icon icon, int aligment); with icons, horizontal alignment
    • JLabel (String text, int aligment); with text, horizontal alignment
    • JLabel (String text, Icon icon, int aligment); text, icons, horizontal alignment method
  • Use picture icon javax.swing.ImageIcon class
    • getResource java.lang.Class class () method can obtain the URL path to the resource file
//图标的使用
package ex13_Swing;

import javax.swing.*;
import java.awt.*;

public class DrawIcon implements Icon {  //实现Icon接口
    private int width;  //声明图标的宽
    private int height;  //声明图标的高

    public int getIconWidth() {  //实现getIconWidth()方法
        return this.width;
    }

    public int getIconHeight() {  //实现getIconHeight()方法
        return this.height;
    }

    public DrawIcon(int width, int height) {  //构造方法
        this.width = width;
        this.height = height;
    }

    public void paintIcon(Component arg0, Graphics arg1, int x, int y) {
        arg1.fillOval(x, y, width, height);  //绘制一个图形
    }

    public static void main(String args[]) {
        JFrame jf = new JFrame();  //创建一个JFrame窗口
        Container container = jf.getContentPane();  //创建一个容器
        container.setBackground(Color.white);
        jf.setVisible(true);
        jf.setSize(200,150);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        DrawIcon icon = new DrawIcon(15,15);  //创建标签对象
        //创建一个标签,设置标签上的文字在标签正中间
        JLabel jl = new JLabel("测试12345566661111111", icon, SwingConstants.CENTER);
        container.add(jl);  //添加到容器
    }

}
//图片图标
package ex13_Swing;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class MyImageIcon  {
    public static void main(String[] args) {
        JFrame jf = new JFrame("hi");  //创建窗体对象
        Container container = jf.getContentPane();  //创建容器
        JLabel jl = new JLabel("这是一个JFrame窗体", JLabel.CENTER);  //创建标签
        //创建图标图片的url,图片方法class文件夹下
        URL url = MyImageIcon.class.getResource("imageButton.jpg");  
        Icon icon = new ImageIcon(url);  //创建图标
        jl.setIcon(icon);  //为标签设置图标
        jl.setHorizontalAlignment(SwingConstants.CENTER);  //设置文字放在标签中间
        jl.setOpaque(false); //设置标签为不透明
        container.add(jl);  //将标签添加至容器

        jf.setSize(500,500);
        jf.setVisible(true);
        jf.setBackground(Color.blue);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

Common layout manager

  • Absolute layout
    • Container.setLayout (null); cancel layout manager
    • Setting the size and position of each container assembly; Container.setBound ()
  • Flow layout manager
    • FlowLayout(int alignment, int horizGap, int vertGap);
    • jf.setLayout (fl)
  • Border Layout Manager (Swing default)
    • Simultaneous use of the installation position and add add components
  • Grid Layout Manager
    • GridLayout (int rows, int columns, int horizGap, int vertGap); using a similar flow layout manager
//流布局管理器
package ex13_Swing;

import javax.swing.*;
import java.awt.*;

public class FlowLayoutPosition {
    public static void main(String[] args) {
        JFrame jf = new JFrame("title");  //创建JFrame对象
        Container container = jf.getContentPane();  //创建容器
        //设置jf参数
        jf.setVisible(true);
        jf.setSize(500,500);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //创建流布局管理器对象,设置对齐方式,水平间隔,垂直间隔
        FlowLayout fl = new FlowLayout(FlowLayout.RIGHT, 10,10);
        jf.setLayout(fl);
        for (int i = 0; i < 100; i++) {
            JButton jb = new JButton("button "+ i); //创建JButton对象
            container.add(jb);  //添加到容器
        }
    }
}
//边界布局管理器
package ex13_Swing;

import javax.swing.*;
import java.awt.*;

public class BorderLayoutPosition {
    public static void main(String[] args) {
        JFrame jf = new JFrame("title");  //创建JFrame对象
        Container container = jf.getContentPane();  //创建容器
        //设置jf参数
        jf.setVisible(true);
        jf.setSize(500, 500);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        BorderLayout bl = new BorderLayout();
        jf.setLayout(bl);  //默认边界布局,可以不写
        //边界布局管理器,上、下、左、右、中
        String[] border = {
                BorderLayout.CENTER,
                BorderLayout.NORTH,
                BorderLayout.SOUTH,
                BorderLayout.WEST,
                BorderLayout.EAST};
        String[] buttonName = {"center", "north", "south", "west", "east"};
        for (int i = 0; i < border.length; i++) {
            JButton jb = new JButton(buttonName[i]);
            container.add(border[i], jb);  //add()方法可以同时添加布局和组件
        }
    }

}

Common panel

Swing panel is a container class inherits from java.awt.container, can contain other components, but it must also be added to other containers

  • JPanel panel
  • JScrollPane panel scroll bars, but also a container, but only to put a component layout manager can not be used, if desired a plurality of components on a plurality of components necessary to JPanel panel, the panel is then added as a whole JPanel on the JScrollPane

 

//JPanel面板
package ex13_Swing;

import javax.swing.*;
import java.awt.*;

public class JPanelTest extends JFrame {
    public JPanelTest() {
        Container c = getContentPane();
        //将整个容器设置成2行1列的网格布局
        c.setLayout(new GridLayout(2, 2, 10, 10));
        //初始化面板,设置面板布局
        JPanel jp1 = new JPanel(new GridLayout(1, 4, 10, 10));
        JPanel jp2 = new JPanel(new GridLayout(1, 3, 10, 10));
        JPanel jp3 = new JPanel(new GridLayout(1, 2, 10, 10));
        JPanel jp4 = new JPanel(new GridLayout(1, 5, 10, 10));
        jp1.add(new JButton("1"));  //在面板中添加按钮
        jp1.add(new JButton("2"));
        jp1.add(new JButton("3"));
        jp1.add(new JButton("4"));
        jp2.add(new JButton("21"));
        jp3.add(new JButton("31"));
        jp3.add(new JButton("32"));
        jp4.add(new JButton("41"));
        jp4.add(new JButton("42"));
        jp4.add(new JButton("43"));
        c.add(jp1);  //添加面板到容器
        c.add(jp2);
        c.add(jp3);
        c.add(jp4);
        setVisible(true);
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new JPanelTest();
    }
}
//JScroll面板
package ex13_Swing;

import javax.swing.*;
import java.awt.*;

public class JScrollPaneTest extends JFrame {
    public JScrollPaneTest() {
        Container c = getContentPane();
        JTextArea jta = new JTextArea(20, 50);  //创建文本区域组件
        JScrollPane jsp = new JScrollPane(jta);  //创建JScrollPane面板对象,将文本区域组件添加上
        c.add(jsp);
        setTitle("带滚动条的文本编辑器");
        setSize(500, 500);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

Button component

  • JButton (String text, Icon icon); submit button components
  • The JRadioButton (); radio button assembly, the button to add all of the panel, the panel is added to the vessel, the group is added to all radio buttons
  • JCheckBox (); add more check boxes to a panel, you can also add a check box for each event listener

 

//提交按钮、单选按钮
package ex13_Swing;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

public class JButtonTest extends JFrame {
    public JButtonTest() {
        Container c = getContentPane();
        URL url = JButtonTest.class.getResource("imageButton.jpg");
        Icon icon = new ImageIcon(url);
        //设置布局3行2列,间隔为5
        setLayout(new GridLayout(5, 1, 5, 5));
        JButton jb1 = new JButton("button1", icon);
        JButton jb2 = new JButton("button2", icon);
        JButton jb3 = new JButton("button3", icon);
        JButton jb4 = new JButton();  //实例化一个没有文字的按钮
        add(jb1);
        add(jb2);
        add(jb3);
        add(jb4);
        jb2.setEnabled(false);  //设置按钮不可用
        jb4.setMaximumSize(new Dimension(10, 10));//设置按钮与图片大小相同
        jb4.setIcon(icon);  //为按钮设置图标
        jb4.setHideActionText(true);
        jb4.setToolTipText("图片按钮");  //设置按钮的提示文字,鼠标指向按钮时
        jb4.setBorderPainted(false);  //设置图标按钮边界不显示
        jb4.addActionListener(new ActionListener() {  //为按钮添加监听事件
            @Override
            public void actionPerformed(ActionEvent e) {
                //弹出确认对话框
                JOptionPane.showMessageDialog(null, "弹出对话框");
            }
        });
        //单选按钮组件
        JRadioButton jrb1 = new JRadioButton();
        JRadioButton jrb2 = new JRadioButton();
        JRadioButton jrb3 = new JRadioButton();
        ButtonGroup bg = new ButtonGroup();  // 添加到组后才是单选按钮
        bg.add(jrb1);
        bg.add(jrb2);
        bg.add(jrb3);
        JPanel jp = new JPanel();  //创建面板
        jp.add(jrb1);
        jp.add(jrb2);
        jp.add(jrb3);
        jp.setBorder(new TitledBorder("TitleBorder"));
        add(jp);


        setVisible(true);
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new JButtonTest();
    }
}
//复选框组件
package ex13_Swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CheckBoxTest extends JFrame {
    public CheckBoxTest() {
        Container c = getContentPane();  //创建容器
        setLayout(new BorderLayout());
        JPanel jp1 = new JPanel();  //创建面板
        JPanel jp2 = new JPanel();

        JCheckBox jc1 = new JCheckBox("1");  //创建复选框
        JCheckBox jc2 = new JCheckBox("2");
        JTextArea jt = new JTextArea(20, 20);  //创建编辑器
        final JScrollPane jsp1 = new JScrollPane(jt);  //创建滑动面板

        jp1.add(jsp1);  //面板1添加编辑器
        jp2.add(jc1);  //面板2添加复选框
        jp2.add(jc2);  //面板2添加复选框
        jc1.addActionListener(new ActionListener() {  //复选框添加监听事件
            @Override
            public void actionPerformed(ActionEvent e) {
                jt.append("复选框1被选中\n");
            }
        });
        jc2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jt.append("复选框2被选中\n");
            }
        });

        c.add(jp1, BorderLayout.NORTH);  //添加面板到容器
        c.add(jp2, BorderLayout.SOUTH);


        setSize(500, 500);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

List of components

  • Drop Down List component
    • The JComboBox (), drop-down list items can be packaged as JComBoxModel type, an array or Vector
  • Components list box
    • JList (), array, Vector type and type ListModel

Text Component

  • Text box components
    • JTextField()
  • Password box assembly
    • JPasswordField()
  • Text Field component
    • The JTextArea (); setLineWrap a class exists () method set to true, wrap

Common listens for events

  • The action listener event
    • addActionListener (new jbAction); ActionListener interface implemented within the class jbAction, the rewriting method actionPerformed
    • the addActionListener (new new ActionListen () {
      public void the actionPerformed (the ActionEvent the arg0) {
      // do something
      }}); implemented using an anonymous inner classes
  • Intersection monitor events
    • addFocusListener (FocusListener new new () {
      public void the focusLost (the FocusEvent the arg0) {// called when the assembly method loses focus
      // do something
      }
      public void the focusGained (the FocusEvent the arg0) method is called when a component obtaining focus //
      });

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Published 46 original articles · won praise 0 · Views 1025

Guess you like

Origin blog.csdn.net/weixin_37680513/article/details/103412860