java 使用JComboBox填充JTable数据

zsohkypk  于 2023-04-28  发布在  Java
关注(0)|答案(3)|浏览(145)

我有一个带表的框架,combobox,我想用combobox从数据库填充表,但如果我使用itemlistener,我看不到表,没有itemlistener和String sql="select * from Arlista",我看到我的表有数据(combob=combobox)

combob.addItemListener(new ItemListener(){
    @Override
    public void itemStateChanged(ItemEvent e){
        tesztvalt=(combob.getSelectedItem()).toString();

        if (e.getItem().equals(tesztvalt))
        {
            try {

                Class.forName( driver );
                Connection connection = DriverManager.getConnection( url );
                String sql="select * from "+tesztvalt+"";
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery( sql );
                ResultSetMetaData md = rs.getMetaData();
                int columns = md.getColumnCount();

                while (rs.next()) {
                    Vector row = new Vector(columns);

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

                }
                rs.close();
                stmt.close();
                connection.close();
            }catch(Exception ex) {
                System.out.println( e );
            }
            JTable table = new JTable(data, columnNames)
            {
                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;
                }
            };
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );

            JPanel buttonPanel = new JPanel();
            getContentPane().add( buttonPanel, BorderLayout.SOUTH );
        }
    }
});
v8wbuo2f

v8wbuo2f1#

这是一个稍微不同的方法,但它很简单。当您从组合框中选择一个项目时,表格会发生更改。它使用一个表模型:

//ComboTableTest.java
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class ComboTableTest extends JFrame implements ActionListener {
    private static final long serialVersionUID = -3898736145211708745L;

    private JComboBox<String> combo;
    private MyTableModel tableModel;

    //constructor
    public ComboTableTest() {
        //set up frame
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600,175);
        setLayout(new FlowLayout());

        //create combo box
        combo = new JComboBox<String>(new String[]{"one", "two", "three"});
        combo.addActionListener(this);
        add(combo);

        //create table
        tableModel = new MyTableModel();
        final JTable table = new JTable(tableModel);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == combo) {
            tableModel.setValueAt(0,0,(String)combo.getSelectedItem());
            tableModel.setValueAt(1,1,(String)combo.getSelectedItem());
            tableModel.setValueAt(2,2,(String)combo.getSelectedItem());
        }

    }

    /*** MAIN ***/
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ComboTableTest frame = new ComboTableTest();
                    frame.setVisible(true);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

class MyTableModel extends AbstractTableModel {
    private static final long serialVersionUID = -1359557492205432915L;

    private String[] columnNames = {"Col 1","Col 2","Col 3"};
    private Object[][] data = new Object[][]{{"1","2","3"},{"4","5","6"},{"7","8","9"}};

    public void setValueAt(int row, int col, String s) {
        data[row][col] = s;
        fireTableDataChanged(); //EDITED
    }

    public int getColumnCount() {
        return columnNames.length;
    }

    public int getRowCount() {
        return data.length;
    }

    public String getColumnName(int col) {
        return columnNames[col];
    }

    public Object getValueAt(int row, int col) {
        return data[row][col];
    }

    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }
}
0x6upsns

0x6upsns2#

String sql="SELECT * FROM "+tesztvalt+""; 

PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();

while (rs.next()) 
{
    tabla.setModel(model);
}

你有几个问题:
1.您错误地使用了PreparedStatement。您的代码可能可以工作(我不确定),但它没有利用PreparedStatement的特性。
1.从ResultSet读取数据的代码没有意义,因为您甚至没有从ResultSet阅读任何数据。
要使用PreparedStatement,代码如下:

String sql = "Select * from ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, tesztvalt );
stmt.executeQuery();

现在,PreparedStatement将使用适当的分隔符构建SQL查询,因此您不必担心这个问题。
阅读JCBC教程中关于Using Prepared Statements的部分以了解更多信息。
如果你想从一个特定的表中读取所有的数据,那么可以查看Table From Database中的TableFromDatabaseExample.java代码。它说明了如何构建查询以及如何访问列名和数据。

50pmv0ei

50pmv0ei3#

我认为最好和最常见的方法是将所有数据都放在JTable中,并使用基于组合框选择的过滤器。
在这个问题中,有人基于文本框完成了此操作。换一个组合很简单。
How can I filter rows in a JTable?
或者查看http://docs.oracle.com/javase/tutorial/uiswing/components/table.html并选择“排序和过滤”

相关问题