gpt4 book ai didi

java - 将 JComboBox 绑定(bind)到 JTable

转载 作者:行者123 更新时间:2023-12-01 13:46:50 25 4
gpt4 key购买 nike

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

最佳答案

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

不要在 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);是用于将新数据加载到所选对象JTable的方法。

了解如何使用JTableJComboBox .

关于java - 将 JComboBox 绑定(bind)到 JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20304996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com