0

I'm using a GUI builder to make a simple JFrame that contains a JPanel. I want to add a random number of JButtons to the panel, is it possible for me to do this without having to write my own code for the JPanel? I ask because I am not strong with Swing layouts.

Main class:

public static void main( String[] args )
{         
    int buttonCount = new Random().nextInt(5)+1;
    JFoo foo = new JFoo(buttonCount);
    foo.setVisible(true);
}

JFoo class:

public class JFoo extends javax.swing.JFrame {
int buttonCount;

public JFoo() {
    initComponents();
}
public JFoo(int buttonCount) {
    this.buttonCount = buttonCount;
    initComponents();
    buttonCountLabel.setText("Button Count: "+buttonCount);
}

private void initComponents() {
    //generated code
    ...
}

The UI

baxdab
  • 141
  • 3
  • 8
  • I'm using NetBeans if that helps. – baxdab Oct 02 '15 at 15:25
  • Can you elaborate what do you meant by `"without having to write my own code for the JPanel?"` ? – user3437460 Oct 02 '15 at 15:40
  • I mean I don't want to have to write the layout for the panel. I want to create an array of `JButton`s with size `buttonCount` and have them contained in the panel. I want this done without having to write my own layout (possibly with some feature of the builder). I was considering inserting an array of `JButton`s with size 5 and setting the number I need visible, but if I wanted to use 100 buttons instead of 5, I would have wasted memory. – baxdab Oct 02 '15 at 15:53
  • 1
    Create a panel using a GridLayout and specify how many button you want on each row. The layout will wrap buttons to a new row as required. – camickr Oct 02 '15 at 16:06
  • 1
    Your problem is your `"... in a GUI builder"` statement. If you need to create GUI components at run-time, you need to do this with code. Not GUI builder code, but code you've written. So have a look at the tutorials, and then try to write that code. – Hovercraft Full Of Eels Oct 02 '15 at 16:19
  • 2
    `"I want this done without having to write my own layout..."` -- also this doesn't make sense. You won't be "writing your own layout", but rather you'll be *using* a layout. This is one line of code: `myPanel.setLayout(new GridLayout(...);` Just fill in the parameters and that's it. What is your aversion towards doing this? – Hovercraft Full Of Eels Oct 02 '15 at 16:23

0 Answers0