我正在使用ComboBox过滤掉我的JTable。 JTable由“需求”,“类型”,“合规性”列和“类型”标题使用的ComboBox组成。
JTable可以很好地显示数据,但是当我在ComboBox中选择一种类型时,将不会显示任何信息,并显示一个空白表。
我要在扩展JPanel并创建JTable的类下发布,并具有使用组合框,defaulttablemodel和TableRowSorter的逻辑
在主要方面,我只是使jtable和jscrollpane可见
package view;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
public class TempPanel extends JPanel {
//Global Variables
public JTable table;
public JScrollPane js;
DefaultTableModel dm;
JButton btnDisplay;
/**
* Create the panel.
*/
public TempPanel() {
initialize();
createColumns();
//Manually adding to Jtable
String rowReq[][] = {{"A", "1", null}, {"B", "2" ,null}, {"C", "2", null}};
addData(rowReq[0][0], rowReq[0][1], rowReq[0][2]);
addData(rowReq[1][0], rowReq[1][1], rowReq[1][2]);
addData(rowReq[2][0], rowReq[2][1], rowReq[2][2]);
}
public void addData(String req, String type, String compliance) {
// TODO Auto-generated method stub
String [] rowData = {req,type,compliance};
dm.addRow(rowData);
}
//Filter my data
private void filter(String query)
{
TableRowSorter<DefaultTableModel> tr = new TableRowSorter<DefaultTableModel>(dm);
table.setRowSorter(tr);
if ( query != "None")
{
tr.setRowFilter(RowFilter.regexFilter(query));
}
else
{
table.setRowSorter(tr);
}
}
private void createColumns() {
// TODO Auto-generated method stub
//Get table model
dm = (DefaultTableModel) table.getModel();
dm.addColumn("Requirements");
dm.addColumn("Type");
dm.addColumn("Compliance");
}
public void initialize()
{
JComboBox comboBox = new JComboBox();
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
String query = comboBox.getSelectedItem().toString();
filter(query);
}
});
comboBox.setModel(new DefaultComboBoxModel(new String[] {"Type1", "Type2", "Type3"}));
comboBox.setBounds(30, 11, 64, 20);
add(comboBox);
table = new JTable(dm);
table.setBounds(10, 42, 220, 127);
js = new JScrollPane(table);
add(js);
btnDisplay = new JButton("Display");
btnDisplay.setBounds(307, 10, 89, 23);
add(btnDisplay);
js.setVisible(false);
table.setVisible(false);
//Manually adding data to jtable
}
}