Swing--星座選擇器界面的實現

概述

  • 將按鈕,下拉列表框和文本框組合起來,實現一個星座選擇處理器

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運行效果如下
初始界面
在這裏插入圖片描述
新增星座–未輸入
在這裏插入圖片描述
新增星座–有輸入
在這裏插入圖片描述
刪除星座–未選擇
在這裏插入圖片描述

刪除星座–有選擇
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章