When I set the size of the JFrame its set the size of the frame itself including the borders. I tried creating a new content Panel and set that size instead of setting the size of the frame itself but it isn't working here is the code:
frame = new JFrame();
JPanel jp = new JPanel();
frame.setTitle(title);
//frame.setSize(width, height);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//insets = frame.getInsets();
//frame.setSize(new Dimension(insets.left + width + insets.right, insets.top + height + insets.bottom));
jp.setPreferredSize(new Dimension(width, height));
frame.setContentPane(jp);
frame.pack();
frame.setVisible(true);
So using insets isn't working and using a new ContentPane is also not working I hope it is clear enough.
EDIT: It's working now I extended the class with Canvas set it's size to width and height and then added it to the JFrame then packed it. This works! But why I think caused it was not the sizing but the way I rendered it, I got the bufferStrategy from the JFrame instead of the canvas which is not the way it should be.
Override getPreferredSize()
to set the preferred size of the JPanel
.
Sample code:
JPanel panel =new JPanel (){
@Override
public Dimension getPreferredSize() {
return new Dimension(..., ...);
}
}
See Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
Use SwingUtilities.invokeLater() or EventQueue.invokeLater() to make sure that EDT is initialized properly.
sample code:
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// GUI related code goes here (not heavy task)
}
});
}
See SwingUtilities.invokeLater
Why are you setting new content pane of JFrame
? Just add in the default content pane using frame.getContentPane().add(panel)
or frame.add(panel)
Call frame.setResizable(false)
in the end after making it visible to make sure that all the components are fit properly.