Java graphical user interface design

xiaoxiao2021-03-06  91

As a Java programmer, people feel more and more people who use the Java development program from the forum, and it is inexhaustible. However, it is also from the forum, and most people mentioning Java is to be a network development - not that, Java can also develop applications, and can develop a beautiful graphical user interface application, that is, Windows / XWindow application. Therefore, I wrote this article, I hope to take you into the door of the Java graphical user interface design.

I. AWT and SWING AWT and SWING are the foundation of the Java design GUI user interface. Unlike the heavyweight components of the AWT, most of SWING is a lightweight component. This is this reason, Swing is almost inevitable, not only has a variety of advanced components, but also more and more easy to use. So start using AWT from the beginning, quickly turn to use Swing.

That is what AWT components have never died? Because Swing is the architecture on AWT, there is no Swing without AWT. So programmers can choose AWT or SWING according to their habits. However, it is best not to mix in both - unless the display style is different, it is also likely to cause the z-order of z-order, such as the following example:

/ *** TestPanels.java * @author Fancy * / import javax.swing *;. Import java.awt *;. Public class TestPanels extends JFrame {public TestPanels () {setDefaultCloseOperation (EXIT_ON_CLOSE); JPanel panel = new JPanel () For (int i = 0; i <2; i ) {panel.add ("Button 00" i));} jtextarea textarea = new Jtextarea (5, 15); TextArea.setLineWrap (TRUE); JScrollPane scrollPane = new JScrollPane (textArea);. getContentPane () add (panel, BorderLayout.NORTH); getContentPane () add (scrollPane, BorderLayout.CENTER);. pack ();} public static void main (String [] args) {TestPANELS TP = New TestPanels (); tp.show ();}}

Run this program and use the mouse to drag the child window named "Cover", we will find a very interesting phenomenon, as shown:

Obviously the Cover sub-window is above the Controls sub-window, but it only covers Swing Button, and there is no cover to cover the AWT Button. Look at it later, do you have such a feeling: swing button is "painting", and AWT button is "post". This is an example of the mixture of the two.

Swing components have aesthetically pleasing, easy to use, and have a large feature, and there are shortcomings - programs using Swing components are usually more slower than those using AWT components. But everyone still prefer to use Swing components, what is the reason? Because with the upgrade of computer hardware, it is no longer a problem. Conversely, users need a beautiful user interface, and developers need easy-to-use development components.

- Ok, I will teach you to develop the Java application in the graphical user interface using the Swing component. II. Framework, listener and event framework (FRAME) is the basis of the Java graphical user interface, which is our usual window, which is a typical feature of the Windows / XWindow application. Speaking of Windows / XWindow, everyone is easy to think about "event". " The Java graphical user interface is exactly the event-driven, and a variety of listeners (Listener) is responsible for capturing various events. If we need to capture and process some of a component of a component, you need to add a listener. For example, we have to change its title when it is activated in a window (JFrame), and we need to add a listener that can listen to the "Activation Window" event for this window (JFRAME object). How to add a listener? This is usually done by a method of addXXXXXListener provided by the component class. For example, JFrame is provided with an AddWindowListener method to add a window listener (WindowListener). A listener often does not only listen to an event, but can listen to related multiple events. For example, WindowListener can listen to the WindowActivate in addition to the WindowActivate, you can listen to the window shutdown event (WindowClosing). So how do these events distinguish? Relying on multiple methods of overloading listeners (CLASS), the listener can automatically call the relevant methods after a certain event. As long as we overload this method, we can handle the corresponding event. Watch an example first:

