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?
The false alignment:
I want it more like this but the text is align to the left:
I already testes the setHorizontalAlignment()
and setHorizontalTextPosition
Methods.
I also want to avoid positioning a Jlabel over the JButton.
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:
setIconTextGap(-100);
where 100 relates to the left icon's width.
A second alternative would be using HTML text:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.