Reputation: 9038
For automatic test purposes is a must to have the text set because is the identification used by robot to navigate though screens.
I need to create a JButton
with text and icon but only show the icon.
I have tried several things:
use of setHideActionText(true)
:
jButton button = new JButton(icon);
jButton.setHideActionText(true);
jButton.setText(_messageManager.getMessage(messageKey));
setHoritzontalTextPosition
setVerticalAlignment
but none worked.
Anyone has any idea on how to solve this?
Upvotes: 2
Views: 6687
Reputation: 1
Button text not shown with painted icons!
The code:
Icon icon = new PlayIcon();
JButton play = new JButton("PlayIcon with text", icon);
You expect a text with the button. But it is not shown! Maybe your icon paints itsself like this:
public class PlayIcon implements Icon ...
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(color==null ? c.getForeground() : color);
GeneralPath path = new GeneralPath();
path.moveTo(x + 2, y + 2);
path.lineTo(x + width - 2, y + height / 2);
path.lineTo(x + 2, y + height - 2);
path.lineTo(x + 2, y + 2);
g2d.fill(path);
g2d.dispose(); // <===========
...
Then the problem is the dispose()
call in the PlayIcon
class.
Remove it!
See: github issue
Upvotes: 0
Reputation:
I need to create a JButton with text and icon but only show the icon.
You could have possibly used setActionCommand()
jButton.setActionCommand("Button 1");
Or, you may also use setName()
jButton.setName("Button 1");
Upvotes: 4
Reputation: 13728
You could avoid the text of the JButton completely if your work with the TooltipText:
jButton1.setIcon(new ImageIcon(getClass().getResource("/money.png")));
jButton1.setToolTipText("Foo");
....
jButton1.getToolTipText(); // use instead of getText()
Upvotes: 0
Reputation: 1883
I would suggest to set the size of the Font of the button text to 0. And if that does not work, set the size to the lowest possible value and the color of the text equal to the background color of the button (you might have to tweak the layout a little afterwards ...)
Upvotes: 0
Reputation: 22074
You want to have the text only in the test environment but not in production?
Then you could so something like this:
setText("");
if(test)
setText("sometext");
Upvotes: 0