How would I get rid of the spacing to the left and right of the text of
a JButton?
I have a button with the text "Lookup" like this:
private final JButton m_lookupButton = new JButton();
private final AbstractAction m_lookupAction =
new AbstractAction("Lookup") {
public void actionPerformed(ActionEvent evt) {
lookup();
}
};
m_lookupButton.setAction(m_lookupAction);
final JPanel buttons=new JPanel();
buttons.add(m_lookupButton);
but when I run the program, the button appears much wider than its text
with a lot of space to the left and right of the text.
If I try to make the button narrower like this:
m_lookupButton.setIconTextGap(0);
m_lookupButton.setPreferredSize
(new Dimension
(m_lookupButton.getPreferredSize().width-1,
m_lookupButton.getPreferredSize().height));
then the text is shown as "Look..."
Any answers gratefully received :)
/Martin
BartCr - 17 May 2005 12:18 GMT
You'll need to override getInsets() on the JButton to achieve this.
JButton m_lookupButton = new JButton() {
public void getInsets() {
return new Insets(0, 0, 0, 0); // Change values to required
}
};
Karsten Lentzsch - 17 May 2005 14:15 GMT
> How would I get rid of the spacing to the left and right of the text of
> a JButton?
The JGoodies Windows L&F and the Plastic L&F family
provide an optional setting to shrink the large gaps.
See https://looks.dev.java.net/
- Karsten
Vova Reznik - 17 May 2005 14:21 GMT
Use method setMargin(java.awt.Insets) of javax.swing.AbstractButton
Insets has only one constructor(int top, int left, int bottom, int right)
Martin A - 18 May 2005 09:36 GMT
> Use method setMargin(java.awt.Insets) of javax.swing.AbstractButton
>
> Insets has only one constructor(int top, int left, int bottom, int right)
Thanks all for help :)
This was best method to only change left and right margin to 2:
button.setMargin
(new java.awt.Insets(button.getMargin().top, 2,
button.getMargin().bottom, 2));
Vova Reznik - 18 May 2005 14:42 GMT
>> Use method setMargin(java.awt.Insets) of javax.swing.AbstractButton
>>
[quoted text clipped - 6 lines]
> (new java.awt.Insets(button.getMargin().top, 2,
> button.getMargin().bottom, 2));
Default Insets for buttons is (2, 14, 2, 14).
Thomas A. Russ - 18 May 2005 23:44 GMT
> How would I get rid of the spacing to the left and right of the text of
> a JButton?
You should also be aware that some platforms use buttons that are not
square, so perhaps the extra space is to allow for oval buttons without
having the text be drawn outside the button itself? Mac OS X with the
Aqua L&F comes to mind.

Signature
Thomas A. Russ, USC/Information Sciences Institute
Martin A - 19 May 2005 09:30 GMT
>
>
[quoted text clipped - 8 lines]
>
>
Is there a way of seeing if the button is oval or, more generally, if
the text fits in to the buttons perimeter?