Graphical user interface: Swing component list

7, Check box

Check boxes provide a way to make a single selection of "checked" or "unchecked". It contains a small box and a label. This box usually has an "x" mark (or other mark indicating "selected") or is empty, depending on whether the check box is selected.

JCheckBox is usually created using a constructor that accepts tags as parameters. You can get and set the status, get and set its label, and even change the label after the JCheckBox object has been established.

When JCheckBox is selected or cleared, an event will occur. You can capture this event in the same way as the deal button: use ActionListener. In the following example, all selected check boxes will be enumerated and displayed in JTextArea:

package gui;

import java.awt.FlowLayout;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import com.buba.util.SwingConsole;

public class CheckBoxes extends JFrame {
	private JTextArea t = new JTextArea(6, 15);
	private JCheckBox cb1 = new JCheckBox("Check Box 1"), cb2 = new JCheckBox("Check Box 2"),
			cb3 = new JCheckBox("Check Box 3");

	public CheckBoxes() {
		cb1.addActionListener(e -> {
			trace("1", cb1);
		});
		cb2.addActionListener(e -> {
			trace("2", cb2);
		});
		cb3.addActionListener(e -> {
			trace("3", cb3);
		});
		setLayout(new FlowLayout());
		add(new JScrollPane(t));
		add(cb1);
		add(cb2);
		add(cb3);
	}

	private void trace(String b, JCheckBox cb) {
		if (cb.isSelected())
			t.append("Box " + b + " Set\n");
		else
			t.append("Box " + b + " Cleared\n");
	}

	public static void main(String[] args) {
		SwingConsole.run(new CheckBoxes(), 200, 300);
	}
}

The trace() method uses append() to display the name of the selected JCheckBox and its current state in the JTextArea, so you can see a check box list, including the check box name and its state.

8, Radio button

The radio button in the invention is derived from the concept of using the radio button on the car before the GUI; When one of them is pressed, the other pressed buttons will pop up. Therefore, radio buttons force you to select only one of multiple options.

To set a set of associated jradiobuttons, you need to add them to a buttonggroup (there can be any number of buttongroups on the form). You can choose to set one of the buttons to checked (true) (set in the second parameter of the constructor). If you set the status of multiple radio buttons to selected, only the last one is valid.

The following is a simple example of using a radio button to capture events using ActionListener:

package gui;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

import com.buba.util.SwingConsole;

public class RadioButtons extends JFrame {
	private JTextField t = new JTextField(15);
	private ButtonGroup g = new ButtonGroup();
	private JRadioButton rb1 = new JRadioButton("one", false), rb2 = new JRadioButton("two", false),
			rb3 = new JRadioButton("three", false);
	private ActionListener al = new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent e) {
			t.setText("Radio button " + ((JRadioButton) e.getSource()).getText());
		}
	};

	public RadioButtons() {
		rb1.addActionListener(al);
		rb2.addActionListener(al);
		rb3.addActionListener(al);
		g.add(rb1);
		g.add(rb2);
		g.add(rb3);
		t.setEditable(false);
		setLayout(new FlowLayout());
		add(t);
		add(rb1);
		add(rb2);
		add(rb3);
	}

	public static void main(String[] args) {
		SwingConsole.run(new RadioButtons(), 200, 125);
	}
}

A text field is used here to display the status. Because it is only used to display rather than collect data, it is set to "non editable". Therefore, this is a way to replace JLabel.                                                                                                                                                                         

9, Combo box

Similar to the function of a group of radio buttons, the combo box (drop-down list) also forces the user to select only one from a group of possible elements. However, this method is more compact, and it is easier to change the contents of the drop-down list without confusing the user (of course, you can also change the radio button dynamically, but it is obviously easy to cause conflict).

By default, the JComboBox combo box is not exactly the same as the combo box under Windows operating system. The latter allows you to select from the list or enter by yourself. To get such behavior, you must call the setEditable() method. Using the JComboBox combo box, you can and can only select one element from the list. In the following example, the JComboBox combo box already has some elements at the beginning, and then when a button is pressed, a new element will be added to the combo box.

