简体   繁体   中英

add jbutton to jpanel after creation

I'm trying to add a JButton to a JPanel sitting in a JFrame during the running of the program. The button actually works (is clickable) but doesn't appear.

JButton takeOffButton = new JButton();
    takeOffButton.setText("Take Off");
    takeOffButton.setBounds(30, 30, 100, 100);
    takeOffButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            Game.switchState(GameState.SPACE, Game.player.curPlanet);
        }

    });
    takeOffButton.setVisible(true);

    panel.add(takeOffButton);

I've set both the Frame and panel's layout to null using setLayout(null)

What might be going on here?

EDIT: I tried simply adding a jbutton to a jpanel in the panel's constructor and not even that is working..

See my comment about layout managers! If you have a null manager, you have to override your panel's paintChildren method and place the children yourself. It is much, much simpler to use a layout manager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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