Java program development and learning components and event handling

(Study reference book: Java2 practical tutorial fifth edition)

One, GUI programming

Container class (Container) and component class (Component). The JComponent class in the javax.swing package is a direct subclass of the Container class in the java.awt package, and an indirect subclass of the Component class in the java.awt package. Basic knowledge points of GUI programming:

  • Java calls an object created by a subclass or indirect subclass of the Component class as a component
  • Java calls the object created by a subclass or indirect subclass of Container a container
  • You can add components to the container. The Container class provides a public method add(), a container can call this method to add components to the container.
  • The container calls the removeAll() method to remove all components in the container, and calls the remove (Component c) method to remove the component specified by the parameter c.
  • The container itself is also a component, so you can add a container to another container to achieve container nesting.
  • Whenever you add a new component to the container or remove a component, you should let the container call the validate() method to ensure that the components in the container can be displayed correctly.

Second, the window

GUI-based applications can provide a container that can directly interact with the operating system. The container can be directly displayed and drawn on the platform (display) controlled by the operating system. Such a container is called the bottom container in GUI design. The object created by the JFrame class provided by Java is a low-level container, commonly known as a window. (The object created by the JDialog class is also a low-level container, commonly known as a dialog box.) When you need a window, you can use JFrame or its subclasses to create an object.
(1) Commonly used methods of JFrame:

	JFrame()创建一个无标题的窗口
	
	JFrame(String s)创建标题为s的窗口
	
	public void setBounds(int a,int b,int width,int height)设置窗口的初始位置为(a,b),即距屏幕左边a个像素,距屏幕上方b个像素,窗口的宽是width,高是height
	
	public void setSize(int width,int height)设置窗口的大小宽是width,高是height
	
	public void setLocation(int x,int y)设置窗口的位置,默认位置是(00public void setVisible(boolean b)设置窗口是否可见,窗口默认不可见
	
	public void setResizable(boolean b)设置窗口是否可调整大小,默认可调整大小
	
	public void dispose()撤销当前窗口,并释放当前窗口所使用的资源
	
	public void setExtendedState(int state)设置窗口的扩展状态,其中参数state取JFrame类中的·	下列类常量:
	MAXIMIZED_HORIZ 水平方向最大化
	MAXIMIZED_VERT 垂直方法最大化
	MAXIMIZED_BOTH 水平垂直方向都最大化
	
	public void setDefaultCloseOperation(int operation)设置单击窗体右上角关闭图标后,程序会做出怎样的处理。其中参数operation取JFrame类中int static常量:
	DO_NOTHING_ON_CLOSE 什么也不做
	HIDE_ON_CLOSE 隐藏当前窗口
	DISPOSE_ON_CLOSE 隐藏当前窗口,并释放窗体占有的其他资源
	EXIT_ON_CLOSE 结束窗口所在的应用程序

(2) Menu bar, menu and menu item
These three components are commonly used in windows. The menu is placed in the menu bar, and the menu item is placed in the menu .

  1. Menu bar: JMenubar, a subclass of the JComponent class, is responsible for creating a menu bar, that is, an object created by JMenubar is a menu bar. JFrame has a method to place the menu bar on the menu:
    setJMenuBar(JMenuBar bar) This method adds the menu bar to the top of the window, only one menu bar can be added to the window
  2. Menu: JMenu, a subclass of JComponent, is responsible for creating menus, that is, an object created by JMenu is a menu
  3. Menu item: JMenuItem, a subclass of the JComponent class, is responsible for creating menu items, that is, an object created by JMenuItem is a menu item
  4. Embedded submenu: JMenu is a subclass of JMeunItem, so the menu itself is also a menu item. When a menu is added to a menu as a menu item, the added menu is called a submenu
  5. Icon on the menu: In order to make the menu item have an icon, you can use the icon class Icon to declare an icon, and then use its subclass ImageIcon class to create an icon. Then the menu item calls the setIcon(Icon
    icon) method to set the icon as the parameter icon

Three, common components and layout

(1) Common components: all subclasses of JComponent

JTextField 文本框,允许用户在文本框输入单行文本

JTextArea 文本区,允许用户在文本区输入多行文本

JButton 按钮,允许用户单击按钮

JLabel 标签,标签为用户提供提示信息

JCheckBox 复选框,为用户提供多项选择,并提供两种状态,一种是选中,一种是未选中,用户通过单击该组件切换状态

JRadioButton 单选按钮,为用户提供单项选择

JComboBox 下拉列表,为用户提供可单项选择的列表

JPasswordField 密码框,允许用户在框内输入单行密码,密码的默认回显字符是*。可以使用setEchoChar(char c)重新设置回显字符,调用char[] getPassword()方法返回用户在密码框中输入的密码。

(2) Common containers: JComponent specifically provides some containers that are often used to add components. Compared with the JFrame bottom container, these containers are often called intermediate containers. The intermediate container must be added to the bottom container to function.

JPanel 面板,创建有个面板后,再向其中添加组件,然后把这个面板添加到其他容器中。JPanel面板的默认布局是FlowLayout布局

JTabbedPane 选项卡窗口,当用户向其中添加一个组件时,选项卡窗口自动为该组件指定一个对应的选项卡,即让一个选项卡对应一个组件。各个选项卡对应 的组件层叠式放入该容器中,当用户单击选项卡时,容器会显示选项卡对应的组件。选项卡默认在该容器的顶部,从左向右依次排列。使用add(String text,Component c);方法将组件c添加到选项卡容器中去,并且对应文本提示是text。

JScrollPane 滚动窗格,只可以添加一个组件,可以把组件放到一个滚动窗格中,然后通过滚动条来观看该组件比如JTextArea不自带滚动条,因此把文本区放到滚动窗口中:JScrollPane scroll = new JScrollPane(JTextArea);

JSplitPane 拆分窗格,是被分成两部分的容器。具有水平拆分和垂直拆分。水平拆分窗口就是左右各一组件,中间用可以水平移动的拆分线隔。垂直拆分同理。
两个常用构造方法:
JSplitPane(int a,Component b,Component c);参数a取该类的静态常量HORIZONTAL_SPLIT或VERTICAL_SPLIT,决定是水平还是垂直
JSplitPane(int a,boolean b,Component c,Component d);参数a同上决定方向,参数b决定当拆分线移动时,组件是否连续变化(true是连续)

JLayeredPane 分层窗格,如果添加到容器的组件经常需要处理重叠问题,就可以考虑将组件添加到分层窗格中。分层窗格分为5层,使用add(Jcomponentcom,int layer)添加组件com,并指定com所在的层。layer的取值是该类中的类常量:DEFAULT_LAYER(最底层),PALETTE_LAYER, MODAL_LAYER,POPUP_LAYER,DRAG_LAYER(最上层)。
如果分层窗口添加了多个组件,当用户用鼠标移动一组件时,可以把该组件放到最上层。添加到同一层的组件,如果发生重叠,后添加的会遮挡先添加的组件。分层窗格调用public void setLayer(Component c,int layer)可以重新设置组件c所在的层,调用public int getLayer(Component c)可以获取c所在的层数。

(3) Common layout: The layout can control the position of the component in the container. How to set the layout:setLayout(布局对象);

FlowLayout 常用构造方法FlowLayout();可以创建一个居中对齐的布局对象使用add方法将组件顺序添加到容器中,组件按照先后顺序从左到右排列,一行排满后就转到下一行继续从左到右排列。组件的大小默认为最佳大小,如需调整需调用public void setPreferredSize(new Dimension(int x,int y))。调用setAlignment(int align)方法可以重新设置布局的对齐方式,其中参数align取值FlowLayout.LEFT、FlowLayout.CENTER、FlowLayout.RUGHT。

BorderLayout 使用这种布局的容器将空间简单分为东西南北中5个区域,每一个添加的组件应该指明添加到哪个区域中。区域由静态常量表示:CENTER、NORTH、SOUTH、WEST、EAST例:将组件b添加到使用该布局的容器con中:con.add(b,BorderLayout.CENTER);

CardLayout  使用该布局的容器可以容纳多个组件,这些组件被层叠放入容器中,最先加入的容器是第一张(最上面),依次向下排列。该布局的特点是:同一时刻容器只能从这些组件中选一个出来显示。假设有一个容器con,使用步骤如下:
(1)创建CardLayout对象作为布局:CardLayout card = new CardLayout();
(2)为容器设置布局:con.setLayout(card)
(3)容器调用add(String s,Component b)将组件b加入容器,给出代号s(不是组件的名字)
(4)用代号显示组件:card.show(con,s);也可按顺序显示

GridLayout  使用较多的布局编辑器,把容器划分为若干行乘若干行的网格区域。组件位于每一个小格中,调用方法add(Component c)将组件c加入容器

null 空布局可以准确定位组件在容器内的大小和位置。setBounds(int a,int b,int width,int height)方法是所有组件都拥有的一个方法。使用方法:
(1)设置容器p为空布局:p.setLayout(null)
(2)添加组件:p.add(Component c)
(3)设置大小和位置:c.setBounds(int a,int b,int width,int height)

BoxLayout 盒式容器,可以利用容器的嵌套,将某个容器嵌入几个盒式容器,达到布局目的。使用静态方法createHorizontaBox()获得一个行型盒式容器,createVerticalBox获得一个列型盒式容器。使用水平支撑和垂直支撑控制布局容器和组件之间的距离。createHorizontalStrut(int width)得到一个不可见的水平支撑,宽度为width;createVerticalStrut(int height)得到一个不可见的垂直支撑,高度为height。

Four, handling events

The program responds to the user's operations on the interface to achieve a specific task called handling events.
(1) Event processing mode
Event source : Objects that can generate events can be called event sources, such as text boxes, buttons, and drop-down lists. The event source must be an object, and this object must be an object that Java thinks can happen.
Monitor : An object is needed to monitor the source of the event in order to deal with the event that occurs. The event source registers an object as its own monitor by calling the corresponding method. The user's corresponding operation will cause the corresponding event to occur, and notify the monitor to make the corresponding treatment.
Interface for handling events : A monitor is an object. In order to process events from the event source, the monitor will automatically call a method. Java stipulates that: in order for the monitor to process events from the event source, the class that created the monitor must implement the corresponding interface, and the monitor calls the interface method overridden by the class when the event occurs.

(2) ActionEvent event
ActionEvent event source : text boxes, buttons, menu items, password boxes and radio buttons can all trigger ActionEvent events, that is, they can all become the event source of ActionEvent events.
Registering a monitor : Java stipulates that components that can trigger ActionEvent events use the method addAction Listener (ActionListener listen) (the parameter type is an interface) to register an instance of a class that implements the ActionListener interface as a monitor of the event source.
ActionListener interface : After the event source triggers the ActionEvent event, the monitor calls action Performed (ActionEvent e) to process the event.
Methods in the ActionEvent class: There are two common methods:

1public Object getSource() 该方法被ActionEvent事件对象调用后可以获取ActionEvent事件的事件源对象的引用,即getSource()方法可以将事件源上转型为Object对象,并返回这个上转型对象的引用。
(2public String getActionCommand() ActionEvent对象调用该方法可以获取发生ActionEvent事件时,和该事件相关的一个命令。

(3) ItemEvent event
ItemEvent event source : select box, drop-down list can trigger ItemEvent event. The change of the selection state of the select box and the confirm selection of each item in the drop-down list can trigger the event.
Registering a monitor : The component that can trigger the event uses addItemListener (ItemListener listen) to register an instance of the class that implements the ItemListener interface as the monitor of the event source.
ItemLisenter interface : After the event source triggers the event, the monitor will call the only method public void itemStateChanged(ItemEvent e) in this interface to process the event.

(4) DocumentEvent event
Document event source : the text area contains an instance that implements the Document interface, which is called the document maintained by the text. The document can trigger the DocumentEvent event, and the text area calls the get Document method to return the maintained document.
Register the monitor : The event source that can trigger the event uses addDocumentListener (DocumentLis tener listen) to register the instance of the class that implements the DocumentListener interface as the monitor of the event source.
DocumentListener interface : This interface has three methods:

public void changedUpdate(DocumentEvent e) //变化更新
public void removeUpdate(DocumentEvent e) //删除更新
public void insertUpdate(DocumentEvent e) //输入更新	

After the event source triggers the file event, the monitor will call the corresponding method in the interface to handle the event.

(5) MouseEvent event
Any component can trigger a mouse event. So the MouseEvent class automatically creates an event object. The method of event source monitor is addMouseListener(MouseListener listener).
Use MouseListener interface to handle mouse events : This interface can handle mouse operations from five trigger event sources: press, release, click, enter, and exit.
Important methods of MouseEvent class:

getX() 获取鼠标指针在事件源坐标系中的x坐标
getY() 获取鼠标指针在事件源坐标系中的y坐标
getModifiers() 获取鼠标的左键或右键。分别用InputEvent类中的常量BUTTON1_MASK和BUTTON3_MASK表示
getClickCount() 获取鼠标被单击的次数
getSource() 获取发生鼠标事件的事件源
MouseListener的重要方法:
mousePressed(MouseEvent e) 处理在组件上按下鼠标触发的鼠标事件
mouseReleased(MouseEvent e) 处理在组件上释放鼠标键触发的鼠标操作
mouseEntered(MouseEvent e) 处理鼠标进入组件触发的鼠标事件
mouseExited(MouseEvent e) 处理鼠标离开组件触发的鼠标事件
mouseClicked(MouseEvent e) 处理在组件上单击鼠标键触发的鼠标事件

Important methods of MouseListener:

mousePressed(MouseEvent e) 处理在组件上按下鼠标触发的鼠标事件
mouseReleased(MouseEvent e) 处理在组件上释放鼠标键触发的鼠标操作
mouseEntered(MouseEvent e) 处理鼠标进入组件触发的鼠标事件
mouseExited(MouseEvent e) 处理鼠标离开组件触发的鼠标事件
mouseClicked(MouseEvent e) 处理在组件上单击鼠标键触发的鼠标事件

Use MouseMotionListener interface to handle mouse events : This interface handles the operations triggered by dragging and moving the mouse on the event source. The commonly used methods are:

addMouseMotionListener(MouseMotionListener listener) 注册监视器 
mouseDragged(MouseEvent e) 处理拖动鼠标触发的事件
mouseMoved(MouseEvent e) 处理鼠标移动触发的事件

(6) Focus events
Components can trigger focus events. The component can be used to addFocusListener(FocusListener listener)register as a focus event monitor. After the component gets the focus monitor, the FocusEvent event will be triggered if there is a change in the input focus of the component. The class that creates the monitor must implement the FocusListener interface, which has two methods:

public void focusGained(FocusEvent e) 组件从无输入焦点变为有输入焦点时,监视器调用该方法
public void focusLost(FocusEvent e) 组件从有输入焦点变为无输入焦点时,监视器调用该方法

The user clicks a component to get the focus, while other components will also lose the focus . A component can call a public boolean requestFocusInWindow()method to get the input focus

(7) Keyboard events
Press, release, or hit a key on the keyboard to trigger a keyboard event. Use the KeyListener interface to handle keyboard events. You can use addKeyListener (KeyListener e) to register the monitor. The interface has the following three methods:

public void keyPressed(KeyEvent e) 处理按下键盘触发的键盘事件
public void keyTyped(KeyEvent e) 处理敲击(按下又释放)触发的事件
public void keyReleased(KeyEvent e) 处理释放键盘触发的键盘事件

Use the public int getKeyCode() [return key code value] or public char getKeyChar() [return the character on the key] method of the KeyEvent class to determine which key is pressed, tapped and released

(8) Window event
JFrame is a subclass of Window, and all objects created by fanshiWindow subclass can have Window Event events.
WindowListener interface : When a window is opened, closed, iconized... a window event is triggered, that is, WindowEvent creates a window event object. Call the getWindow() method to get the window where the window event occurred. The window uses the addWindowlistener method to obtain the monitor. The class of the object creating the monitor must implement the WindowListener interface, which has 7 methods:

public void windowActivated(WindowEvent e) 窗口从激活到未激活状态调用该方法。
public void windowDeactivated(WindowEvent e)窗口从激活状态到未激活状态调用该方法。
public void windowClosing(WindowEvent e) 当窗口正在关闭时,调用该方法。
public void windowClosed(WindowEvent e) 当窗口关闭后,调用该方法。
public void windowIconified(WindowEvent e) 当窗口图标化后,调用该方法。
public void windowDeiconified(WindowEvent e) 当窗口撤销图标化后,调用该方法。
public void windowOpened(WindowEvent e) 当窗口打开时,调用该方法。
在调用图标化时,会同时调用撤销激活方法;在撤销图标化时,会同时调用激活方法。关闭窗口时,监视器首先调用正在关闭方法再调用关闭后方法。

WindowAdapter adapter : When Java provides more than one method for handling events, Java provides an adapter class accordingly. The adapter has implemented the corresponding interface, so you can directly use the object created by the subclass of the adapter class as the monitor, and override the required method in the subclass.

(9) An anonymous class instance or window is used as a monitor
An anonymous class instance is used as a monitor : If an instance of an internal class is used as a monitor, when an event occurs, the monitor is easier to operate the members of the external embedded class where the event source is located. It is not necessary to pass the reference of the object to the monitor.
Window as a monitor : If the window where the component is located is used as a monitor, the monitor can conveniently operate other members of the window.

Five, dialog box

The JDialog class and the JFrame class are both subclasses of Window, and the instances of both are the underlying container. There are two types of dialog boxes: modeless and modal. When a modal dialog box is activated, other windows of the program where the dialog box is located cannot be activated. There is no such restriction if there is no mode. (Usually before performing an important operation, a modal dialog box pops up to indicate the importance of the operation)
(1) Message dialog box
This dialog box is a modal dialog box. Before performing an important operation, it is best to pop up a message dialog box frame. Use the static method of the JOptionPane class to create a message dialog: the public static void showMessageDialog (Component parentComponent,String message,String title,int messageType)
first parameter specifies the position of the dialog when it is visible, the second parameter specifies the information displayed in the dialog, the third parameter specifies the title, and the fourth parameter takes the value of JOptionPane Class constants in the class, used to give the appearance of the dialog box:INFORMATION_MESSAGE、WARNING_MESSAGE、ERROR_MESSAGE、QUESTION_MESSAGE、PLAIN_MESSAGE

(2) Input dialog box
This dialog box contains a text box for the user to enter text, confirm and cancel buttons, and is a modal dialog box. A string is required. Use the static method of the JOptionPane class to create an input dialog: the public static String showInputDialog(Component parentComponent,Object message,String title,int message)
first parameter specifies the component that the input dialog depends on, the fourth component specifies the appearance, and the constant values ​​are the same as above.

(3) Confirmation dialog box
This dialog box is a modal dialog box. The static method of the JOptionPane class creates a confirmation dialog box: the public static int showConfirmDialog(Component parentComponent,Object message,String title,int optionType)
first parameter specifies the position where the dialog box appears, and the fourth parameter can take the class constant to specify the appearance: YES_NO_OPTION、YES_NO_CANCEL_OPTION、OK_CANCEL_OPTION
this method will Returns one of the following integer values:JOptionPane.YES_OPTION、JOptionPane.NO_OPTION、JOptionPane.CANCEL_OPTION、JOptionPane.OK_OPTION、JOptionPane.CLOSED_OPTION

(4)
The static method of the color dialog box JOptionPane class creates a color dialog box: the public static Color showDialog(Component component,String title,Color initialColor)
third parameter specifies the initial color returned by the color dialog box

(5) Custom dialog box
. Create a dialog box class by creating a subclass of JDialog. An instance of this class is a dialog box. The dialog box is a container, and the default layout is BorderLayout. Two common construction methods for dialog boxes:

JDialog() 构造一个无标题的初始不可见的对话框
JDialog(JFrame owner) 构造一个无标题的初始不可见的无模式的对话框,owner是对话框所依赖的窗口。

Six, tree components and table components

(1) Tree component: The object of the JTree class is called the tree component
DefaultMutableTreeNode node : To construct a tree component, you must create a node object for it in advance. Any object created by a class that implements the MutableTreeNode interface can become a node on the tree. There is only one root node in the tree, and all other nodes lead from here. Other nodes are divided into branch nodes with child nodes and leaf nodes without child nodes. Each node has its own text label and image icon. The Default MutableTreeNode class creates nodes on the tree. The commonly used construction methods for this class are:

DefaultMutableTreeNode(Object userObject)
DefaultMutableTreeNode(Object userObject,boolean allowChildren) 

TreeSelectionEvent event on the tree: The tree component can trigger the TreeSelectionEvent event, and the tree usage addTreeSelectionListener(TreeSelectionListener listener)method gets a monitor. When the mouse clicks on the node, the monitor will automatically call the method in the interface

(2) Table components:
Three commonly used construction methods for JTable:

JTable() 创建默认的表格模型
JTable(int a,int b) 创建a行,b列的默认模型表格
JTable(Object data[][],Object columnName[]) 创建默认表格模型,并且显示由data指定的二维数组的值,其列名由columnName指定

Guess you like

Origin blog.csdn.net/YCF8746/article/details/113611894