X1XX
X1XX

Reputation: 141

Adding two panels to a JFrame in Java

So what I'm trying to do is have 2 panels (it has to be panels) inside of a JFrame and have 1 a certain size, the other a smaller size and having the smaller sized one painted a certain color.

public class Binary{

private JLabel header;
private JTextField userInput1;
private JButton doIt;
private JButton clear;
private JRadioButton binary, decimal;
private JLabel number2;
private JFrame frame1;
private JPanel panel1;
private JPanel panel2;

public Binary(){

    frame1 = new JFrame("Number Converter"); // frame 
    frame1.setLayout(new FlowLayout());
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    panel1 = new JPanel(); // first panel (light grey)
    panel1.setSize(250, 475);
    frame1.add(panel1);

    header = new JLabel("1- Select the mode: ");
    panel1.add(header);

    ButtonGroup choices= new ButtonGroup();
    binary = new JRadioButton("Binary to Decimal"); // add the first radiobutton binary to decimal
    choices.add(binary);
    decimal = new JRadioButton("Decimal to Binary"); // add the second radiobutton decimal to binary
    choices.add(decimal);
    frame1.add(binary); // adds both to the program
    frame1.add(decimal);

    userInput1 = new JTextField(20); // Adds a blank text field for user input
    frame1.add(userInput1);

    number2 = new JLabel("2- Enter some words then click Do It:"); 
    frame1.add(number2);

    panel2 = new JPanel(); // second panel, bottom dark grey
    panel2.setOpaque(true);
    panel2.setBackground(Color.GRAY);
    panel2.setSize(500, 500);
    frame1.add(panel2);

    doIt = new JButton("Do It"); // left button do it
    frame1.add(doIt);

    clear = new JButton("Clear"); // right button clear
    frame1.add(clear);

    frame1.setSize(250, 500);
    frame1.setVisible(true);
}

}

For some reason, my code here basically outputs a minuscule panel on top of my first panel. Is there something I'm missing?

Upvotes: 1

Views: 347

Answers (1)

PabloJ
PabloJ

Reputation: 308

I found 2 possible answers to your problem.

  1. You can add the two buttons (Do it & Clear), to panel2. Which would end up like this:

1st solution

  1. You can add a blank JLabel to panel2.

    size = new JLabel("//You can add as many spaces here as you want, the more you have, the larger it will be horizontaly");

    panel2.add(size);

    //If you want to make it larger verticaly, just make more JLabels and add them to panel2.

The result of this one will be something like this:

2nd solution

Best of luck!

Upvotes: 2

Related Questions