I have problem with creating own swing component. I want to create component that will render some image and it will fit current window (or container) size proportionally.
The problem is that I cant know real available space for component in container (without insents, borders, may be something else...).
This example shows the problem:
public class Main
{
static class MyComponent extends JComponent
{
@Override
public Dimension getPreferredSize()
{
if(isShowing())
{
int width = getParent().getSize().width - 4;
Dimension dimension = new Dimension(width, (int)(width / 0.8));
System.out.println(dimension);
return dimension;
}
return super.getPreferredSize();
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.RED);
g.fillOval(0, 0, getWidth(), getHeight());
}
}
public static void main(String... args)
{
JFrame frame = new JFrame("Test");
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(Color.DARK_GRAY);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(2, 2, 2, 2);
c.gridx = c.gridy = 0;
panel.add(new MyComponent(), c);
c.gridy++;
panel.add(new MyComponent(), c);
frame.add(new JScrollPane(panel));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
}
}
If you remove 4 (left & right from insets) from getParent().getSize().width - 4
expression and launch, you will see that component(s) will increase its size infinitely.
In the above code I get full width of container, but I need available width so that component will not trigger container to resize again and again.
Or is there another way to fit component normally?