【问题标题】:Is it possible to put text on top of a image in a button?是否可以将文本放在按钮中的图像顶部?
【发布时间】:2011-02-12 09:32:36
【问题描述】:

我的按钮中有 .jpg 图像。我还想在图像上放一些文字。我为此使用以下语法:

JButton btn = new JButton(label,icon);

但我没有在按钮中看到文字(只有图像)。我做错了什么?

【问题讨论】:

  • 刚刚注意到,在您最近的 15 个答案中,没有一次您愿意接受任何答案。如果您有这么多时间发布问题,那么您也有时间接受已经给出的答案。

标签: java image swing text jbutton


【解决方案1】:

我不知道您为什么看不到文字和图标。默认情况下,文本应绘制在图标的右侧。

在您使用的图标顶部显示文本:

JButton button = new JButton(...);
button.setHorizontalTextPosition(JButton.CENTER);
button.setVerticalTextPosition(JButton.CENTER);

【讨论】:

    【解决方案2】:

    您是要在图像顶部叠加文本还是仅将文本放置在图像外部? 将文本定位在图像之外很容易,并且是@camickr 提到的默认行为。 要将文本移到顶部,您可以:

    ImageIcon icon = new ImageIcon(pathToicon);
    JButton myButton = new JButton("Press me!", icon);
    myButton.setVerticalTextPosition(SwingContstants.TOP);
    

    另外,请注意只有 .gif、.jpg 和 .png。将由 ImageIcon 处理

    【讨论】:

      【解决方案3】:

      默认情况下,swing 按钮的水平文本位置为SwingConstants.TRAILING,它将在图标之后绘制文本(想想复选框或单选按钮)。如果你想让文本居中在图标上,你只需要设置按钮的水平文本位置:

      JButton button = new JButton(label, icon);
      button.setHorizontalTextPosition(SwingConstants.CENTER);
      

      【讨论】:

        【解决方案4】:

        如果你想在任何挥杆组件中以你喜欢的方式演奏,你可以很好地覆盖paint()方法。这样你就可以为所欲为。

        package test;
        
        import java.awt.Graphics;
        
        import javax.swing.JButton;
        import javax.swing.JFrame;
        import javax.swing.JPanel;
        
        public class ButtonTest {
            public static void main(String[] args){
                new ButtonTest().test();
            }
        
            public void test(){
                JFrame frame = new JFrame("Biohazard");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JPanel pnl = new JPanel();
                pnl.add(new MyButton());
                frame.add(pnl);
                frame.setSize(600, 600);
                frame.setVisible(true);
            }
        
            class MyButton extends JButton{
                public void paint(Graphics g){
                    //anything you want
                }
            }
        }
        

        【讨论】:

          【解决方案5】:

          JButton button = new JButton(text,icon); button.setVerticalTextPosition(SwingConstants.TOP); button.setHorizontalTextPosition(SwingConstants.CENTER);

          这对我有用。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-12-23
            • 2013-02-28
            • 1970-01-01
            • 2018-04-29
            • 2011-02-24
            • 2010-09-26
            • 2023-03-02
            • 2013-09-16
            相关资源
            最近更新 更多