Search code examples
javaswingborderjcomponentmargins

How to get the painted size of a Swing component?


When I add Swing component (like a JButton) to a JPanel, it renders with it's 'preferred size'.

However, the preferred size is actually larger than the painted button. There appears to be an invisible border around it.

Here's a simple frame with my test panel:

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

TestPanel pnl = new TestPanel();
frame.getContentPane().add(pnl);

frame.pack();
frame.setVisible(true);

Here's my test panel ...

public class TestPanel extends JPanel {

    JButton btn1 = new JButton("Test1");
    JButton btn2 = new JButton("Test2");

    public TestPanel() {
        this.add(btn1);
        this.add(btn2);
    }

    public void paint(Graphics g) {
        super.paint(g);

        g.setColor(Color.RED);
        Dimension dim = btn1.getPreferredSize();
        g.drawRect(btn1.getX(), btn1.getY(), (int)(dim.getWidth()), (int)(dim.getHeight()));
    }

}

Notice I painted btn1's "PreferredSize" in RED to demonstrate that the preferredSize is actually larger than the button itself.

enter image description here

My question is, how can I determine the width and height of the painted button, not the JButton's preferredSize?

Any help is greatly appreciated, thanks!

UPDATE

Because I actually need this to work for all Swing components, here's a screen shot with the more components.

Unfortunately, I need to figure this out, determining the "real" size of the visible widget is crucial to my application.

enter image description here


Solution

  • I don't think this is particular or practically achievable.

    The problem is, the button is using the "unpainted" area to paint other elements, like the focus highlight.

    You could try look at the AbstractButton#set/getMargin