I am creating a form with a JPanel inside it for some graphic elements and some buttons for managing the thing. For some reason, I have to specify the JPanel 10 pixels less than the width and 30 pixels less than the actual graphics that I want to place inside it. What causes this problem?
This is the code:
public class Window {
public Sheepness sheepness;
public ButtonPanel buttonPanel;
public PaintPanel paintPanel;
public JFrame frame;
public Window(Sheepness sheepness) {
this.sheepness = sheepness;
frame = new JFrame("Sheepness simulation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout frameLayout = new BorderLayout();
JPanel background = new JPanel(frameLayout);
background.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
buttonPanel = new ButtonPanel(this);
background.add(BorderLayout.SOUTH, buttonPanel.buttonBox);
paintPanel = new PaintPanel(this);
paintPanel.setPreferredSize(new Dimension(320, 240));
background.add(BorderLayout.CENTER, paintPanel);
frame.getContentPane().add(background);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}
public class PaintPanel extends JPanel {
public Window window;
public PaintPanel(Window window) {
this.window = window;
}
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.blue);
g.fillRect(0, 0, 320, 240);
}
}
Screenshot with preferred 320 x 240 size:
Cannot find the original image http://www.cmbi.ru.nl/~estens/Sheepness/Sheepness_simulation_border.png .
You can see that 320 x 240 fillRect does not completely fill the JPanel, there remains a border of width 10 px and height 30 px.
Screenshot with preferred size 310 x 210:
http://www.cmbi.ru.nl/~estens/Sheepness/Sheepness_simulation_noBorder.png.
320 x 240 fillRect!
?