Reputation: 11
Is it possible to have a north and south component in the same JPanel
? For example, I want text to display with a 2 x 2 grid layout below. How could I change this code to make that happen? I'm new to Java Swing and am not sure where I should look.
public CompView(){
super("Super");
setResizable(false);
setLocationRelativeTo(null);
JPanel northPanel = new JPanel();
JPanel middlePanel = new JPanel();
JPanel southPanel = new JPanel();
getContentPane().add(northPanel, BorderLayout.NORTH);
northPanel.add(new JLabel("TITLE", CENTER));
northPanel.setLayout(new GridLayout(2,2));
northPanel.add(new JLabel("Text: "));
northPanel.add(new JTextField());
northPanel.add(new JLabel("Text: "));
northPanel.add(new JTextField());
getContentPane().add(middlePanel, BorderLayout.CENTER);
middlePanel.setLayout(new GridLayout(2,1));
middlePanel.add(new JLabel("Title 2:", CENTER));
middlePanel.add(new JTextField());
}
Current Image
I would like the output to look like this:
| Super |_| |X|
---------------------------- --|
| Title | |
---------------------------- |
| Text: | JTextField 1 | | } North Panel
---------------------------- |
| Text: | JTextField 2 | | |
---------------------------- --|
| Title 2 | |
---------------------------- } Center Panel
| | Resizable JTextField | | |
---------------------------- --|
Hope this diagram helps.
Upvotes: 1
Views: 2664
Reputation: 18792
A common strategy to solve complex computing tasks, is to break them into small, well defined manageable tasks. Divide and conquer.
This also applies to gui: break the design into small, easy to layout containers. In this case start by dividing the design into 2 areas, as you did (north and south), and subdivide each. For example:
The basic ideas is to divide the layout into smaller areas, each having simple distinct layout that can be implemented by one layout manager.
An implementation of the north part could look like:
//avoid extends JFrame. Use for simplification
public class CompView extends JFrame{
CompView(){
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel northPanel = new JPanel(new GridLayout(2,0));
FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER);
JPanel titlePanel = new JPanel(layout1);
titlePanel.add(new JLabel("TITLE"));
northPanel.add(titlePanel);
FlowLayout layout2 = new FlowLayout(FlowLayout.LEFT);
JPanel textfieldPanel1 = new JPanel(layout2);
textfieldPanel1.add(new JLabel("Text: "));
JTextField txt = new JTextField();
txt.setColumns(5);
textfieldPanel1.add(txt);
northPanel.add(textfieldPanel1);
add(northPanel, BorderLayout.NORTH);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new CompView());
}
}
Upvotes: 2