Reputation: 77
I'm a newbie. Trying to make auto resize border. I made border on my frame with 2 panels. I added panels with border into first panel.
I want border which retreated from all edges. In this border panel I also added text panel and button. When I expand the window, or resize it panel with border is resizing too. But there is not indents from edges when I am using BorderLayout.
public class App {
private JFrame frame;
private JPanel panel;
private JPanel panel_1;
private JTextField textField;
private JButton addBtn;
public static void main(String args[]) {
App app = new App();
app.initialize();
app.frame.pack();
app.frame.setVisible(true);
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
panel.setLayout(new BorderLayout(0, 0));
panel_1 = new JPanel();
panel_1.setPreferredSize(new Dimension(784, 40));
panel_1.setBorder(new LineBorder(new Color(0, 0, 0)));
panel.add(panel_1, BorderLayout.CENTER);
textField = new JTextField();
textField.setPreferredSize(new Dimension(6, 24));
panel_1.add(textField);
textField.setColumns(50);
addBtn = new JButton("Add");
addBtn.setPreferredSize(new Dimension(70, 24));
panel_1.add(addBtn);
}
}
This is with BorderLayout - http://snag.gy/S43C2.jpg. Also I tried with FlowLayout in panel - http://snag.gy/ndjDG.jpg
Can you help me please?
Upvotes: 1
Views: 2753
Reputation: 51565
I'm assuming that this is the GUI you're trying to create.
To create this GUI, you need to use multiple JPanels with more than one Swing layout manager.
Here's the hierarchy of Swing components I would use.
JFrame - border layout
JPanel - main panel, border layout
JPanel - text, button panel, border layout, border north
JTextField - border center
JButton - border east
JScrollPane - border center
JTable
JPanel - button panel, flow layout, border south
JButton (3)
You get the spacing by setting an empty border on the JPanels and JScrollPane. The empty border can be as wide as you wish.
Upvotes: 3
Reputation: 9717
The problem is that because you set the border on a panel that you add into BorderLayout.NORTH
. When you resize the window, BorderLayout.NORTH
section will only resize horizontally, that's why the border will not be resized correctly.
public static void main(String args[]) {
JavaApplication11 app = new JavaApplication11();
app.initialize();
app.frame.pack();
app.frame.setVisible(true);
}
private JFrame frame;
private JPanel panel;
private JTextField textField;
private JButton addBtn;
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
frame.add(panel);
Border border = new CompoundBorder(new EmptyBorder(5, 10, 15, 20), new LineBorder(Color.BLACK));
panel.setBorder(border);
textField = new JTextField(50);
panel.add(textField);
addBtn = new JButton("Add");
panel.add(addBtn);
}
Upvotes: 5