我编写了这个程序,它有一个JComboBox,其中的项目代表我的数据库中的表,每个项目都应该显示它的内容,因为它们在选择时在JTable的数据库中。我运行程序,但是当我选择组合框项目时,只有comboBox中的第一项显示其在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));
答案 0 :(得分:1)
您只需在构建该数据时将数据加载到Jtable
,然后您就永远不会这样做,因为Jtable
在您选择JComboBox
中的其他项目时不会更新
而不是在ActionListener
使用phoneBrandCombo
上使用ItemListener
,而不是下一个:{/ p>
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
的{{1}}加载新数据的方法。
答案 1 :(得分:0)
它可以正常使用:
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();
}
} });