【问题标题】:JButton with icon and text but hide text带有图标和文本但隐藏文本的 JButton
【发布时间】:2013-04-17 10:00:22
【问题描述】:

出于自动测试目的,必须设置文本,因为这是机器人在屏幕上导航时使用的标识。 我需要创建一个带有文本和图标的JButton,但只显示图标。

我已经尝试了几件事:

  1. 使用setHideActionText(true)

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

  3. setVerticalAlignment

但没有任何效果。

有人知道如何解决这个问题吗?

【问题讨论】:

  • 修复测试环境:如果您无法测试仅图标的标签/按钮,它就会损坏(如您所见 :-)。仅仅为了那个损坏的测试工具而添加黑客会破坏代码。为了识别,它应该使用名称或客户端属性
  • 而不是使用文本,每个JComponent都可以有一个名字
  • @keopatra 有诀窍,将自动测试更改为使用名称并为系统中的每个按钮设置唯一名称。

标签: java swing user-interface jbutton


【解决方案1】:

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

您可能使用过setActionCommand()

jButton.setActionCommand("Button 1");

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

jButton.setName("Button 1");

【讨论】:

    【解决方案2】:

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

    那么你可以这样:

    setText("");
    if(test)
       setText("sometext");
    

    【讨论】:

    • 测试像在生产中一样执行,有一个自动编译和生成二进制文件的环境,测试自动接受它,所以这个代码是不可能的;)
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

      • 自动测试已经完成,用于识别按钮组件的文本值,所以我不能使用这个想法,但这是一个很好的想法;)
      【解决方案5】:

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

      代码:

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

      那么问题是PlayIcon 类中的dispose() 调用。 删除它!

      The result will be like this

      见:github issue

      【讨论】:

        猜你喜欢
        • 2011-01-10
        • 2013-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-07
        • 1970-01-01
        • 2013-02-15
        相关资源
        最近更新 更多