更新 JComboBox

Posted

技术标签:

【中文标题】更新 JComboBox【英文标题】:Updating a JComboBox 【发布时间】:2012-05-23 07:05:01 【问题描述】:

我有一个自动设置的 JComboBox,它使用一种在启动时从我的数据库中获取所有 Id 的方法,我还有一个删除功能,它将从数据库中删除选定的对象,但它不会删除 id从列表中。执行删除方法时,有什么方法可以 吗?如果有帮助,我的代码如下。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.sql.*;

import java.util.ArrayList;

public class EditMember extends JFrame 

    String[] positions = "", "Trainee", "Writer", "Moderator", "Administrator";

    JComboBox _id = new JComboBox(getId());
    JComboBox _position = new JComboBox(positions);

    JTextField _name = new JTextField(10);
    JTextField _username = new JTextField(10);
    JPasswordField _password = new JPasswordField(10);

    JButton edit = new JButton("Edit Member");
    JButton delete = new JButton("Delete Member");
    JButton generate = new JButton("Generate Report");
    JButton exit = new JButton("Exit");
    JButton load = new JButton("Load in");

    Toolkit kit = Toolkit.getDefaultToolkit();
    Dimension screenSize = kit.getScreenSize();
    int screenHeight = (int)screenSize.getHeight();
    int screenWidth = (int)screenSize.getWidth();

    public EditMember() 
        super("Edit Member");
        setLayout(new GridLayout(7,1,1,1));

        add(_id);
        add(load);
        load.addActionListener(new LoadInListener());

        add(new JLabel("Name:"));
        add(_name);

        add(new JLabel("Username:"));
        add(_username);

        add(new JLabel("Password:"));
        add(_password);

        add(new JLabel("Position:"));
        add(_position);

        add(edit);
        add(delete);
        delete.addActionListener(new DeleteListener());
        add(generate);
        add(exit);
        exit.addActionListener(new ExitListener());

        setSize(406, 200);
        setResizable(false);
        setLocation(screenWidth/4, screenHeight/4);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setVisible(true);
    

    public static void main(String[] args) 
        new EditMember();
    

    public Object[] getId() 
        Connection con;
        Statement stmt;
        ResultSet rs;

        //Object[] returnId;
        ArrayList<Object> returnId = new ArrayList<Object>();
        try 
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con = DriverManager.getConnection("jdbc:odbc:collegesys","root","0blivi0n");

            stmt =con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
            rs = stmt.executeQuery("SELECT `id` FROM main");

            while(rs.next()) 
                returnId.add(rs.getObject("id"));
            

            con.close();
         catch(Exception e) 
            e.printStackTrace();
        
        return returnId.toArray(new Object[returnId.size()]);
    

    public class ExitListener implements ActionListener 
        public void actionPerformed(ActionEvent e) 
            dispose();
        
    

    public class LoadInListener implements ActionListener 
        public void actionPerformed(ActionEvent e) 
            String giveId = _id.getSelectedItem().toString();

            populate(giveId);
        
    

    public class DeleteListener implements ActionListener 
        public void actionPerformed(ActionEvent e) 
            delete();
        
    

    public void delete() 
        Connection con;
        Statement stmt;
        ResultSet rs;
        int idA;
        String name, username, password, position;

        try 
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con = DriverManager.getConnection("jdbc:odbc:collegesys","root","0blivi0n");

            stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
            PreparedStatement pstmt = con.prepareStatement("DELETE FROM `main` WHERE ID = ?");
            pstmt.setInt(1, (int)_id.getSelectedItem());
            pstmt.execute();
            // udpate JComboBox here
         catch(Exception e) 
            e.printStackTrace();
        
    

    public void populate(String a) 
        Connection con;
        Statement stmt;
        ResultSet rs;
        int idA;
        String name, username, password, position;

        try 
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con = DriverManager.getConnection("jdbc:odbc:collegesys","root","0blivi0n");

            stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
            rs = stmt.executeQuery("SELECT * FROM main");

            while(rs.next()) 
                idA = rs.getInt("id");
                name = rs.getString("name");
                username = rs.getString("username");
                password = rs.getString("password");
                position = rs.getString("position");
                if(Integer.parseInt(a) == idA) 
                    _name.setText(name);
                    _username.setText(username);
                    _password.setText(password);
                    _position.setSelectedItem(position);
                
            
         catch(Exception e) 
            e.printStackTrace();
        
    

【问题讨论】:

docs.oracle.com/javase/6/docs/api/javax/swing/… 不使用模型的其他方式:***.com/a/49411906/7185318 【参考方案1】:

如here 所述,您可以这样做:

public void delete()

    ...
    SwingUtils.invokeLater(new Runnable()
    
        @Override
        public void run()
        
            DefaultComboBoxModel model = new DefaultComboBoxModel( yourStringArray );
            comboBox.setModel( model );
        
    );

yourStringArray 是您想在JComboBox 中呈现的任何内容。我已经有一段时间没有使用 Swing 了,但通常您需要做的任何 GUI 更改都需要您通过 SwingUtils.invokeLater(Runnable)。这将使您的更改通过事件调度线程 (EDT) 进行操作,该线程负责处理 GUI。大多数在线示例不这样做,原因是它们中的大多数似乎是在事件侦听器中进行更改,而事件侦听器本身在 EDT 中运行。

【讨论】:

以上是关于更新 JComboBox的主要内容,如果未能解决你的问题,请参考以下文章

需要帮助访问内部类中的变量for循环

关于JComboBox和JSpinner的问题

增量更新

版本更新

ABP规则怎么自动更新

更新父状态时更新子组件