[英]Java Swing align text inside icon
How can i align a text to the left of a JButton but the icon is sill centered and isnt pushed away by the text?如何将文本对齐到 JButton 的左侧,但图标居中并且不会被文本推开?
The false alignment:虚假的 alignment:
I want it more like this but the text is align to the left:我希望它更像这样,但文本左对齐:
I already testes the setHorizontalAlignment()
and setHorizontalTextPosition
Methods.我已经测试了
setHorizontalAlignment()
和setHorizontalTextPosition
方法。
I also want to avoid positioning a Jlabel over the JButton.我还想避免在 JButton 上放置 Jlabel。
My code:我的代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
public class Example extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Example frame = new Example();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Example() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JButton settings_bnt = new JButton("settings");
settings_bnt.setIcon(new ImageIcon(Example.class.getResource("/grafics/MainGUI/Settings.png")));
settings_bnt.setFont(new Font("Tahoma", Font.PLAIN, 17));
settings_bnt.setForeground(Color.WHITE);
settings_bnt.setHorizontalAlignment(SwingConstants.CENTER);
settings_bnt.setHorizontalTextPosition(SwingConstants.CENTER);
settings_bnt.setBounds(10, 10, 112, 35);
settings_bnt.requestFocus();
add(settings_bnt);
}
}
One desires a button with the icon image as background.需要一个以图标图像为背景的按钮。
After a look, the easiest to have a JButton with its normal icon & text & button look was to do:看了看,最简单的 JButton 具有正常的图标 & 文本 & 按钮外观是:
setIconTextGap(-100);
where 100 relates to the left icon's width.其中 100 与左侧图标的宽度有关。
A second alternative would be using HTML text:第二种选择是使用 HTML 文本:
URL backgroundURL = getClass().getResource("/background.png");
String text = "Panic!";
text = "<html><div style='padding: 3px 10px 3px 10px; background: url("
+ backgroundURL.toExternalForm() + ")'>"+ text + "</div>";
setText(text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.