[英]How can I make my JTable appear on button click?
The following code works, but only after the Display Values and the resize button is pushed. 以下代码有效,但仅在按下“显示值”和“调整大小”按钮之后。 It does not appear until after I push both the Display Values and the resize button is pushed. 直到同时按下“显示值”和“调整大小”按钮后,它才会出现。 How do I make it appear when only the Display Values button is pushed? 当仅按“显示值”按钮时,如何显示它?
public class myClass extends JFrame{
String[] colNames = {"Item Name",
"Department",
"Original Price",
"Sales Price"};
Object[][] input = {
{"Kathy", "Smith",
new Double(10), new Integer(5)},
{"John", "Doe",
new Double(10), new Integer(3)},
{"Sue", "Black",
new Double(10), new Integer(2)},
{"Jane", "White",
new Double(10), new Integer(20)},
{"Joe", "Brown",
new Double(10), new Integer(10)}
};
//display values
JButton buttonDisplay = new JButton();
buttonDisplay.setText("Display Values");
container.add(buttonDisplay);
buttonDisplay.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
JTable jt = new JTable( input, colNames );
JScrollPane pane = new JScrollPane( jt );
jt.setPreferredScrollableViewportSize(
new Dimension(200,200));
pane.add(jt);
container.add( pane );
container.add(jt);
/*Must use a JTextBox or JTable to display all the stored values for:
*
* Item name
Department
Original price
Sale price
*/
}
});
You only need to add the scrollpane, not both the scrollpane and the table. 您只需要添加滚动窗格,而无需添加滚动窗格和表格。 So remove the 因此,删除
container.add(jt);
line. 线。 Further, if you add something to a Container
which is already visible, you should invalidate the Container
as explained in the javadoc. 此外,如果您向已经可见的Container
添加内容,则应按照javadoc中的说明使Container
无效。 Adding 新增中
container.revalidate();
container.repaint();
should make the table visible. 应该使表格可见。
Try calling pack()
after you add the new component. 添加新组件后,尝试调用pack()
。 This will resize your JFrame to fit everything. 这将调整您的JFrame的大小以适合所有情况。 This is what I assume your "resize button" is doing. 这就是我假设您的“调整大小按钮”正在执行的操作。
public void actionPerformed(ActionEvent evt) {
// ... your other code ...
container.pack();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.