Swing components are similar to AWT components, but add new methods to each component and provide more advanced components.
Basic components of Swing:
1. Button (JButton):
Buttons in Swing can display images, and the button can be set as the default icon for a window, and multiple images can be assigned to a button.
(1) Commonly used construction methods of JButton.
JButton(String text): Characters displayed on the button.
JButton(Icon icon): Display the icon on the button.
JButton(String text, Icon icon): Both icons and characters are displayed on the button.
(2). Commonly used methods:
b1.setEnabled(false); //Make the button currently unavailable
b1.setToolTipText("..."): //Set button tip text
b1.setMnemonic(KeyEvent.VK_D); // Bind b1 to the alt+D key
(3).Case code:
Copy the code code as follows:
public class JButtonExample3 extends JPanel implements ActionListener {
protected JButton b1, b2, b3;
public JButtonExample3() {
ImageIcon leftButtonIcon = createImageIcon("right.gif");
ImageIcon middleButtonIcon = createImageIcon("middle.gif");
ImageIcon rightButtonIcon = createImageIcon("left.gif");
b1 = new JButton("Invalid middle button (D)", leftButtonIcon);
b1.setVerticalTextPosition(AbstractButton.CENTER);//Horizontal center alignment
b1.setHorizontalTextPosition(AbstractButton.LEADING);//Equivalent to LEFT
b1.setMnemonic(KeyEvent.VK_D); // Bind b1 to the alt+D key
b1.setActionCommand("disable");
b2 = new JButton("M middle button", middleButtonIcon);
b2.setVerticalTextPosition(AbstractButton.BOTTOM);
b2.setHorizontalTextPosition(AbstractButton.CENTER);
b2.setMnemonic(KeyEvent.VK_M); // Bind b2 to the alt+M key
b3 = new JButton("E activates the middle button", rightButtonIcon);
b3.setMnemonic(KeyEvent.VK_E); // Bind b3 to the alt+E key
b3.setActionCommand("enable");
b3.setEnabled(false);
//Add event listeners to 1 and 3
b1.addActionListener(this);
b3.addActionListener(this);
//Set button prompt text
b1.setToolTipText("Clicking this button will invalidate the middle button!");
b2.setToolTipText("Click this button, no event occurs!");
b3.setToolTipText("Clicking this button will make the middle button effective");
//Add button to JPanel
add(b1);
add(b2);
add(b3);
}
public void actionPerformed(ActionEvent e) {
if ("disable".equals(e.getActionCommand())) {
b2.setEnabled(false);
b1.setEnabled(false);
b3.setEnabled(true);
} else {
b2.setEnabled(true);
b1.setEnabled(true);
b3.setEnabled(false);
}
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = JButtonExample3.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn′t find file: " + path);
return null;
}
}
public static void main(String[] args) {
//Set up to use the new swing interface
//Provides a hint as to whether the newly created JFrame should have the Window decorations provided for it by the current appearance (such as borders, widgets to close the window, titles, etc.).
JFrame.setDefaultLookAndFeelDecorated(true);
//Create a form
JFrame frame = new JFrame("Little Dragon Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create a panel
JButtonExample3 newContentPane = new JButtonExample3();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
// display form
frame.pack();
frame.setLocation(300, 200);
frame.setVisible(true);
}
}
Running screenshot:
2. Combo box (JComboBox):
Detailed explanation of how to use combo box (drop-down list JComboBox) and examples:
Construction method:
* JComboBox() creates a JComboBox component.
* JComboBox(ComboBoxModel model) Create a JComboBox component based on the model.
* JComboBox(Objext[] items) uses array objects to create a JComboBox component.
* JComboBox(Vector items) uses Vector objects to create a JComboBox component.
Commonly used methods:
....
Comprehensive example:
Copy the code code as follows:
import java.awt.*; /* Contains all classes for creating user interfaces and drawing graphics images. */
import javax.swing.*; /* Provide a set of "lightweight" components and try to make these components work the same way on all platforms */
public class JComboBoxDemo extends JFrame {
public JComboBoxDemo() {
/*
* Container is the parent class of all containers and a subclass of the Java language component class Component. A container is a component that has the function of accommodating other components and containers.
* The most basic element of a Java graphical user interface is a component. A component is an object that can be displayed on the screen graphically and interact with the user, such as a button, a text box, etc.
* In Java, components are usually placed in a certain container and the this.getContentPane() method is used to return the contentPane object of this form.
*/
Container contentPane = this.getContentPane();
/* Create a panel object, specify the layout manager as GridLayout, 1 row and 2 columns. The default layout management of Jpanel is FlowLayout */
JPanel jPanel1 = new JPanel(new GridLayout(1, 2));
// Create JComboBox using String array
String[] fruit = { "apple", "banana", "orange", "pear", "mango" };
JComboBox jComboBox1 = new JComboBox(fruit);
jComboBox1.addItem("Other"); //Add another "Other" option at the end of the list box options
//Set the titled border of the jList1 object
jComboBox1.setBorder(BorderFactory.createTitledBorder("Your favorite fruit:"));
//Add list box jComboBox1 to the panel
jPanel1.add(jComboBox1);
//Use ComboBoxModel to create JComboBox
ComboBoxModel myModel = new MyModel();
JComboBox jComboBox2 = new JComboBox(myModel);
//Set the titled border of the jList1 object
jComboBox2.setBorder(BorderFactory.createTitledBorder("Your favorite fruit:"));
//Add list box jComboBox2 to the panel
jPanel1.add(jComboBox2);
//Add panel to parent container
contentPane.add(jPanel1);
//Set the title of this form
this.setTitle("JComboBoxDemo");
//Set the initial size displayed by this form
this.setSize(350, 90);
this.setLocation(300, 200);
//Set this form to be initially visible
this.setVisible(true);
}
class MyModel extends DefaultComboBoxModel {
String[] fruit = { "apple", "banana", "orange", "pear", "mango" };
MyModel() {
for (int i = 0; i < fruit.length; i++) {
/* addElement() method is used to add option elements to the list box */
this.addElement(fruit[i]);
}
}
}
public static void main(String args[]) {
JComboBoxDemo test = new JComboBoxDemo();
}
}
screenshot:
3. List box (JList):
The function of the list box is similar to that of the drop-down list box. It also allows users to make choices among several items, but there are some differences. It provides users with more diverse selection modes, including single selection, continuous selection, and multiple selection. , corresponding to the 3 constants in ListSelectionModel:
(1) static int SINGLE_SELECTION Only one can be selected.
(2) static int SINGLE_INTERVAL_SELECTION Press and hold the [Shift] key to select the contact interval.
(3) static int MULTIPLE_INTERVAL_SELECTION Hold down the [Ctrl] key to select multiple items.
The constructor is as follows:
(1) JList() creates a JList component.
(2) JList(ListModel model) Create a JList component based on the model.
(3) JList(Object[] items) uses array objects to create a JList component.
(4) JList (Vector items) Use Vector objects to create a JList component.
Adding the list box JList to the JScrollPane can achieve scrolling of the list box.
Example 1 of using the List (JList) component is as follows:
Copy the code code as follows:
public class JListDemo1 extends JFrame{
Container contentPane;
JPanel jp;
JList jList1,jList2,jList3;
public JListDemo1(){
contentPane = this.getContentPane();
jp = new JPanel(new GridLayout(1,3));
//Use String array to create JList object
String[] fruit={"apple","banana","orange","pear","mango"};
jList1=new JList(fruit);
//Set the titled border of the jList1 object
jList1.setBorder(BorderFactory.createTitledBorder("Your favorite fruit: "));
//Set the selection mode of jList1 object to single selection
jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jp.add(jList1);
//Use ListModel to create a JList object to realize the dynamics of the list content
ListModel myModel=new MyModel(); //Create a list model object
jList2=new JList(myModel); //Create a list based on the list model object
jList2.setBorder(BorderFactory.createTitledBorder("Your favorite fruit: "));
//Set the selection mode of the jList2 object to hold down [Ctrl] for multiple selections
jList2.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
jp.add(jList2);
jList3=new JList(fruit);
jList3.setBorder(BorderFactory.createTitledBorder("Your favorite fruit: "));
jList3.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
jList3.setVisibleRowCount(3);
jList3.setFixedCellWidth(120);
jList3.setFixedCellHeight(30);
JScrollPane jScrollPane = new JScrollPane(jList3);
jp.add(jScrollPane);
contentPane.add(jp);
this.setTitle("JListDemo");
this.setSize(340,200);
//pack();
this.setLocation(400, 300);
this.setVisible(true);
}
//By inheriting the DefaultListModel class, list selection of dynamic content can be achieved
class MyModel extends DefaultListModel{
String[] fruit={"apple","banana","orange","pear","mango"};
MyModel(){
for(int i=0;i<fruit.length;i++){
/* void addElement(Object obj)
* Adds the specified component to the end of such a table. */
this.addElement(fruit[i]);
}
}
}
public static void main(String[] args){
JListDemo1 test=new JListDemo1();
}
}
The running results are shown in the figure below:
List box example 2 code:
Copy the code code as follows:
public class JListDemo2 extends JFrame {
Container contentPane;
JPanel jp;
JList jListFont, jListSize;
//Constructor
public JListDemo2() {
contentPane = this.getContentPane();
jp = new JPanel(new GridLayout());
setJListFont();
setJListFontSize();
contentPane.add(jp);
this.setTitle("JListDemo");
this.setSize(240, 200);
this.setLocation(400, 300);
this.setVisible(true);
} // End of JListDemo2
public void setJListFont() {
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
final String fontName[] = ge.getAvailableFontFamilyNames(); // Get the system's local font
jListFont = new JList(fontName);
//Set the titled border of the jList1 object
jListFont.setBorder(BorderFactory.createTitledBorder("System Font: "));
//Set the selection mode of the jList1 object to single selection
jListFont.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jListFont.setVisibleRowCount(3);
jListFont.setFixedCellWidth(120);
jListFont.setFixedCellHeight(20);
JScrollPane jScrollPane1 = new JScrollPane(jListFont);
jp.add(jScrollPane1);
}
public void setJListFontSize() {
final String fontSize[] = { "8", "9", "10", "12", "14", "15", "16",
"18", "20", "21", "22", "24", "26", "28", "30", "36", "48",
"54", "72", "89" };
//Create a list box of font sizes listSize
jListSize = new JList(fontSize);
jListSize.setBorder(BorderFactory.createTitledBorder("Font size: "));
//Set the selection mode of the jList2 object to hold down [Ctrl] for multiple selections
jListSize
.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
jListSize.setVisibleRowCount(3);
jListSize.setFixedCellWidth(120);
jListSize.setFixedCellHeight(20);
JScrollPane jScrollPane2 = new JScrollPane(jListSize);
jp.add(jScrollPane2);
}
public static void main(String[] args) {
JListDemo2 test = new JListDemo2();
}
}
Schematic diagram of program operation:
4.javax.swing
Class JColorChooser:
JColorChooser (color selection dialog) provides a controller pane that allows the user to manipulate and select colors.
JColorChooser constructor:
JColorChooser(): Create a JColorChooer object, the default color is white.
JColorChooser(Color initialColor): Create a JColorChooer object and set the initial color.
JColorChooser(ColorSelectionModel modal): Constructs a JColorChooser object with ColorSelectionModel.
The most common way to use JColorChooser is to use the static method showDialog() of JColorChooser. That is to say, in most cases, we will not create a new JColorChooser object, but directly use the static method (showDialog()) of JColorChooser to output Color selection dialog box. Using this method, we can also get the color selected by the user. If the user does not choose, a null value will be returned.
Simple case 1 code for color selection dialog:
Copy the code code as follows:
public class JColorChooserDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("JColorChooserDemo");
MyPanel panel = new MyPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setLocation(300, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class MyPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton button,rgb,red,green,blue;
private Color color = new Color(255, 51, 150);
public MyPanel() {
button = new JButton("Get Color");
rgb = new JButton("RGB: ");
red = new JButton("Red: ");
green = new JButton("Green: ");
blue = new JButton("Blue: ");
button.addActionListener(this);
setPreferredSize(new Dimension(550, 250));
setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
setBackground(color);
add(button);
add(rgb);
add(red);
add(green);
add(blue);
}
public void actionPerformed(ActionEvent e) {
color = JColorChooser.showDialog(this, "Choose Color", color);
if (color != null) {
setBackground(color);
button.setText("Get again");
rgb.setText("RGB: " + color.getRGB());
red.setText("Red: " + color.getRed());
green.setText("Green: " + color.getGreen());
blue.setText("Blue: " + color.getBlue());
}
}
}
The running result diagram is as follows:
Another common way to use JColorChooser is to use the createDialog() static method. After using this static method, you will get a JDialog object. We can use this JDialog object to make more settings for the color selection dialog box. However, To use this method, you must cooperate with the JColorChooser object, that is, you must create a new JColorChooser object. The following example introduces the simplest and most practical JColorChooser. After selecting the color, you can change the background color on the JLabel.
Simple case 2 code for color selection dialog:
Copy the code code as follows:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ColorChooserDemo1 extends MouseAdapter {
JFrame f = null;
JLabel label = null;
JLabel label1 = null;
JLabel label2 = null;
Rectangle rec1 = null;
Rectangle rec2 = null;
public ColorChooserDemo1() {
f = new JFrame("ColorChooser Example");
Container contentPane = f.getContentPane();
contentPane.addMouseListener(this);
label = new JLabel(" ", JLabel.CENTER);
label.setPreferredSize(new Dimension(300, 20));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
label1 = new JLabel("Left Label", JLabel.CENTER);
label1.setBackground(Color.red);
label1.setForeground(Color.black);
label1.setOpaque(true);
label1.setBounds(0, 0, 150, 150);
panel.add(label1);
label2 = new JLabel("Right Label", JLabel.CENTER);
label2.setBackground(Color.green);
label2.setForeground(Color.black);
label2.setOpaque(true);
label2.setBounds(150, 0, 150, 150);
panel.add(label2);
rec1 = label1.getBounds();
rec2 = label2.getBounds();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(label, BorderLayout.SOUTH);
f.setSize(new Dimension(300, 150));
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
// Implement the mousePressed() and mouseClicked() methods in MouseAdapter. When the mouse is pressed, you can know the current position of the mouse cursor. When the mouse is pressed continuously
//Twice, if the cursor is in the label, a color selection dialog box will appear, and the user can choose any color to change the color of the label.
public void mousePressed(MouseEvent e) {
label.setText("The current mouse coordinates (X,Y) are: (" + e.getX() + "," + e.getY() + ")");
}
public void mouseClicked(MouseEvent e) {
Point point = e.getPoint();
if (e.getClickCount() == 2) {
if (rec1.contains(point)) {
/*
* Use the showDialog() static method of JColorChooser to output the color selection dialog box
*, the three parameters in showDialog() are: parent component of the dialog box, color selection dialog box title
*, with the default color of the dialog box. After the user selects the color, press the "OK" button to return
* Color object, if the "Cancel" button is pressed, null value is returned.
*/
Color color = JColorChooser.showDialog(f,
"Change label1 Color", Color.white);
if (color != null) // If the value is null, it means the user pressed the Cancel button
label1.setBackground(color);
}
if (rec2.contains(point)) {
Color color = JColorChooser.showDialog(f,
"Change label2 Color", Color.yellow);
if (color != null) // If the value is null, it means the user pressed the Cancel button
label2.setBackground(color);
}
}
}
public static void main(String[] arg) {
new ColorChooserDemo1();
}
}