/ *** TestFrame.java * @Author fancy * / import javax.swing. *; Import java.awt.event. *; Public class testframe extends jframe {private int counter = 0; public testframe () {/ * Used anonymous Class Add a Window Listener * / AddWindowListener (New Windowadapter () {PUBLIC VOID WINDOWCLOSING (WindowEvent E) {System.Ost.Println ("EXIT WHEN CLOSED Event"); System.exit (0); // Exit Application} Public void windowActivated ("Test Frame" ; // Change window title}}); setResizable (false); // Settings window is fixed size setsize (200, 150);} public static void MAIN (String [] args) {testframe tf = new testframe (); tf.show ();}} This example, we have designed a window class (public class testframe extends jframe {...) and for this window Added a window listener (New windowAdapter () ...). And the window listener we add mainly monitors two events: Public Void WindowClosing (WindowEvent E) ...) and Window Activation (WINDOWEVENT E) ...). We exited the entire application (System.exit (0);) in the window, and we changed the title of the window (SetTitle (SETTITLE) "TEST FRAME" COUNTER );). Finally, we show an instance of this window class in the main method, run to get the result shown below: This program is running It is a frame that has not been added, that is, an empty window. So, do you know how to display a few pieces of code? I don't know if it doesn't matter. I will tell you that it is only necessary to do three things: Generate an instance (object) -> Set size -> display, corresponding, is the following three sentence:

JFrame Frame = New Jframe ("frame's title"); frame.setsize (400, 300); frame.show (); maybe you will say: The first sentence means I clear, the third sentence means I understand, why Be sure to have a second sentence? In fact, I think that I will understand it. Can you draw a rectangle that can't have a size? Can you draw it? No. Similarly, there is no size window, how to display? So we need to set size with the setsize (int width) method. We have another way: use JFrame's PACK () method to make it adapt to a size. Pack () is satisfactory in most, but sometimes it will make you smile - try it. In JFrame, we use the AddWindowListener method to join a listener WindowListener (New Windowadapter () ...) to listen to window events that happen on JFrame .WindowListener is an interface, in java.awt.event this package, but In the above example, I didn't use WindowListener, but use WindowsAdapter. What is going on? Windowadapter is a simplest implementation of the WindowsListener interface and is also in the package java.awt.event. If we use the WindowListener generated directly An anonymous class requires every method of it (a total of 7). But Windowadapter as the simplest implementation of WindowListener, has implemented each method of it is empty method (ie, only empty statements, or no statements ). With Windowadapter only need to overload the possible method (only 2 in the previous example), do not need to implement each method. Advantages obvious - reduce the amount of code. Window events occurred on JFrame (WindowEvent) comprising: a trigger windowClosed (WindowEvent e) window trigger trigger trigger loses focus windowDeactivated (WindowEvent e) window is closed windowClosing (WindowEvent e) window then closed to give focus windowActivated (WindowEvent e) window windowDeiconified (WindowEvent e) windowIconified ( The WindowEvent E) Windowpendeend (WindowEvent E) window is opened after opening two methods. If you are running back and forth between the previous example, you can use ALT in the Windows operating system TAB to switch) ... Try, what do you find? Is there a number on the title of our sample window to be added, this is settitle in the WindowActivated event ("Test Frame" COUNTER ); credit. And another event The system.exit (0) in WindowClosing is processed to ensure that the current Java application is exited when the window is turned off. What will I do if I don't do this? After the test, you will find that the window is closed, but the program is not over, but at this time, there is no other way in addition to using ^ C forced.

So, this is very important: If you want to quit the app when you close the window, you need your own write code to handle the WindowClosing event. ...... Nothing, there is another simple way to let JFrame handle this thing - you only need to call JFRAME's setDefaultcloseOperation: frame.setdefaultcloseOperation (jframe.exit_on_close); we can be in the JFrame object Add AWT or SWING components. However, although it has an Add method, it cannot be used directly to add components, otherwise it will throw an exception - do not believe it. There is only one explanation for this phenomenon: JFrame is not a container, it is just a framework. So how should I add a component? JFrame has a Content PANE, and the window is displayed in this Content Pane. JFrame provides two ways: getContentPane and SetContentPane are used to get and set their Content Pane. Usually we don't need to reset the Content Pane of JFrame, just get the content PANe to add components. Such as: (new jframe ()). GetContentPane (). Add ("Test Button");

3. Button, switch button, check button, and radio button buttons are the buttons, don't even know the buttons?

Switch button, there are two buttons of two states, that is, press the status and bounce status, if the selected state or the unselected state is called.

The check button, also called the check box, and uses a small box to indicate two states.

The radio button is called the radio button, which is selected in a small round box point. Often groups appear, only one of a set of radio buttons can be selected.

What did you find? - Right, this part is in a variety of buttons, and the last three buttons have two states. Let's take a look at these buttons.

In the above figure, from top to bottom, it is the button, switch button, check button, and radio button. The icon window is the following example of the results:

/ *** TestButtons.java * @author Fancy * / import javax.swing *;. Import java.awt.event *;. Public class TestButtons {JFrame frame = new JFrame ( "Test Buttons"); JButton jButton = new JButton ( "JButton"); // button JToggleButton toggle = new JToggleButton ( "Toggle button"); // toggle button JCheckBox checkBox = new JCheckBox ( "check Box"); // check button JRadioButton radio1 = new JRadioButton ( "Radio button 1 "); // radio button JRadioButton radio2 = new JRadioButton (" radio button 2 "); JRadioButton radio3 = new JRadioButton (" radio button 3 "); JLabel label = new JLabel (" Here is Status, look here. "); // is not a button, is a static text public testButtons () {frame.setDefaultcloseOperation (jframe.exit_on_close); frame.getContentPane (). SetLayout (new java.awt.flowLayout ()); / * For general buttons Add actions Listener * / jButton.addActionListener (new actionListener () {public void actionPerformed (ActionEvent AE) {Label.Settext ("You Clicked JButton");}}); / * For the switch button Add actions listener * / Toggle.AddActionListener (New ActionListener () {public void actionperformed (ActionEvent AE) {JTOGGL EBUTTON TOGGLE = (JTogglebutton) AE.getsource (); if ("You SELECTED TOGGLE button);} else {label.settext (" You Deselected Toggle Button);}} }); / * add an entry listener * / checkBox.addItemListener (new ItemListener () {public void itemStateChanged (ItemEvent e) {JCheckBox cb = (JCheckBox) e.getSource () to check button; label.setText ( "selected Check Box is " CB.isSselected ());}}); / * Use a button group object to accommodate a set of radio buttons * / buttonGroup group = new buttonGroup (); / * Generate a new action listener object, Alternate * / ActionListener Al =

new ActionListener () {public void actionPerformed (ActionEvent ae) {JRadioButton radio = (JRadioButton) ae.getSource (); if (radio == radio1) {label.setText ( "You selected Radio Button 1");} else if ( Radio == Radio2) {label.setText ("You SELECTED RADIO Button 2);} else {label.settext (" You SELECTED RADIO Button 3);}}}; / * Add action listener for each radio button * / Radio1.addactionListener (al); radio2.addactionListener (al); Radio3.AddActionListener (AL); / * Add a radio button to the button group * / group.add (radio1); group.add (RADIO2); Frame.getContentPane (); frame.getContentPane (). add (checkbox); frame.getcontentpane (). add (checkbox); frame.getcontentpane (). add (radio1) Frame.getContentPane (). Add (radio2); frame.getContentPane (). Add (radio3); frame.getContentPane (). Add (label); Frame.setsize (200, 250);} public void show () { Frame.show (); public static void main (string [] args) {testbuttons (); tb.show ();}} In addition to the general button, the remaining three buttons have two states, ie Select (Press) Status and not select (bounce up). So how should we judge? The switch button (JTOGGLEBUTTON) provides an isselected () method to determine the current state, indicating that it is in a selected state when the return value is true (TRUE), indicating that it is in the unselected state when the return value is false (false). The check button (JCheckbox) and radiobutton are inherited from JTogGleButton, so it also has an islected () method. As in the above example, if (Toggle.isSelected ()) {..., etc..

The radio button is determined by its own characteristics that they must appear, and there can be only one group can be selected. So we need to manage it with a special class --ButtonGroup. In multiple radio buttons added to ButtonGroup, if there is a selected, other radio buttons in the same group are automatically changed to the unselected state. Add a button to ButtonGroup, which is using its add method, Group.Add (Radio1) in the above example;

Since we have added multiple radio buttons to a buttonGroup, then we can add a button object that contains multiple radio buttons to the Content Pane of JFrame to achieve the purpose of adding all of the radio buttons. ? No! ButtonGroup is not a displayable component that is for management. So, when adding a group of Jradiobutton to JFrame, you need one to add JRADIOBUTTON instead of increasing a ButtonGroup. In the above example, Jlabel is used, which is not a button, but a static text component, mainly used to display the prompt text. To get a JLabel object, you can use its getText () method; in turn, you should use the text content displayed by a JLabel object, you should use its settext (String text) method, such as label.setText in the above example ("You SELECTED TOGGLE button";

In fact, these two methods can also be used for JButton and other classes. For example, in the previous example we use new jbutton ("jButton") to construct a button JButton if you use jButton.getText () to get the string "jButton". JButton.Settext ("a Button"), you can change the text displayed on the button to "a Button". This two code is not written, you can try it yourself.

A large number of actionListener is used in a large number of acts. ActionListener only monitors an event, which is triggered when an action is generated on its related components, so it is called action event. ActionListener only needs to be implemented, it is ActionPerformed (ActionEvent AE). The button, the switch button, and the radio button are clicked, and the action will be sent to cause the action listener to call the ActionPerformed method. So if you want to do anything after clicking the button, you should have an actionListener's ActionPerformed method. Various buttons provide the AddActionListener method to add actions listener.

The check box is special. Although it also has the AddActionListener method, it means that the action listener can be used, but you will find a motion listener after use. why? It turns out that click on a check button, the trigger is not an action event, but is an itemStateChanged event in an entry event (itemStateChange) event, which is listened by the entry listener (ItemListener), and the appropriate method of reload is itemStateChanged ItemListener. method.

In the above example, we add an ACTIONListener named Al to each radio button, how to determine which radio button triggered the event and listened by the AL? We can get the trigger event radio button from the getSource () method of ActionEvent. Since getSource () returned is an Object reference, although this reference points to an instance of a radio button, we still need to convert this type of type to JRADIOBUTTON, as in the above example: jradiobutton radio = (JRADIOBUTTON) AE. GetSource () ;, only so that we can call JRADIOBUTTON to have a way to object. At the same time, it is also necessary to explain that each radio button can add a separate ActionListener instance without having to add the same. The same reason, several components of the ActionListener need to be added without coherent, or add the same anctionsListener instance. The key is to overload the programmer's overloading of the ActionPerformed method. For example, the code below adds the same action listener instance for a JButton object and a JRADIOBUTTON object:

/ *** Test.java * @Author fancy * / import javax.swing. *; Import java.awt.event. *; Public class test {jButton B; JRADIOBUTTON RB; public test () {jframe f = new jframe "TEST"); f.setdefaultcloseOperation (jframe.exit_on_close); F.GetContentPane (). SetLayout (new java.awt.flowLayout ()); b = new jbutton ("jbutton"); RB = New Jradiobutton ("Radiobutton" ); ActionListener a = new actionListener () {public void actionPerformed (AE.GetSource () == b) {system.out.println ("You Clicked the jbutton");} else {system.out .println ("You Clicked The Radiobutton);}}}; B.AddActionListener (A); Rb.AddActionListener (A); F.GetContentPane (); add (b); f.getContentPane (). Add (rb) F.PACK (); f.show (); public static void main (string [] args) {new test ();}}

After running the program, click two buttons, according to the corresponding, the console can be obtained as follows:

You Clicked the jbutton

You Clicked The Radiobutton

This shows that multiple unused components adding the same listener is feasible - but provided that these components can add this listener.

IV. Text input box, password input box text input box includes two, single-line text input box (JTextField) and multi-line text input boxes (JTextArea). The password input box has only one (JPasswordfield). JPasswordField is a subclass of JtextField, and its main difference is that JPasswordfield does not display things that users entered, but only one fixed character set by the programmer, such as '*'. The following example diagrams and code are examples of jtextfield, jpasswordfield, and jtextarea:

/ ** * TestTexts.java * @author Fancy * / import javax.swing *;. Import javax.swing.event *;. Public class TestTexts extends JFrame {private JLabel label = new JLabel ( "Status"); private JTextField textField ; private JPasswordField pwdField; private JTextArea textArea; public TestTexts () {super ( "Test Texts"); setDefaultCloseOperation (EXIT_ON_CLOSE); getContentPane () setLayout (new java.awt.FlowLayout ());. textField = new JTextField (15) ; / * Listening Text Cursor Mobile Event * / TextField.addcaretListener (New CareTlistener () {Public Void CaretUpdate (CareTevent E) {// If you change the content, you can update the contents of Label display instantly Label.SetText (TextField.getText (TEXTFIELD.GETTEXT ));}}); Pwdfield = new jpasswordfield (15); pwdfield.sechochar ('#'); Textarea = New Jtextarea (5, 15); TextArea.setLineWrap (TRUE); getContentPane (); add (textfield); add getContentPane (). Add (pwdfield); getContentPane (). add (textarea); getContentPane (). Add (label); setsize (200, 200);} public static void main (string [] args) {testtexts TT = New TestTexts (); tt.show ();}} In the above example, we constructed a single line text box with a width of 15 characters (TextField = New JtextField (15);), and add a CaretListener with the AddCaretListener method .addcaretlistener ...). CaretListener listens to the mobile event of the text cursor. This event is triggered when the user moves the text cursor in the JTextField when the user moves the text cursor. We need to overload CaretUpdate (CareTevent E) to process events (Public Void CaretUpdate (CareTevent E) ...). This way, we can do things in the onchange event similar to the TEXTBOX in VB. JTextField has 5 constructor, usually used four: jtextfield () Jtextfield (int columns), such as TEXTFIELD = New JtextField (15); jtextfield (String text) JtextField (String text, int columns) where the parameter text is The initial content of a single line text box, and columns specifies the width of the single line text box and characterized by characters.

The text content in JtextField can be obtained with the getText () method. You can also use the setText method to specify the text content in jtextfield. JPasswordfield is a subclass of JtextField, and its constructor is also similar. JPasswordfield provides a Setechochar (CHAR CH) method to hide the character displayed, the default is '*' character, set to '#' characters (PWDField.sechochar ('#') in the previous example;). Like JTextField, JPasswordField also uses the GetText method and setText or set text content (of course, it is hidden on the user interface). JtextField is a single line text box that cannot be displayed multi-line text. If you want to display multiple lines, you have to use multiple lines of text box Jtextarea. Jtextarea has six construction methods, commonly used: Jtextarea () Jtextarea (int Rows, int columns) jtextarea (String text) jtextarea (String text, int rings, int columns) Text is the initial text content of Jtextarea; Rows is JTextarea's height, in behavioral unit; columns is the width of Jtextarea, with characters. As described in the above example, a multi-line text box of 15 characters is constructed (Textarea = New Jtextarea (5, 15);). The multi-line text box is not automatically folded by default (but you can enter the Enter Runline), we can use the JTextArea's setLineWrap method setting whether to allow automatic folding. SetLineWrap (TRUE) is allowed to automatically fold, setLineWrap (false) is not allowed to fold automatic folding. The multi-line text box will automatically expand the size according to the content input, do not believe it, do an experiment yourself - if you don't fold it automatically, then the width of the multi-line text box is determined by the longest line; if the data exceeds the pre- The number of lines set, the multi-line text box will expand its own height adaptation. In other words, the multi-line text box does not automatically generate scroll bars. How to do? Tell the scroll pane (jscrollpane), you will know. The textual content of the multi-line text box can also be done using GetText and SetText.

V. Switch, Scrolling Pane and Layout Management pane (JScrollpane) A large number of arrangements and arrangements for various components on the window in the graphical user interface design. The so-called arrangement and arrangement here is the layout, so I have to talk about the layout first. Components that will be added to the container (usually a window, etc.) are placed in a certain order and rule, making it more beautiful, which is the layout. The layout is managed by the Layout Manager. So, when should we use the layout manager? Which layout manager is applied? How do you use the layout manager? Often, we design a window, which is to add a number of components. To manage the layout of these management, we will use the layout manager. For example, design a simple editor, just put two buttons and a multi-line text box in this editor. These components are arbitrarily arranged by Java yourself? Or is it more standardized according to a certain positional relationship? Of course, the latter should be selected. So, in order to arrange these components in accordance with a certain location relationship, we need to use the layout manager. Then we encountered a choice - which layout manager used. To this end, we must first know what layout manager, what is the layout characteristics. Common layout managers are: flowLayout, BorderLayout, GridLayout, BoxLayout, etc., where FlowLayout and BorderLayout are most commonly used. This article mainly talks about these two layout managers. The following list describes their layout features:

Layout Manager layout Features FlowLayout sequentially in order from left to right from top to bottom, one line can not be put to the next line to continue BorderLayout to place the component according to Dong, South, West, North, and China five areas Up to one component GridLayout is placed in each direction like a frameless table, and one component BoxLayout is placed in a row or a box, and one component in each box is the above-mentioned editor. For example, if you select FlowLayout, then two buttons and a multi-line text box will be arranged in one line - of course, this is a wide enough condition; if the window is slightly narrow, it may be divided into two lines, and the first line has two A button, while the second line is multi-line text box - this is the ideal situation; if the window is narrow, it may be arranged in three lines, the first line and the second line are placed, and the third line is placed. Multi-line text box. Therefore, if the window size can be changed, the positional relationship between the three components may also vary with the change in the size of the window. So FlowLayout is not applicable. In fact, in the routines mentioned above, most of them use FlowLayout, which is because we don't require the layout of the component. What is the situation in BorderLayout? We can try to join a pane (JPANEL, explain later), and place the two buttons, then add this pane to the north of BorderLayout (ie, the upper part); add the multi-line text box to the middle of BorderLayout . The results are the most ideal situation similar to the second possibility of using FlowLayout. Moreover, if the window size is changed, their positional relationship is still the relationship between the North -, will not change. The rest of the two layout managers, the cooperation of the pane, can also arrange the three components required for the above editor. But because their use is slightly complicated, they will not talk. Let's talk about how to use FlowLayout and BorderLayout. Any layout manager needs to be used on the container, such as the Content Pane of JFrame and the JPANEL, which you want to say, are contained. The container assembly provides a setLayout method, which is used to change its layout manager. By default, JFrame's Content Pane is used by BorderLayout, and JPanel is using FlowLayout. But no matter what, we can call their setLayout methods to change its layout manager. For example, in the editor described above, we must use Border.getContentPane (). SetLayout (new borderlayout ()); setLayout ()); setLayout ()); Object. Then, we have ended the direct operation of the layout manager, and the remaining only needs to add components to the container. If you use flowLayout, we only need to add components using the container's Add (Component C) method. However, if you use BorderLayout, it is not the same because you want to design it to which area added to the component. Then we add components using the container's Add (Component C, Object O) method, the second parameter of the method is to specify the added area. For example, in the above editor to add a multi-line text box to the middle of BorderLayout, you can use Frame.getContentPane (). Add (New Jtextarea (5, 15), BorderLayout.center).

The five areas of BorderLayout are described in the following five constants: BorderLayout.east East BorderLayout.South South BorderLayout.west West BorderLayout.North North BorderLayout.Center has already mentioned using JPANEL. As a container, JPANel can be included in some components, then add this JPanel object as a component to another container (called parent container). What is the benefit of this feature? Isn't it possible to add one component in a zone that mentioned BorderLayout? But our editor needs to add two buttons to its north, what should I do? In the above example, we use a JPanel to include these two buttons, then add this JPanel object as a component to the setup layout manager to BorderLayout's Content Pane. When it comes to the layout characteristics of each layout manager, almost every area can only add a component, then we want to add multiple components to a zone, you will use JPanel. If you haven't understood it, you may easily understand it later. And what about scrolling panes (jscrollpane)? It is a container that can generate scroll bars, usually only one component, and automatically generates a scroll bar according to the size of this component. For example, when JTextArea is mentioned above, JTextAera will automatically expand the size with the user input, it is easy to break the layout of each component. However, if we are inclusing it in a scroll pane, its extension will not directly reflect the size of the size, and will reflect on the scroll bar of the scroll pane, and will not break the layout of each component. . The later example will make you clear. Is it waiting for an example? Well, the examples: / ** * TestPanels.java * @author Fancy * / import javax.swing *; import java.awt *; public class TestPanels extends JFrame {public TestPanels () {setDefaultCloseOperation (EXIT_ON_CLOSE); JPanel.. Panel = new jPanel (); for (int i = 0; i <2; i ) {panel.add ("Button 00" i));} jtdextarea textarea = New jTextarea (5, 15); Textarea .setLineWrap (true); JScrollPane scrollPane = new JScrollPane (textArea); getContentPane () add (panel, BorderLayout.NORTH);.. getContentPane () add (scrollPane, BorderLayout.CENTER); pack ();} public static void main (String [] args) {TestPANELS TP = New TestPanels (); tp.show ();} This example is the following figure, it is the result we want - the above two buttons, below is a scrolling Multi-line text box:

转载请注明原文地址:https://www.9cbs.com/read-95298.html

New Post(0)