package gui;

import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;

import com.buba.util.SwingConsole;

public class ComboBoxes extends JFrame {
	private String[] description = { "enthusiastic", "Dull", "Tenacious", "excellent", "Aging", "yellow-bellied", "luxuriant", "Corrupt" };
	private JTextField t = new JTextField(15);
	private JComboBox<String> c = new JComboBox<>();
	private JButton b = new JButton("Add items");
	private int count = 0;

	public ComboBoxes() {
		for (int i = 0; i < 4; i++)
			c.addItem(description[count++]);
		t.setEditable(false);
		b.addActionListener(e -> {
			if (count < description.length)
				c.addItem(description[count++]);
		});
		c.addActionListener(e -> {
			t.setText("index: " + c.getSelectedIndex() + " " + ((JComboBox) e.getSource()).getSelectedItem());
		});
		setLayout(new FlowLayout());
		add(t);
		add(c);
		add(b);
	}

	public static void main(String[] args) {
		SwingConsole.run(new ComboBoxes(), 200, 175);
	}
}

                                                                                                                                                                                                                                                                          The JTextField in the above example is used to display the "selected index" (the sequence number of the currently selected element) and the text of the selected element in the combo box.

10, List box

The list box is obviously different from the JComboBox combo box, which is not only reflected in the appearance. When the JComboBox combo box is activated, a drop-down list will appear; JList always occupies a fixed number of lines on the screen, and its size will not change. If you want to get the selected item in the list box, just call getSelectedValues(), which can generate a string array with the name of the selected item.

JList components allow multiple choices; If you hold down the Ctrl key and click on multiple items continuously, the previously selected items will remain selected, that is, you can select as many items as you want. If you select an item, hold down the shift key and click another item, all items between the two items will be selected. To remove one item from the selected item group, hold down the Ctrl key and click on the item.

package gui;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextArea;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.buba.util.SwingConsole;

public class List extends JFrame {
	private String[] flavors = { "Chocolates", "strawberry", "Vanilla fudge vortex", "Mint", "Mocha almond fudge", "Rum raisins", "Nut sugar cream", "Dark chocolate ice cream pie" };
	private DefaultListModel<String> lItems = new DefaultListModel<>();
	private JList<String> lst = new JList<>(lItems);
	private JTextArea t = new JTextArea(flavors.length, 20);
	private JButton b = new JButton("Add Item");
	private ActionListener bl = new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent e) {
			if (count < flavors.length) {
				lItems.add(0, flavors[count++]);
			} else {
				// Disabled because no more flavors can be added to the list
				b.setEnabled(false);
			}
		}
	};

	private ListSelectionListener ll = new ListSelectionListener() {
		@Override
		public void valueChanged(ListSelectionEvent e) {
			if (e.getValueIsAdjusting())
				return;
			t.setText("");
			for (String item : lst.getSelectedValuesList())
				t.append(item + "\n");
		}
	};
	private int count = 0;

	public List() {
		t.setEditable(false);
		setLayout(new FlowLayout());
		// Create borders for components
		Border brd = BorderFactory.createMatteBorder(1, 1, 2, 2, Color.BLACK);
		lst.setBorder(brd);
		t.setBorder(brd);
		// Add the first four items to the list
		for (int i = 0; i < 4; i++)
			lItems.addElement(flavors[count++]);
		add(t);
		add(lst);
		add(b);
		// Register event listener
		lst.addListSelectionListener(ll);
		b.addActionListener(bl);
	}

	public static void main(String[] args) {
		SwingConsole.run(new List(), 250, 375);
	}
}

You can observe that a border is added around the list box.

If you just want to add a string array to JList, there is a simpler way: as long as you pass the array to JList's constructor, you can automatically construct the list box. The only reason for using the "list model" in the above example is that it can manipulate the list box during program execution.

JList itself does not provide direct support for scrolling. Of course, all you have to do is wrap JList into JScrollPane, which will automatically help you deal with the details.

If this article is of great help to you, please pay attention to it.

Tags: Java

Posted by mdowling on Wed, 25 May 2022 10:54:33 +0300