- Make sure that the JPanel is not using GroupLayout. Most any other layout would work well, but likely for the moment, JPanel's default FlowLayout will work best.
- Be sure to call
revalidate()
andrepaint()
on the JPanel after adding a component, if you are adding the component after the GUI has been rendered, such as on a button push. - If still having problems, show your code.
- General advice: avoid using code generation utilities until after you understand the underpinnings of the GUI library, here Swing. You won't regret doing this.
Java Swing: Add a component by code in NetBeans
-
24-09-2022 - |
Question
I'm using NetBeans, and I've a JFrame
where I added a JPanel
to it using the NetBeans's palette.
I want to add a JRadioButton
manually to that JPanel
, so this is the code I tried in the constructor :
ButtonGroup group = new ButtonGroup();
JRadioButton btn1 = new JRadioButton("btn1 ");
JPanel1.add(btn1);
But when I run that JFrame
I don't see that JRadioButton
anywhere, but it works when I add it using the NetBens's
palette.
How can I solve this problem ?
Solution
OTHER TIPS
The problem with NetBeans GUI Builder is that it initializes everything for you, where you can't alter the code unless you open the file on some other platform. In which case you have the risk of totally messing up the code.
What I can suggest is to maybe attempt something like this
- Create an empty
JPanel
with a preferred size that you set in theproperty
pane. You may also want to set the layout also, depending on your requirements. After the
initComponent()
then add theJRadioButtons
public MyGUI(){ initComponents(); ButtonGroup group = new ButtonGroup(); JRadioButton btn1 = new JRadioButton("btn1 "); jPanel1.add(btn1); jpanel1.revalidate(); // as @Hovercraft Full Of Eels suggested jPanel1.repaint(); }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow