2

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:

  1. use of 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?

4

5 回答 5

3

我需要创建一个带有文本和图标的 JButton,但只显示图标。

您可能使用过setActionCommand()

jButton.setActionCommand("Button 1");

或者,您也可以使用setName()

jButton.setName("Button 1");
于 2015-10-28T09:12:58.683 回答
0

您希望文本仅在测试环境中而不是在生产环境中?

然后你可以这样:

setText("");
if(test)
   setText("sometext");
于 2013-04-17T10:05:49.580 回答
0

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

于 2013-04-17T10:09:06.427 回答
0

如果您使用 TooltipText,则可以完全避免使用 JButton 的文本:

   jButton1.setIcon(new ImageIcon(getClass().getResource("/money.png")));
   jButton1.setToolTipText("Foo");  
   ....
   jButton1.getToolTipText(); // use instead of getText()
于 2013-04-17T12:03:11.840 回答
0

按钮文本未显示绘制图标!

编码:

        Icon icon = new PlayIcon();
        JButton play = new JButton("PlayIcon with text", icon);

您期望带有按钮的文本。但是没有显示!也许您的图标会像这样描绘自己:

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(); // <===========
...

然后问题是课堂上的dispose()电话PlayIcon。去掉它!

结果会是这样

见:github问题

于 2022-01-16T16:44:02.070 回答