【问题标题】:Binding JComboBox to a JTable将 JComboBox 绑定到 JTable
【发布时间】:2013-12-16 18:51:27
【问题描述】:

我编写的这个程序有一个 JComboBox,其中的项目代表我的数据库中的表,每个项目都应该显示它的内容,因为它们在选择时在 JTable 上的数据库中。我已经运行了程序,但是当我选择组合框项目时,只有组合框中的第一个项目在 JTable 上显示其内容,随后的选择不显示任何内容。有人可以看看它并告诉我做错了什么吗?或建议我任何有用的教程?非常感谢您的帮助,在此先感谢!

public class InventoryItems extends javax.swing.JFrame {
/**
 * 
 */
private static final long serialVersionUID = 1L;
private Object[] comboItems = new phoneClass().phoneManufacturerArray();
private JComboBox phoneBrandCombo = new JComboBox(comboItems);
private JPanel brandPane;
private JPanel instructionPane;
private JLabel instruction, brandLabel;
private JScrollPane scrollPane;
private JTable table;
private Object sel;
private Connection con;
private Statement stm;
private ResultSet rset;
private ResultSetMetaData meta;

/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            /**
             * Add a Look&F to the GUI
             */
            try{
                UIManager.setLookAndFeel("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel");
             } catch (ClassNotFoundException ex) {
                  java.util.logging.Logger.getLogger(LoginInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
              } catch (InstantiationException ex) {
                  java.util.logging.Logger.getLogger(LoginInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
              } catch (IllegalAccessException ex) {
                  java.util.logging.Logger.getLogger(LoginInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
              } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                  java.util.logging.Logger.getLogger(LoginInterface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
              }
            InventoryItems inst = new InventoryItems();
            inst.setLocationRelativeTo(null);
            inst.setVisible(true);
        }
    });
}

public InventoryItems() {
    super();
    initGUI();
}

private void initGUI() {
    try {
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        /**
         * rows and column names declared as vectors.
         */
         final Vector columnNames = new Vector();
         final Vector data = new Vector();
          sel = phoneBrandCombo.getSelectedItem();

           //Get Selected Items and retrieve contents based on selected Item.

           try{
               try{
                  Class.forName("com.mysql.jdbc.Driver").newInstance();
                 }catch(ClassNotFoundException cnf){
                  System.out.println("Class Not Found Exception: "+cnf);
                 }catch(IllegalAccessException iaE){
                  System.out.println("Illegal Access Exception: "+iaE);
                 }catch(InstantiationException iE){
                  System.out.println("Instantiation Exception: "+iE);
                }
                 con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
                    + "phoneshopsystem", dbLogin.dbUser(), dbLogin.dbPwd());
                 String query = "SELECT phoneID, phoneModel, phonePrice, QuantityInStock FROM "+sel;
                  stm = con.createStatement();
                   rset = stm.executeQuery(query);
                 meta = rset.getMetaData();

                int columns = meta.getColumnCount();

                //Get Column Names

                 for (int i = 1; i <= columns; i++)
                    {
                        columnNames.addElement( meta.getColumnName(i) );
                    }

                 while (rset.next())
                    {

                        Vector row = new Vector(columns);

                          for (int i = 1; i <= columns; i++)
                          {
                            row.addElement( rset.getObject(i) );
                          }

                          //Fill JTable rows with database table rows

                        data.addElement( row );
                    }
                rset.close();
                stm.close();
                con.close();

            }catch(SQLException sql){
                JOptionPane.showMessageDialog(null, "Table SQL Exception@: "+sql.getMessage());
            }

          /**
           * Initialise the Table with the rows and column names
           * retrieved from the database resultSet.
           */

table = new JTable(data, columnNames){
    private static final long serialVersionUID = 1L;

        public Class getColumnClass(int column){
            for(int row = 0; row < getRowCount(); row++){
                Object o = getValueAt(row, column);

                 if(o != null){
                     return o.getClass();
                 }
            }
            return Object.class;
        }
    };

    /**
    * Table properties
    */
{
//table.setPreferredSize(new java.awt.Dimension(534, 180));
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setGridColor(Color.LIGHT_GRAY);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setSelectionBackground(new Color(248, 248, 248));
table.setSelectionForeground(new Color(51, 0, 51));
table.setBackground(new java.awt.Color(248,248,248));
}
    // Add Table to JScrollPane
{
scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new java.awt.Dimension(534, 189));
scrollPane.setBackground(new java.awt.Color(212,208,200));
scrollPane.setBorder(BorderFactory.createTitledBorder(""));
scrollPane.setViewportView(table);
getContentPane().add(scrollPane, BorderLayout.SOUTH);
}

