JButton button = new JButton("Edit");JButton button = new JButton(new ImageIcon("images/start.gif"));Here the icon file start.gifis placed under images directory which is relative to the program.String iconPath = "/net/codejava/swing/jbutton/stop.jpg"; Icon icon = new ImageIcon(getClass().getResource(iconPath)); JButton button = new JButton(icon);Here the icon file stop.jpgis placed under a specific package in the classpath.
JButton button = new JButton("Start", new ImageIcon("images/start.gif"));frame.add(button); dialog.add(button); panel.add(button); applet.getContentPane().add(button);
frame.add(button, BorderLayout.CENTER); panel.add(button, gridbagConstraints);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
// do everything here...
}
}); button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
// delegate to event handler method
buttonActionPerformed(evt);
}
}); The event handler method is declared as follows:private void buttonActionPerformed(ActionEvent evt) {
// do something here...
} public class App extends JFrame implements ActionListener {
public App() {
// creates the button...
// adds event listener:
button.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent evt) {
// do something here...
}
} Here the container (JFrame) must implement the ActionListener interface and override the method actionPerformed().
button.setMnemonic(KeyEvent.VK_E);
String mapKey = "KEY_F2";
InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(KeyStroke.getKeyStroke("F2"), mapKey);
button.getActionMap().put(mapKey, new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
buttonActionPerformed(evt);
}
}); getRootPane().setDefaultButton(button);The default button is bold in the window like the 3rd button in this screenshot:
6. Customizing JButton’s appearancebutton.setFont(new java.awt.Font("Arial", Font.BOLD, 14));
button.setBackground(Color.YELLOW);
button.setForeground(Color.BLUE);button.setText("<html><color=blue><b>Edit</b></font></html>");
You can download source code of this program in the attachment section.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.