java GUI programming

java GUI programming

awt和swing
  • awt: abstract window toolset
    • Affiliation package:java.awt
  • swing: extension of awt, not a replacement
    • Swing inherits many classes of awt, so when using swing class library indirectly uses awt class library
    • Affiliation package:javax.swing
  • Common methods in the component class:
    • String getName() Get the name of the component

    • Container getParent() Get the container that directly contains the component

    • boolean isFocusable() Determine whether the component can get focus

    • boolean isFocusOwner() Determine whether the component has the focus

    • void setEnabled(boolean b) Set whether the component is blocked (for example, if the button is false, it will be grayed out and not clickable)

    • boolean isEnabled() Determine whether the component is blocked

    • void setSize(int width,int height) Set the size of the component

    • void setVisible(boolean b) Set whether the component is visible

    • boolean isVisible() Determine whether the component is visible

    • void setLocation(int x,int y) Specify the location where the component is displayed

      • A small example
public class TestFrame {
    public static void main(String[] args) {
        //通过跟进看源码和构造器
        Frame frame=new Frame("第一个窗口");
        //设置可见性
        frame.setVisible(true);
        //窗口大小
        frame.setSize(400,400);
        //背景颜色
        frame.setBackground(new Color(56, 146, 255));
        //窗口位置
        frame.setLocation(200,200);
        //设置大小固定
        frame.setResizable();
    }
}

Insert picture description here

Steps to write GUI
  • 构造界面: Constructing component objects
    • Construct container object + construct component object + add method
  • 美化界面: Reasonable layout of container components
  • 响应界面: Add event handling mechanism to the interface
  • Some commonly used methods in the Component class
    • Common methods in the Container class:
      • Component add(Component comp) adds the component to the container
      • void remove(Component comp) Remove the component from the container
      • void setLayout(LayoutManager mgr) Set the layout of the container
    • Common methods of the Frame class:
      • void setTitle(String s) set title
      • String getTitle() Get title
    • Common methods of Label class and TextField class:
      void setText(String s) Set text information
      String getText() Get text information
    • Common methods of the Button class:
      • void setLabel(String s) Set the label information of the button, not the component name, just the content on the label instead of the button name
      • String getLabel() Get the label information of the button
  • FlowLayout layout class: components are placed in order from left to right, row by row
  • GridLayout layout class: divide the container into grids of the same size
  • Font class:Font f1=new Font(" 宋体" , Font.BOLD , 23);
package GUI;
import java.awt.*;
import javax.swing.*;

public class GuiPra extends JFrame{
    GuiPra(){
        super("练习");
    }
    public void f(){
        setSize(400,400);
        setBackground(Color.ORANGE);
        setLocation(300,300);
        setLayout(new FlowLayout());
        add(new Label("用户名:"));
        add(new JTextField(5));
        add(new Label("密码:"));
        add(new TextField(5));
        add(new JButton("登录"));
        add(new JButton("退出"));
        setVisible(true);
    }

    public static void main(String[] args) {
        new GuiPra().f();
    }
}

Insert picture description here

Note the difference between Label and JLabel: JLabel's setBackground is inherited from JComponent, while JComponent's setOpaque(boolean) is false by default, the background is transparent and the underlying pixels cannot be displayed. Therefore, if you want to use JLabel's background settings, you need to change the method to true

5 steps to create a graphical interface
  • Create JFrame form
  • Set the size, position, background layout of the form, etc.
  • Define a series of required components
  • Add the component to the form through the add method
  • Let the form display: setVisible
Delegated event handling model
  • Three elements: event source, event, event handler (listener)
  • Three steps:
    • Determine event source and event
    • Define the handler to realize the interface of related events
    • Associate event source and event handler
package Practice2;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Guipra2 extends JFrame implements ActionListener{
    private JButton bok,bexit;
    private JTextField username;
    private Label tla;
    private JPasswordField password;
    public Guipra2(){
        super("一个界面");
    }
    public void f(){
        setSize(400,400);
        setLocation(300,300);
        setBackground(Color.GRAY);
        setLayout(new FlowLayout());
        username=new JTextField(5);
        password=new JPasswordField(5);
        add(new Label("用户名:"));
        add(username);
        add(new Label("密码:"));
        add(password);
        bok=new JButton("确定");
        bexit=new JButton("退出");
        add(bok);
        add(bexit);
        add(new Label("  "));
        tla=new Label("  ");//提示信息的标签
        add(tla);
        setVisible(true);
        //GUI界面设计部分
        bexit.addActionListener(this);//建立关联
        bok.addActionListener(this);
    }
    public  void actionPerformed(ActionEvent e){
    	//发生按钮点击事件监听器必须实现与事件对应的接口AcctionListener,并且自动调用事件处理方法actionPerformed
        if (e.getSource()==bexit)
            System.exit(0);
        if (e.getActionCommand().equals("确定")){
            String KeyText=String.valueOf(password.getPassword());
            //将字符数组转换成字符串
            if(username.getText().equals("why")&&password.getPassword().equals("1234"))
                tla.setText("欢迎你");
            else
                tla.setText("用户名或者密码输入错误");
            setVisible(true);
        }
    }

    public static void main(String[] args) {
        Guipra2 g=new Guipra2();
        g.f();
    }
}


Insert picture description here

  • Note: The events that can be generated by each event source in the java class library are determined, the matching event listener interface is also determined, and the method of establishing an association with the listener is also determined. For example, the JButton object in the above example can generate an ActionEvent event, then the method to establish an association isaddActionListener(ActionListener e)
    • And there is a specific method in the listener interface, which is actually a method to complete the time processing, such as the above example public void actionPerformed(ActionEvent e)
    • To realize the closing action of the form:
      • Implement WindowListener interface
      • Rewrite the 7 methods in the interface, of which only need to usepublic void WindowClosing(WindowEvent e){System.exit(0);}
Adapter class led by window closing
  • Because the listener must implement all the abstract methods in the listener interface, it is troublesome and like the window closing only needs to use one method but has to rewrite 7 methods.
  • The second way to close the window
//定义一个内部类
class A extents WindowAdapter{
	public void WindowClosing(WindowEvent e){System.exit(0);}
	//在构造函数中加入下面语句
	this.addWindowListener(new A());
}
  • The third way to close the form
    • Since closing the window is a common feature of Frame, JFrame provides a static int constant EXIT_ON_CLOSE
JFrame f=new JFrame("why的界面");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Layout management
  • Set the layout method: void setLayout(LayoutManager m)
  • FlowLayout: Flow layout
    • By default, it is placed line by line from left to right and top to bottom
    • LEFT (left justified)
    • RIGHT (right aligned)
    • CENTER (center alignment)
    • LEADING (first alignment): mainly for English letters
    • TRAILING (tail alignment)
setLayout ( new FlowLayout( FlowLayout.RIGHT ) );
  • GridLayout: grid layout
setLayout(new GridLayout(3,2,5,10));//将容器等分成3 行*2 列个网格 ,每个网格只能放一个组件,且自动填满;网格水平间隙为5 ,纵向间隙为10,只能以行为序从左至右填写网格
  • BorderLayout: Border layout (default layout manager)
    • Divide the container into 5 areas, east, west, south, north, middle, and each area can only put one component, and it will fill up automatically可将组件放到指定区域,也可缺省某些区域
add(new JButton("EAST"),BorderLayout.EAST);

Guess you like

Origin blog.csdn.net/Phoebe4/article/details/111461400