Reduce size of jpanels

859 views Asked by At

I have a frame with GridLayout(3,0).These 3 rows have 3 different panels.
Panel-1:

  • JTextArea inside a JScrollPane

Panel-2:(BoxLayout.Y_AXIS)

  • 4 JPanels with FlowLayout, each consisting of
    a)JRadioButton b)JTextField

Panel-3:

  • A simple JButton


As seen in the picture, I provided different background colors for each Panel. My target is to reduce the size of each JPanel to fit the contents.

JPanels layout

Code:

private static JFrame f;
private static JPanel p1,p2,p3;
private static JPanel rbtf[];
private static ButtonGroup bg;
private static JRadioButton jb[];   
private static JTextField tf[];

private static JTextArea qtn;
private static JScrollPane sp;
private static JButton submitbtn,nextbtn,prevbtn;   

public static void build(JFrame frame){
    f=frame;    
    f.setLayout(new GridLayout(3, 0));
    p1=new JPanel();
    p1.setSize(600, 100);
    p1.setBackground(Color.BLUE);
    p2=new JPanel();
    p2.setLayout(new BoxLayout(p2,BoxLayout.Y_AXIS));
    p2.setSize(600, 200);
    p2.setBackground(Color.RED);
    p3=new JPanel();
    p3.setBackground(Color.RED);
    p3.setSize(600, 100);
    rbtf=new JPanel[4];
    jb=new JRadioButton[4];
    bg=new ButtonGroup();
    tf=new JTextField[4];

    qtn=new JTextArea(3,45);        
    sp=new JScrollPane(qtn);        
    p1.add(sp);

    for(int i=0;i<4;i++){
        jb[i]=new JRadioButton();
        tf[i]=new JTextField(10);           
        rbtf[i]=new JPanel();
        rbtf[i].setLayout(new FlowLayout());
        rbtf[i].setBackground(Color.GRAY);
        bg.add(jb[i]);  
        rbtf[i].add(jb[i]);
        rbtf[i].add(tf[i]);
        p2.add(rbtf[i]);
    }

    submitbtn = new JButton("ADD QUESTION");
    p3.add(submitbtn);      

    f.getContentPane().add(p1);f.getContentPane().add(p2);f.getContentPane().add(p3);
    f.setVisible(true);
    f.setSize(new Dimension(600, 400));
    f.setLocationRelativeTo(null);
  }
}
0

There are 0 answers