java,gui,现在弹窗中有一个表格,两个下拉菜单栏。例如,表格第一列记录了学生的性别,第二列为年龄。第一行为“zhang”,28。第二列为“wang”,19。第三列为“zhang”,19,第四列为“wang”,28。则第一个菜单栏为性别,下拉选项有“zhang”,“wang”,第二个菜单栏叫年龄,下拉选项为19,28。通过下拉菜单栏可以实现筛选表格的功能。可以分别筛选,也可以两个菜单栏一起筛选。注释放在外面,不要放在整体代码里
时间: 2023-08-12 20:03:16 浏览: 137
可以筛选的下拉菜单
以下是一个简单的Java GUI程序,包含一个表格和两个下拉菜单栏。你可以在菜单栏中选择性别和年龄来筛选表格。
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableFilterDemo extends JFrame {
private JComboBox<String> genderComboBox;
private JComboBox<Integer> ageComboBox;
private JTable table;
public TableFilterDemo() {
// 初始化表格数据
Object[][] data = {
{"zhang", 28},
{"wang", 19},
{"zhang", 19},
{"wang", 28}
};
String[] columnNames = {"Gender", "Age"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
// 创建表格和下拉菜单栏
table = new JTable(model);
genderComboBox = new JComboBox<String>(new String[]{"zhang", "wang"});
ageComboBox = new JComboBox<Integer>(new Integer[]{19, 28});
// 创建筛选器并添加到表格模型中
RowFilter<DefaultTableModel, Object> genderFilter = new RowFilter<DefaultTableModel, Object>() {
public boolean include(Entry<? extends DefaultTableModel, ? extends Object> entry) {
String gender = (String)entry.getValue(0);
return gender.equals(genderComboBox.getSelectedItem());
}
};
RowFilter<DefaultTableModel, Object> ageFilter = new RowFilter<DefaultTableModel, Object>() {
public boolean include(Entry<? extends DefaultTableModel, ? extends Object> entry) {
Integer age = (Integer)entry.getValue(1);
return age.equals(ageComboBox.getSelectedItem());
}
};
RowFilter<DefaultTableModel, Object> compoundFilter = RowFilter.andFilter(java.util.Arrays.asList(genderFilter, ageFilter));
((DefaultTableModel)table.getModel()).setRowFilter(compoundFilter);
// 添加下拉菜单栏的监听器
genderComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
((DefaultTableModel)table.getModel()).setRowFilter(compoundFilter);
}
});
ageComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
((DefaultTableModel)table.getModel()).setRowFilter(compoundFilter);
}
});
// 创建主面板并添加组件
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JLabel("Gender:"), BorderLayout.WEST);
panel.add(genderComboBox, BorderLayout.CENTER);
panel.add(new JLabel("Age:"), BorderLayout.EAST);
panel.add(ageComboBox, BorderLayout.SOUTH);
add(panel, BorderLayout.NORTH);
add(new JScrollPane(table), BorderLayout.CENTER);
// 设置窗口属性并显示
setTitle("Table Filter Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
TableFilterDemo demo = new TableFilterDemo();
}
}
```
阅读全文