简体   繁体   English

带有图标和文本但隐藏文本的 JButton

[英]JButton with icon and text but hide text

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.我需要创建一个带有文本和图标的JButton ,但只显示图标。

I have tried several things:我尝试了几件事:

  1. use of setHideActionText(true) :使用setHideActionText(true)

     jButton button = new JButton(icon); jButton.setHideActionText(true); jButton.setText(_messageManager.getMessage(messageKey));
  2. setHoritzontalTextPosition

  3. setVerticalAlignment

but none worked.但没有一个工作。

Anyone has any idea on how to solve this?任何人都知道如何解决这个问题?

I need to create a JButton with text and icon but only show the icon. 我需要创建一个带有文本和图标的JButton,但仅显示该图标。

You could have possibly used setActionCommand() 您可能已经使用过setActionCommand()

jButton.setActionCommand("Button 1");

Or, you may also use setName() 或者,您也可以使用setName()

jButton.setName("Button 1");

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");

我建议将按钮文本的字体大小设置为0。如果这样不起作用,请将大小设置为尽可能低的值,并将文本颜色设置为按钮的背景颜色(您可能有之后再调整布局...)

You could avoid the text of the JButton completely if your work with the TooltipText: 如果使用TooltipText,则可以完全避免JButton的文本:

   jButton1.setIcon(new ImageIcon(getClass().getResource("/money.png")));
   jButton1.setToolTipText("Foo");  
   ....
   jButton1.getToolTipText(); // use instead of getText()

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.那么问题是PlayIcon类中的dispose()调用。 Remove it!去掉它!

The result will be like this结果会是这样

See: github issue见: github问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM