Basic process of swing programming
First step: Get the main form
Copy Code code as follows:
JFrame the JF = new JFrame ("Demo1");
Step two: Get the container for the main form
Copy Code code as follows:
Container C = Jf.getcontentpane ();
Step three: Set the container layout
Copy Code code as follows:
C.setlayout (New FlowLayout (flowlayout.left,20,20));
Step Fourth: Add components and set component properties
Copy Code code as follows:
JLabel Label1 = new JLabel ("Hello world!");
JLabel Label2 = new JLabel ("Bye world!");
Label1.setbackground (Color.Blue);
Label1.setopaque (TRUE);
Step Fifth: Set the form properties, close the main form, exit the program
Copy Code code as follows:
Jf.setsize (200, 100); To set the main form size
Jf.setvisible (TRUE);
Jf.setresizable (FALSE);
Jf.setdefaultcloseoperation (Jframe.exit_on_close),//Set to exit the program when the form is closed
Other:
Jf.setdefaultcloseoperation (jframe.exit_on_close), or you can use the following code instead
Jf.addwindowlistener (New Windowadapter () {
@Override
public void windowclosing (WindowEvent e) {
Super.windowclosing (e);
System.exit (0);
}
});
3. A little personal learning experience:
* Learning swing, make a simple small software, not difficult, want to do good-looking, you need to have a deeper study of the layout!
* One use of swing: Although swing is a bit outdated, it can be done with gadgets, ancillary work, etc. Individuals are interested in the computer graphics interface.
The *swing component uses some design patterns, it is worth studying, it is very useful for programming!
* Learning things in your insistence, many kits are similar to a kind of profound, others can also analogy!
4. Attach a swing program learned in the Youtobe video:
Copy Code code as follows:
Package com.ting723.www;
Import Java.awt.Container;
Import Java.awt.GridLayout;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Javax.swing.ImageIcon;
Import Javax.swing.JButton;
Import Javax.swing.JFrame;
Import Javax.swing.JPanel;
public class Demo10xogame extends jframe{
JPanel JP = new JPanel ();
Public Demo10xogame () {
Container C = This.getcontentpane ();
C.add (JP);
Jp.setlayout (New GridLayout (3, 3));
for (int i = 0; i < 9; i++) {
Xobutton JB = new Xobutton ();
Jp.add (JB);
}
This.setsize (500, 500);
This.setdefaultcloseoperation (Jframe.exit_on_close);
This.setlocationrelativeto (NULL);
This.setvisible (TRUE);
}
public static void Main (string[] args) {
New Demo10xogame ();
}
}
Copy Code code as follows:
Class Xobutton extends JButton implements ActionListener {
Private ImageIcon X, O;
byte value = 0;
Public Xobutton () {
X = new ImageIcon (This.getclass (). GetResource ("X.png"));
O = new ImageIcon (This.getclass (). GetResource ("O.png"));
This.addactionlistener (this);
}
@Override
public void actionperformed (ActionEvent e) {
value++;
Value%= 3;
Switch (value) {
Case 0:
SetIcon (NULL);
Break
Case 1:
SetIcon (X);
Break
Case 2:
SetIcon (O);
}
}
}