I have noticed that running the program I'm listing below sometimes produces an unwanted effect.
EDIT: I've simplified the code to make things look clear. I'm drawing a String which prints out the current component size. I've overriden the getPrefferedSize() method in the Component class and set width and height to 640 x 512 respectively. However, I'm still getting different results after running the program: 640 x 512 and 650 x 522. Weird thing is removing the frame.setResizable(false) line fixes things. But I want the window to be resizable
import java.awt.*;
import javax.swing.*;
public class DrawTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
DrawFrame frame = new DrawFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
});
}
}
class DrawFrame extends JFrame
{
private static final long serialVersionUID = 1L;
public DrawFrame()
{
setTitle("DrawTest");
setLocationByPlatform(true);
Container contentPane = getContentPane();
DrawComponent component = new DrawComponent();
contentPane.add(component);
}
}
class DrawComponent extends JComponent
{
private static final long serialVersionUID = 1L;
public Dimension getPreferredSize() {
return new Dimension(640, 512);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
String msg = getWidth() + " x " + getHeight();
g2.setPaint(Color.BLUE);
g2.drawString(msg, getWidth()/2, getHeight()/2);
}
}