{
instructionPane = new JPanel();
FlowLayout instructionPaneLayout = new FlowLayout();
instructionPane.setLayout(instructionPaneLayout);
instruction = new JLabel();
instruction.setText("<html><body><br><p>"
            + "Select The Phone-Brand e.g 'Nokia',"
            + " To View Inventory."
            + "</p><br></body></html>");
instruction.setFont(new Font("Times New Roman", 3, 11));
instruction.setHorizontalAlignment(JLabel.CENTER);
instruction.setVerticalAlignment(JLabel.CENTER);
instruction.setBackground(new Color(240, 240, 240));
instruction.setEnabled(false);
instructionPane.add(instruction);
getContentPane().add(instruction, BorderLayout.NORTH);
}

{
brandPane = new JPanel();
FlowLayout brandPaneLayout = new FlowLayout();
brandPane.setLayout(brandPaneLayout);
brandLabel = new JLabel("Phone Brands: ");
brandLabel.setEnabled(false);
brandPane.add(brandLabel);
phoneBrandCombo.addActionListener(new ActionListener(){
    @Override
        public void actionPerformed(ActionEvent ae){
            if(ae.getSource() == phoneBrandCombo.getSelectedItem()){
                phoneBrandCombo.getSelectedItem();
            }
    }
});
brandPane.add(phoneBrandCombo);
brandPane.setBackground(new java.awt.Color(240,240,240));
getContentPane().add(brandPane, BorderLayout.CENTER);
}

pack();
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setBackground(new java.awt.Color(240,240,240));
setPreferredSize(new Dimension(550, 330));

【问题讨论】:

    标签: java swing jtable jcombobox


    【解决方案1】:

    它可以正常工作:

    phoneBrandCombo.addItemListener(new ItemListener(){
    @Override
        public void itemStateChanged(ItemEvent ie){
            if(ie.getStateChange() == ItemEvent.SELECTED){
                selectedItem = ((JComboBox)ie.getSource()).getSelectedItem(); 
    classes.loadTableData db = new classes.loadTableData();
    db.loadData(selectedItem, data, columnNames);
    
    table.setModel(new DefaultTableModel(data, columnNames));
      }else{
             data.removeAllElements();
             columNames.removeAllElements();
      }
    

    } });

    【讨论】:

    • 请在您的问题中添加其他信息,而不是在答案中添加其他信息。
    • 您的观点已被记录!我已将帖子编辑为答案!
    【解决方案2】:

    您在构建时仅将数据加载到 Jtable 一次,然后您永远不会这样做,因为当您在 JComboBox 中选择另一个项目时,您的 Jtable 不会更新。

    不要在phoneBrandCombo 上使用ActionListener,而是使用ItemListener,如下所示:

     phoneBrandCombo.addItemListener(new ItemListener() {
    
            @Override
            public void itemStateChanged(ItemEvent arg0) {
                if(arg0.getStateChange() == ItemEvent.SELECTED){
                    Object object = ((JComboBox)arg0.getSource()).getSelectedItem();
                    //loadDataFromDBToTable(object);
                }
            }
        });
    

    这里的loadDataFromDBToTable(object); 是为选定的object 加载新数据到JTable 的方法。

    了解如何使用 JTableJComboBox

    【讨论】:

    • 让我再检查一下代码,我会在有改进时发布反馈。我很欣赏你的评论,我真的很喜欢。
    • 我实现了你的建议,但似乎仍然做错了。我已经阅读了一些关于 JTable 的内容,但它没有给出任何关于如何实现我想要实现的目标的示例。这就是我所做的:
    • 现在可以正常使用了。我添加了一个 ELSE 子句,当从组合框中选择不同的项目时,它会重新绘制表格。谢谢!
    猜你喜欢
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 2011-10-12
    • 2015-01-27
    相关资源
    最近更新 更多