JTable fill data with JComboBox

核能气质少年 提交于 2019-11-28 12:24:20

问题


I have a frame with table,combobox, i want to fill the table with data from database by combobox, but if i use with itemlistener i dont see the table, without itemlistener and String sql="select * from Arlista" then i see my table with data (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 );
        }
    }
});

回答1:


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

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

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

You have a couple of problems:

  1. You are using the PreparedStatement incorrectly. Your code may work (I'm not sure), but it does not take advantage of the features of the PreparedStatement.

  2. The code that read the data from the ResultSet makes no sense because, well you aren't even reading any data from the ResultSet.

To use a PreparedStatement the code is something like:

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

Now the PreparedStatement will build the SQL query with the proper delimiters so you don't need to worry about that.

If you want to read all the data from a specific table, then check out the TableFromDatabaseExample.java code found in Table From Database. It shows how to build the query as well as how to access the column names and data.




回答2:


This is a slightly different way, but it is simple. When you select an item from the combo box, the table changes. It uses a table model:

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



回答3:


I think the best and most common approach is to have all the data in the JTable and use a filter which is based on the combobox selection.

In this question someone has done this based on a Text box. Changing for a combo would be simple.

How can I filter rows in a JTable?

Or for a tutorial look at http://docs.oracle.com/javase/tutorial/uiswing/components/table.html and select "Sorting and Filtering"



来源:https://stackoverflow.com/questions/24081941/jtable-fill-data-with-jcombobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!