我有一个代码,为给定的布尔表达式生成一个真值表。例如,考虑用户输入表达式(A + B)+(C + D)。我有一个字符串数组headers[]
,它将存储真值表所有必需的标题。
在这种情况下,它将包含:"A", "B", "C", "D", "A+B", "C+D", "(A+B)+(C+D)"
然后生成的真值表(2d int array TruthTable[][]
)将包含以下数据:
0000000
1000101
0100101
1100101
0010011
1010111
0110111
1110111
0001011
1001111
0101111
1101111
0011011
1011111
0111111
1111111
因此headers[]
数组的第一个元素将对应TruthTable[][]
的第一列。如何考虑这些数据动态生成真值表(使用JTable)?
答案 0 :(得分:1)
使用 DefaultTableModel 创建 JTable ,并向表模型插入新行。 它的教程JTable and Model
表的简单示例:
public class Example extends JFrame{
private JTable table;
private DefaultTableModel modelTable;
public Example(){
init();
}
private void init() {
table = new JTable();
table.setGridColor(Color.BLACK);
table.setAutoResizeMode(2);
modelTable = new DefaultTableModel(new Object[][]{}, new String[] {"A", "B", "C"});
table.setModel(modelTable);
Object[][] data = new Object[][]{{"1","2","3"},{"4","5","6"}};
for(int i =0;i<data.length;i++){
modelTable.addRow(data[i]);
}
}
public static void main(String... s){
Example p = new Example();
p.add(new JScrollPane(p.table));
p.pack();
p.setVisible(true);
}
}
答案 1 :(得分:0)
@ alex2410在他说要使用DefaultTableModel时有一点。
如果您在使用FormLayout时遇到问题,请下载JGoodies表单或简单更改布局=)
也许这就是你要找的东西:
public class ThruthTablePanel extends JPanel {
private JScrollPane scrollPane;
private JTable table;
/**
* Create the panel.
*/
public ThruthTablePanel() {
initComponents();
}
private void initComponents() {
String columnsLayout = "3dlu, default:grow, 3dlu";
String rowsLayout = "3dlu, default:grow, 3dlu";
setLayout(new FormLayout(columnsLayout, rowsLayout));
scrollPane = new JScrollPane();
add(scrollPane, "2, 2, fill, fill");
Object[] headers = new Object[] { "A", "B", "C",
"D", "A+B", "C+D",
"(A+B)+(C+D)" };
String[] results = new String[] { "0000000", "1000101", "0100101",
"1100101", "0010011", "1010111", "0110111", "1110111",
"0001011", "1001111", "0101111", "1101111", "0011011",
"1011111", "0111111", "1111111" };
DefaultTableModel model = new DefaultTableModel(new Object[][] {}, headers);
model.setRowCount(results.length);
table = new JTable(model);
for (int j = 0; j < results.length; j++) {
for (int i = 0; i < results[j].length(); i++) {
model.setValueAt(results[j].charAt(i), j, i);
}
}
table.setFillsViewportHeight(true);
scrollPane.setViewportView(table);
}
public static void main(String[] args) {
JFrame frm = new JFrame();
frm.setContentPane(new ThruthTablePanel());
frm.setSize(new Dimension(400, 400));
// frm.pack();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
但是,如果填充了ThruthTable [] [],则可以将其作为参数传递给模型。
DefaultTableModel model = new DefaultTableModel(/* Here you put your ThruthTable Vector */, headers);
table = new JTable(model);