如何使用数据库中的信息将jcombobox逐步添加到数组中



我在java中有一个pogram,其中我有一个JFrame和一个Jtable,Jtable有10行4列。第三列是一个jcombobox,它进入DB,为该行第2列和第1列中输入的值获取属于第3列的值。这是代码:

//JCOMBOBOX CREATED
TableColumn sportColumn = table.getColumnModel().getColumn(3);
JComboBox comboBox = new JComboBox();
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
comboBox.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent event) {

try{     

int comboboxRow = table.getSelectedRow();
String OFNUPK = (String) table.getValueAt(comboboxRow, 1);
String TFCCMP = (String) table.getValueAt(comboboxRow, 2);
// Se o valor for nulo ou não inteiro isto vai atirar erro
int OFNUP = Integer.parseInt(OFNUPK);
// Verificar se o valor é válido
if (TFCCMP != null && !TFCCMP.isEmpty()) {
Connection con = DriverManager.getConnection("jdbc:as400://" + host, user, pwd);
// create new statement from connection
Statement stmt = con.createStatement();
// Se puderes aqui usa prepared statements como te mostrei ontem
String s = "SELECT DISTINCT a.TFCPAI FROM $$CLI00F55.FOFFAN a, SICGA00F55.FORFAB f WHERE "
+ "a.TFCCMP = '" + TFCCMP + "' AND f.OFNUPK = " + OFNUP +" AND f.OFNUPK = a.TFSNOF";
ResultSet rs = stmt.executeQuery(s);
//APAGAR OS DADOS ANTERIORES
while(rs.next())
{
comboBox.addItem(rs.getString(1));
}

当在同一行中单击Jcombobox并添加相同的值时,我遇到了两个问题。在下一行中,上一行中出现的数据也会出现。

如果您需要更多信息,请发表评论。非常感谢。

您不需要使用任何侦听器。您需要重写TableCellEditor中的方法getTableCellEditorComponent()

JComboBox comboBox = new JComboBox();
sportColumn.setCellEditor(new DefaultCellEditor(comboBox)) {
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int row,
int column) {
JComboBox comboBox = (JComboBox) editorComponent
String OFNUPK = (String) table.getValueAt(row, 1);
String TFCCMP = (String) table.getValueAt(row, 2);
// Se o valor for nulo ou não inteiro isto vai atirar erro
int OFNUP = Integer.parseInt(OFNUPK);
// Verificar se o valor é válido
if (TFCCMP != null && !TFCCMP.isEmpty()) {
Connection con = DriverManager.getConnection("jdbc:as400://" + host, user, pwd);
// create new statement from connection
Statement stmt = con.createStatement();
// Se puderes aqui usa prepared statements como te mostrei ontem
String s = "SELECT DISTINCT a.TFCPAI FROM $$CLI00F55.FOFFAN a, SICGA00F55.FORFAB f WHERE "
+ "a.TFCCMP = '" + TFCCMP + "' AND f.OFNUPK = " + OFNUP +" AND f.OFNUPK = a.TFSNOF";
ResultSet rs = stmt.executeQuery(s);
//APAGAR OS DADOS ANTERIORES
while(rs.next())
{
comboBox.addItem(rs.getString(1));
}
}
});

请注意,您还需要确保TableModel具有适当的setValueAt()方法。我猜您使用的是DefaultTableModel。如果你是,那么它已经有了一个合适的setValueAt()方法,所以你不需要在那里做任何事情。

另外,不要忘记关闭数据库连接以及处理可能引发的任何SQLException。也许可以考虑使用PreparedStatement而不是Statement

最新更新