Reputation: 3283
I've been staring at my code for hours, and I've cut out almost everything down to the simplest bits and I don't know how to make a JPanel expand to the size of the frame. Ideally (in the end) I'd like a container panel with a north and south content panels. The north panel needs to take up whatever space is leftover once the south panel is placed.
For now, though, I have a tiny red speck that is only as big as its content. Can someone give me some insight into what I am doing fundamentally wrong?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class TestCode extends JFrame {
private DescriptionPanel window = new DescriptionPanel();
public static void main(String[] args){
TestCode frame = new TestCode();
frame.pack();
frame.setTitle("Grape Project");
frame.setLocationRelativeTo(null);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public TestCode(){
add(window);
}
}
And the DescriptionPanel class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DescriptionPanel extends JPanel{
private JPanel container = new JPanel();
public DescriptionPanel(ImageIcon pic, JLabel text){
container.setBackground(Color.red);
add(container);
}
}
Upvotes: 2
Views: 4689
Reputation: 53616
This is a typical BorderLayout
scenario.
By default, JPanel
s have a FlowLayout
already set, so you need to call setLayout
, or you can initialize your DescriptionPanel
with the proper layout manager :
super(new BorderLayout());
// setLayout(new BorderLayout());
add(top, BorderLayout.CENTER); // take all available upper space left
add(bottom, BorderLayout.SOUTH); // take the vertical space specified
Upvotes: 6
Reputation: 16294
Set the LayoutManager
to BorderLayout
:
setLayout(new BorderLayout());
Upvotes: 5