Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

java - How to Dynamically Add JButton to JPanel?

In NetBeans, I have used the GUI editor to make a JFrame and I've put a JPanel in the frame. At the moment, I'm trying to make a new button in the panel when the class constructs. This is the code I have, but I can't seem to get it to work. (The first line makes the button, the other lines try to show it.)

this.jPanel2.add(new JButton("Test"),BorderLayout.NORTH);
this.jPanel2.validate();
this.jPanel2.revalidate();
this.jPanel2.repaint();
this.jPanel2.setVisible(true);
this.revalidate();
this.setVisible(true);
this.repaint();

I've been googling all night, but can't seem to get it to work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Some times when you don't see a button it is a layout manager issue (as in you aren't setting the right properties for the layout manager). You can test this by disabling it:

this.jPanel2.setLayoutManager(null);

And setting bounds for the button (JButton.setBounds()).

If the above fixes your problem, then you need to look into the requirements set by the LayoutManager you are using (see also the answer by Robin).

All the calls to validate(), revalidate() and repaint() are not needed to do this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...