下面的代码演示了如何设置的选定项目,JComboBox然后如何获得选定项目的值。在此示例中,我们设置了JComboBox组件,以便用户可以输入自己的值。
package org.nhooo.example.swing;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ComboBoxSelectedItem extends JFrame {
public ComboBoxSelectedItem() {
initialize();
}
private void initialize() {
setSize(300, 300);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
// 创建一个包含四个项目的组合框,并将其设置为可编辑,以便用户可以
// 输入自己的价值。
final JComboBox<String> comboBox = new JComboBox<>(new String[] {"One", "Two", "Three", "Four"});
comboBox.setEditable(true);
getContentPane().add(comboBox);
//创建两个按钮,将设置组合框的所选项目。的
// 第一个按钮选择“两个”,第二个按钮选择“四个”。"Two" and and second button select "Four".
JButton button1 = new JButton("Set Two");
getContentPane().add(button1);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
comboBox.setSelectedItem("Two");
}
});
JButton button2 = new JButton("Set Four");
getContentPane().add(button2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
comboBox.setSelectedItem("Four");
}
});
// 创建一个文本字段,用于当我们按
//获取值按钮。当用户输入自己的值时,所选项目
// 返回的是用户输入的字符串。
final JTextField textField = new JTextField("");
textField.setPreferredSize(new Dimension(150, 20));
JButton button3 = new JButton("Get Value");
getContentPane().add(button3);
getContentPane().add(textField);
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText((String) comboBox.getSelectedItem());
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ComboBoxSelectedItem().setVisible(true);
}
});
}
}