Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 是否可以在按钮中的图像顶部放置文本?_Java_Image_Swing_Text_Jbutton - Fatal编程技术网

Java 是否可以在按钮中的图像顶部放置文本?

Java 是否可以在按钮中的图像顶部放置文本?,java,image,swing,text,jbutton,Java,Image,Swing,Text,Jbutton,我的按钮中有.jpg图像。我还想把一些文字的图像顶部。为此,我使用以下语法: JButton btn = new JButton(label,icon); 但我在按钮中看不到文本(只有图像)。我做错了什么?我不知道您为什么看不到文本和图标。默认情况下,文本应绘制在图标的右侧 要在您使用的图标顶部显示文本,请执行以下操作: JButton button = new JButton(...); button.setHorizontalTextPosition(JButton.CENTER); bu

我的按钮中有.jpg图像。我还想把一些文字的图像顶部。为此,我使用以下语法:

JButton btn = new JButton(label,icon);

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

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

要在您使用的图标顶部显示文本,请执行以下操作:

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

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

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

另外,请注意只有.gif、.jpg和.png。将由ImageIcon处理默认情况下,swing按钮的水平文本位置为
SwingConstants.training
,它将在图标后绘制文本(请考虑复选框或单选按钮)。如果希望文本位于图标的中心,只需设置按钮的水平文本位置:

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

如果希望在任何swing组件中以任何方式播放,可以很好地重写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
        }
    }
}

JButton按钮=新的JButton(文本、图标);
按钮。设置垂直文本位置(SwingConstants.TOP);
按钮设置水平文本位置(SwingConstants.CENTER)


这对我很有效。

我注意到,在你最近的15个答案中,没有一个是你愿意接受的。如果你有足够的时间发布问题,那么你也有时间接受已经给出的答案。