I am trying to fit an image to be placed in a JPanel. I find the width and height of the JPanel and scale the image to have the same width and height as the JPanel. My problem is the image is then slightly outside of the JPanel.
A simple short example is
public class TestJPanel {
/**
* @param args
*/
public static void main(final String[] args) {
final JFrame jf = new JFrame();
final JButton jb = new JButton("100by100");
jb.setPreferredSize(new Dimension(100,100));
final JPanel jp = new JPanel();
jp.setPreferredSize(new Dimension(100, 100));
System.out.println(jp.getInsets());
jp.add(jb);
jf.getContentPane().add(jp);
jf.pack();
jf.setVisible(true);
}
}
In this case the button is slightly outside of the JPanel.
Is there a different method aside from JPanel.getWidth()
and the equivalent height method to find the maximum size of a component to put in a JPanel?
Edit
I think this is an issue with the layout manager. In my application I am using GridBagLayout.
Changing the example above to the following prevents the button being cut off.
public class TestJPanel {
/**
* @param args
*/
public static void main(final String[] args) {
final JFrame jf = new JFrame();
final JButton jb = new JButton("100by100");
jb.setPreferredSize(new Dimension(100,100));
final JPanel jp = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
jp.setPreferredSize(new Dimension(100, 100));
System.out.println(jp.getInsets());
jp.add(jb);
jf.getContentPane().add(jp);
jf.pack();
jf.setVisible(true);
}
}