I'm using netbeans to create a project app and I'm trying to get a custom image file to act as a button, I heard somewhere set it as a label instead but I'm quite new to this so I need an in depth answer on how to do this. The website won't let me post an image of the button because I'm only new but the button is in the shape of a triangle.
Asked
Active
Viewed 2,640 times
1
-
Start by reading the JButton API and you will find a link on `How to Use Buttons...` which contains a working example. – camickr Mar 01 '13 at 16:18
1 Answers
4
Use methods implemented in API and to remove Borders and Background from JButton
.
e.g.
from code
import java.awt.Insets;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class MyToggleButton extends JFrame {
private static final long serialVersionUID = 1L;
private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");
public MyToggleButton() {
final JButton toggleButton = new JButton();
toggleButton.setBorderPainted(false);
toggleButton.setBorder(null);
toggleButton.setFocusable(false);
toggleButton.setMargin(new Insets(0, 0, 0, 0));
toggleButton.setContentAreaFilled(false);
toggleButton.setIcon((errorIcon));
toggleButton.setSelectedIcon(infoIcon);
toggleButton.setRolloverIcon((infoIcon));
toggleButton.setPressedIcon(warnIcon);
toggleButton.setDisabledIcon(warnIcon);
add(toggleButton);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MyToggleButton t = new MyToggleButton();
}
});
}
}

mKorbel
- 109,525
- 20
- 134
- 319
-
3See also [this example](http://stackoverflow.com/a/10862262/418556) that mixes buttons & labels. – Andrew Thompson Mar 01 '13 at 14:27
-
2Also see [this](http://stackoverflow.com/questions/13825123/event-detection-on-opaque-pixels-in-jbutton/13825593#13825593) example for creating buttons using transparent images and allowing clicks only on non-transparent pixels. – David Kroukamp Mar 01 '13 at 14:57