I'm making a Scorched Earth like game in Java (for my exam project :D), but I have this problem. I'm drawing a window (JFrame), setting layout to BorderLayout, applying an extended JPanel, and packing the window, but after it has been packed, it's showing some extended white space at the left and bottom border.
This is my main class:
public class Main {
public static void main(String[] args) {
javax.swing.JFrame frame = new javax.swing.JFrame("game title");
panel p = new panel(new java.awt.Dimension(512, 512));
frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new java.awt.BorderLayout());
frame.getContentPane().add(p, java.awt.BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}
panel is my JPanel class, which in the constructor is setting it's preferred size to the argument (512x512). I've tested this on both Windows and Linux, and the error it at both places, and the size of the white gap differs from OS to OS.
This is my panel class:
class panel extends javax.swing.JPanel{
panel(java.awt.Dimension size){
setPreferredSize(size);
}
public void paint(java.awt.Graphics g){
g.setColor(java.awt.Color.BLUE);
g.fillRect(0, 0, 512, 512);
}
}
Please help!
I've tried to reproduce this without your panel class (which needs a better name and should at least be named using CamelCase):
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("game title");
JPanel p = new JPanel();
p.setPreferredSize(new java.awt.Dimension(512, 512));
p.setBackground(java.awt.Color.BLUE);
frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new java.awt.BorderLayout());
frame.getContentPane().add(p, java.awt.BorderLayout.CENTER);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}
This produces a window with a blue 512x512 panel in it and no differently-colored border. So the problem must be with your panel class.
saua,
This isn't what you asked, but it's important never the less... You don't override paint in swing; instead you override paintComponent.
See Sun's "Custom Painting" tutorial: http://java.sun.com/docs/books/tutorial/uiswing/painting/
In fact, I strongly suggest (considering your choice of project) that you go through the whole Swing tutorial. It takes "a while", but it's worth the time.
Cheers. Keith.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With