A.Y
A.Y

Reputation: 137

Java GridBagLayout positioning

i'm trying to make a window with GridBagLayout, here are my code:

   import java.awt.FlowLayout;
   import java.awt.GridBagConstraints;
   import java.awt.GridBagLayout;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;

   import javax.swing.JButton;
   import javax.swing.JFrame;
   import javax.swing.JPanel;
   import javax.swing.JScrollPane;
   import javax.swing.JTextArea;

   public class ReadMessage extends JFrame implements ActionListener
   {
JButton Last;
JButton Delete;
JButton Store;
JButton Next;
JTextArea MessageBox;

public ReadMessage()
{
    setLayout(new FlowLayout());
    JPanel Panel = new JPanel();
    add(Panel);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Panel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();


    MessageBox = new JTextArea();
    MessageBox.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(MessageBox, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    MessageBox.setLineWrap(true);
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 4;
    c.weightx = 0.0;
    c.ipady = 300;
    c.ipadx = 300;
    Panel.add(scrollPane, c);


    Last = new JButton("Last");
    c.gridx = 0;
    c.gridy = 1;
    c.ipady = 0; 
    c.weightx = 0.5;
    Panel.add(Last, c);
    Last.addActionListener(this);

    Delete = new JButton("Delete");
    c.gridx = 1;
    c.gridy = 1;
    c.ipady = 0; 
    c.weightx = 0.5;
    Panel.add(Delete, c);
    Delete.addActionListener(this);

    Store = new JButton("Store");
    c.gridx = 2;
    c.gridy = 1;
    c.ipady = 0; 
    c.weightx = 0.5;
    Panel.add(Store, c);
    Store.addActionListener(this);

    Next = new JButton("Next");
    c.gridx = 3;
    c.gridy = 1;
    c.ipady = 0; 
    c.weightx = 0.5;
    Panel.add(Next, c);
    Next.addActionListener(this);

}



}

and it turns out to be something like this enter image description here

what i really want is like this

enter image description here

I know i did terribly wrong but i can't figure out what exactly i did wrong, I read the docs on oracle but couldn't find a thing, could you point out what i did wrong, and how to fix it? thank you very much

Upvotes: 0

Views: 46

Answers (2)

JB Nizet
JB Nizet

Reputation: 691715

All your buttons have a gridwidth of 4 instead of 1.

Upvotes: 3

camickr
camickr

Reputation: 324108

You can nest panels each using a different layout manager to achieve your desired layout.

  1. Create a main panel with a BorderLayout and add this panel to the frame
  2. Add the JTextArea to the BorderLayout.CENTER of the main panel
  3. Create a second panel for the buttons and use a FlowLayout. Then add the buttons to this panel. Then this panel can be added to the main panel at the BorderLayout.PAGE_END.

Upvotes: 1

Related Questions