Java Swing: Add a component by code in NetBeans
Asked Answered
I

2

6

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 ?

Imprest answered 5/1, 2014 at 18:29 Comment(0)
K
8
  1. 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.
  2. Be sure to call revalidate() and repaint() 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.
  3. If still having problems, show your code.
  4. 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.
Kirovabad answered 5/1, 2014 at 18:33 Comment(3)
I think it's using GroupLayout, but where can I change it in netbeans ?Imprest
@SuSha: you can check the JPanel's properties and it will tell you exactly what layout it's using and allow you to change it. But again, check out the Swing Tutorials, put NetBeans's code generation aside, and first learn to code all by hand.Kirovabad
Okey, thanks for help, I found where I can change the layout, but I don't know which layout I should use.Imprest
C
3

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 the property pane. You may also want to set the layout also, depending on your requirements.
  • After the initComponent() then add the JRadioButtons

     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();
     }
    
Crossrefer answered 5/1, 2014 at 18:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.