【问题标题】:Java : How to place text on top of an Image on top of a Button?Java:如何在按钮顶部的图像顶部放置文本?
【发布时间】:2021-12-23 05:35:47
【问题描述】:

将图像添加到 JButton 可以按预期工作。
向 JButton 添加文本按预期工作。
将 Text 和 Image 添加到 JButton 时,它会并排添加 2 个项目,而不是彼此叠加。

这里是示例代码。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;

public class ToolBarSample {
  public static void main(final String args[]) {
    JFrame frame = new JFrame("JToolBar Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JToolBar toolbar = new JToolBar();
    toolbar.setRollover(true);

    JButton b2 = new JButton();
    b2.setText("Big Button");
    b2.setIcon(new ImageIcon("C:\\Downloads\\Java.png"));
    b2.setBackground(Color.RED);
    b2.setFocusable(false);
    b2.setOpaque(true);
    Dimension buttonSize = new Dimension(340,27);
    b2.setPreferredSize(buttonSize);
    b2.setMinimumSize(buttonSize);
    b2.setMaximumSize(buttonSize);
    b2.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
    b2.setVerticalAlignment(SwingConstants.CENTER);

    toolbar.add(b2);
    
    Container contentPane = frame.getContentPane();
    contentPane.add(toolbar, BorderLayout.NORTH);
    JTextArea textArea = new JTextArea();
    JScrollPane pane = new JScrollPane(textArea);
    contentPane.add(pane, BorderLayout.CENTER);
    frame.setSize(550, 350);
    frame.setVisible(true);
  }
}

上面的代码生成了一个带有图像和文本“Big Button”的红色大按钮。

如何将文本从右侧移到图像顶部。 黑框显示我希望显示文本的位置。

这是怎么做到的?完成此操作需要进行哪些更改?

【问题讨论】:

    标签: java swing icons jbutton


    【解决方案1】:

    要将文本水平/垂直居中在图标上,您可以使用:

    JButton button = new JButton("Centered");
    button.setIcon( ... );
    button.setHorizontalTextPosition(JLabel.CENTER);
    button.setVerticalTextPosition(JLabel.CENTER);
    

    如果您需要图标顶部其他位置的文本,请查看:JButton settext specific position

    【讨论】:

    • 谢谢。我期待一些复杂的解决方案,但这很好用。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2011-02-15
    • 2018-04-29
    • 2011-02-24
    • 1970-01-01
    • 2013-02-28
    • 2015-02-07
    相关资源
    最近更新 更多