当前位置: 首页 > 知识库问答 >
问题:

将 JComboBox 绑定到 JTable

乜胜泫
2023-03-14

我编写了这个程序,它有一个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));

共有2个答案

傅长恨
2023-03-14

它适用于此:

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();
  }

} });

倪子晋
2023-03-14

在构造它时,你只将数据加载到 Jtable 一次,然后你永远不会这样做,因为你的 JtableJComboBox 中选择另一个项目时不会更新。

不要在手机上使用 ActionListenerBrandCombo,请使用 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); 是将新数据加载到所选对象的 JTable方法

阅读有关使用 JTableJComboBox 的信息。

 类似资料:
  • 有没有一种方法可以直接将memcached绑定到它下面的本地存储?将用一个例子来解释。假设hbase被用作分布式的后端。memcached的一层被用作缓存层,它可以被认为是hbase的一个完全副本(在某种意义上)。假设系统中有4个节点,其中3个用于hbase并在其顶部有一个memcached层,1个节点用于计算。通常的规范是查找memcached是否有某个键。如果有,取出来并用于计算。如果没有,则

  • 我正在Java创建一个 代码:

  • 如何将MVVM值绑定到dropdownlist?下面的输入元素运行良好

  • 问题内容: 我想在Android中运行长时间运行的操作。假设任务将运行约5-10分钟。因此,我打算使用并将其绑定到。 现在我正在使用,即使我知道不能/不应该将其用于长时间运行的操作,因此我打算立即进行更改。很多时候,发生的情况是在任务运行时,用户将应用程序最小化,并且一段时间后,Android操作系统关闭/清除了,以释放一些内存。 因此,我一直没有任何目的地运行,并且尝试更新其中的视图时崩溃了。

  • 我正在尝试这里提供的解决方案https://social.msdn.microsoft.com/forums/en-us/16a91381-0714-4ba1-aff0-7f3b6483b282/populate-a-treeview-from-xsd-file-in-wpf?forum=wpf只采用xs:element和xs:sequence节点,排除所有其他节点(xs:complextype>

  • 我在一个razorpage上有一个单选按钮,像这样 表单的模型如下所示 和SQL的模型如下所示 而SQL中的CostCenter的数据类型是varchar(80) 当我保存表单时,CostCenter没有绑定到SQL中的任何值,它将保持为NULL,但表单的其余值将正确保存 那是什么原因造成的呢? 如果选择了“proj”,我想保存值“proj”,如果选择了“dep”,我想保存值“dep” 谢谢 托玛