Search code examples
javaswingjpanellayout-managerborder-layout

How to add several panels with labels to a single frame?


I am learning Java Swings, and i am creating one frame and i want to add to it more than one panel with different orientations, as you see below in the code jpanet_1 and jpanel_2 each of them has a specific dimensions set using setBound() method.

The problem is at run time, "hello world" appears only in the second panel and does not appear in the first one. I tried to switch the order in which I am adding the two panels to the main frame as follows:

    jFrame_2.add(jPanel_2);
    jFrame_2.add(jPanel_1);

But then, the "hello world" is added to panel_2 only.

  1. Please let me know how to add the two panels to the frame so the the statement "hello world" appears in both

  2. As you see in the code, i a specifying dimensions to each panel I wish to add to the frame, then I add it, is there any other recommended way to add panels to frames?

pic

CODE:

  public class GUI_01 {

JFrame jFrame_1;
JFrame jFrame_2;
JPanel jPanel_1;
JPanel jPanel_2;
final JLabel jLabel_Hello = new JLabel("Hello World");
JOptionPane jOptions;
final String[] options = {"yes", "no", "maybe"};

public GUI_01() {
    // TODO Auto-generated constructor stub
    setUpGUI1();
    setUpGUI2();
}

private void setUpGUI2() {
    // TODO Auto-generated method stub
    jFrame_2 = new JFrame("Border Demo");
    jPanel_1 = new JPanel();
    jPanel_2 = new JPanel();
    
    jPanel_1.setBorder(BorderFactory.createTitledBorder("title"));
    jPanel_1.setBounds(30, 100, 110, 300);
    jPanel_1.add(jLabel_Hello);
    
    jPanel_2.setBorder(BorderFactory.createLoweredBevelBorder());
    jPanel_2.setBounds(20, 50, 120, 80);
    jPanel_2.add(jLabel_Hello);
    
    jFrame_2.setBounds(0, 0, 600, 600);
    jFrame_2.add(jPanel_1);
    jFrame_2.add(jPanel_2);
    jFrame_2.setVisible(true);
}

Solution

  • the problem is at run time, "hello world" appears only in the second panel and does not appear in

    That is correct. A component can only have a single parent.

    If you want the text "Hello World" then you need to create two JLabels and add one of the labels to each panel.

    JLabel label1 = new JLabel("Hello World");
    JPanel panel1 = new JPanel();
    panel1.add( label1 );
    JLabel label2 = new JLabel("Hello World");
    JPanel panel2 = new JPanel();
    panel2.add( label2 );
    

    I tried to use gridlayout but i could not place a jpanel in a specific cell of gridlayout..

    You can't just add components to random cells. You must have components in every cell, or in the case of a GridBagLayout, the component can span multiple cells.