概述
- 将按钮,下拉列表框和文本框组合起来,实现一个星座选择处理器
Demo
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Demo {
public static void main(String[] args) {
JFrame jFrame = new JFrame("选择星座示例");
String[] arr = {
"--请选择--",
"处女座",
"狮子座"
};
JComboBox jComboBox = new JComboBox(arr);
JLabel jLabel1 = new JLabel("添加新星座:");
JLabel jLabel2 = new JLabel();
JTextField jTextField = new JTextField(15);
JButton jButton1 = new JButton("新增");
JButton jButton2 = new JButton("删除");
JPanel jPanel = new JPanel();
//设置边框
jPanel.setBorder(new EmptyBorder(5,5,5,5));
//设置事件监听
jButton1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String str = jTextField.getText();
if(str.equals("")){
jLabel2.setText("请输入要添加的星座!");
}else{
jComboBox.addItem(str);
jLabel2.setText("添加成功,新增了:"+str);
}
}
});
jButton2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String str = (String)jComboBox.getSelectedItem();
if(str.equals("--请选择--")){
jLabel2.setText("请选择要删除的星座");
}else{
jComboBox.removeItem(str);
jLabel2.setText("删除成功,删除了:"+str);
}
}
});
//将组件添加进面板,容器
jPanel.add(jComboBox);
jPanel.add(jLabel1);
jPanel.add(jTextField);
jPanel.add(jButton1);
jPanel.add(jButton2);
jPanel.add(jLabel2);
jFrame.add(jPanel);
//设置窗体的大小,可见,关闭方式
jFrame.setSize(500,200);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Demo运行效果如下
初始界面
新增星座–未输入
新增星座–有输入
删除星座–未选择
删除星座–有选择