Search code examples
javaswinglayoutframegrouplayout

GroupLayout does not give required result


Here I add the buttons but none of them is displayed on my frame also when i add button individually they overlap each other what should i do can some one find problem in my code I have been referral to this site: https://weblogs.java.net/blog/tpavek/archive/2006/02/getting_to_know_2.html

Code: import java.awt.; import javax.swing.; import java.awt.event.; import static javax.swing.GroupLayout.Alignment.;

class Abc extends JFrame
{
JButton b[];

Abc()
{
b=new JButton[5];
JPanel jp=new JPanel();
for(int i=0;i<b.length;i++)
{
b[i]=new JButton();
}
GroupLayout layout=new GroupLayout(jp);
jp.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);

layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(b[0])
.addComponent(b[1])
.addComponent(b[2])
.addGroup(layout.createParallelGroup(LEADING)
        .addComponent(b[3])
        .addComponent(b[4]))
);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(BASELINE)
.addComponent(b[0])
.addComponent(b[1])
.addComponent(b[2])
.addComponent(b[3]))
.addComponent(b[4])
);
setTitle("kuvh b");
setSize(1000,1000);
//for(int i=0;i<5;i++)
//{
add(b[0]);
add(b[2]);
pack();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel(
                                  "javax.swing.plaf.metal.MetalLookAndFeel");
                                //  "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                                //UIManager.getCrossPlatformLookAndFeelClassName());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                new Abc().setVisible(true);
            }
        });
    }
}

The code is resulting in the following, which is not what I wanted. please tell me the solution to this problem


Solution

  • You have to add the panel jp to your frame if you want it to appear there. You add buttons 0 and 2, but not the panel that I can see.