简体   繁体   English

按下JButton后将JTable放在JPanel上

[英]Placing JTable on JPanel after JButton is pressed

When I run this code, the button shows up on the JPanel but once I click the button, nothing happens. 当我运行此代码时,按钮显示在JPanel上,但是一旦我单击按钮,就没有任何反应。 Any suggestions on where I'm going wrong here? 关于我在哪里出错的任何建议? Sorry if it's really simple. 对不起,如果真的很简单。 I'm fairly new when it comes to GUIs. 在GUI方面,我相当新。

final JPanel card3 = new JPanel();
//Tetris setup
JButton startGame = new JButton("START GAME");
card3.setLayout(new GridBagLayout());
GridBagConstraints gbc2 = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2,2,2,2);
card3.add(startGame, gbc2);
gbc.gridy = 1;
startGame.addActionListener(new ActionListener() {          
    @Override
    public void actionPerformed(ActionEvent e) {
        Tetris game = new Tetris();
        JTable table = new JTable(game.getNumRows(), game.getNumCols());
        card3.add(table);
    }
});

Normally you would add the table to a JScrollPane and then add the scrollpane to the panel. 通常,您将表添加到JScrollPane,然后将滚动窗格添加到面板。 This way you will automatically get the table header to appear. 这样,您将自动获取表标题。

When you add a component to a visible GUI you need code like: 将组件添加到可见GUI时,您需要以下代码:

panel.add( scrollPane );
panel.revalidate();

This will cause the layout manager to be invoked to it can lay out all the components again. 这将导致调用布局管理器,它可以再次布局所有组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM