[英]JTable fill data with JComboBox
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) 我有一个带有表,组合框的框架,我想通过组合框用数据库中的数据填充表,但是如果我与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 );
}
}
});
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();
}
}
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: 您有几个问题:
You are using the PreparedStatement
incorrectly. 您使用的PreparedStatement
错误。 Your code may work (I'm not sure), but it does not take advantage of the features of the PreparedStatement
. 您的代码可能可以运行(我不确定),但是它没有利用PreparedStatement
的功能。
The code that read the data from the ResultSet makes no sense because, well you aren't even reading any data from the ResultSet. 从ResultSet读取数据的代码没有意义,因为您甚至根本没有从ResultSet读取任何数据。
To use a PreparedStatement the code is something like: 要使用PreparedStatement,代码类似于:
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. 现在,PreparedStatement将使用适当的定界符来构建SQL查询,因此您无需担心。
If you want to read all the data from a specific table, then check out the TableFromDatabaseExample.java
code found in Table From Database . 如果要从特定表中读取所有数据,请检出Table From Database中的TableFromDatabaseExample.java
代码。 It shows how to build the query as well as how to access the column names and data. 它显示了如何构建查询以及如何访问列名和数据。
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. 我认为最好和最常见的方法是将所有数据存储在JTable中,并使用基于组合框选择的过滤器。
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? 如何过滤JTable中的行?
Or for a tutorial look at http://docs.oracle.com/javase/tutorial/uiswing/components/table.html and select "Sorting and Filtering" 或者,有关教程的信息,请访问http://docs.oracle.com/javase/tutorial/uiswing/components/table.html,然后选择“排序和过滤”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.