Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing: Add a component by code in NetBeans

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 ?

like image 743
Renaud is Not Bill Gates Avatar asked Jan 05 '14 18:01

Renaud is Not Bill Gates


2 Answers

  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.
like image 60
Hovercraft Full Of Eels Avatar answered Oct 16 '22 13:10

Hovercraft Full Of Eels


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();
     }
    
like image 28
Paul Samsotha Avatar answered Oct 16 '22 12:10

Paul Samsotha