I have .jpg images in my buttons. I also would like to put some text on top of the images. I use the following syntax for that:
JButton btn = new JButton(label,icon);
But I do not see text in the buttons (only image). What am I doing wrong?
I have no idea why you are not seeing the text and icon. By default the text should be painted to the right of the icon.
To display the text on top of the icon you use:
JButton button = new JButton(...);
button.setHorizontalTextPosition(JButton.CENTER);
button.setVerticalTextPosition(JButton.CENTER);
If you want to play any way you like in any swing component, you can very well override the paint() method. This way you can do whatever you like.
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With