code = Java
// ButtonFrame.java
// Creating JButton
package btest.ButtonFrame;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ButtonFrame extends JFrame{
private JButton plainJButton; // button with just text
private JButton fancyJButton; // button with icons
// ButtonFrame adds JButtons to JFrame
public ButtonFrame(){
super("Testing Buttons");
setLayout(new FlowLayout()); // set frame layout
plainJButton = new JButton("Plain Button"); // button with text
add(plainJButton); // add plainJButton to JFrame
Icon bug1 = new ImageIcon(getClass().getResource("HD.png"));
Icon bug2 = new ImageIcon(getClass().getResource("Apple.png"));
fancyJButton = new JButton("Fancy Button", bug1); // set image
fancyJButton.setRolloverIcon(bug2); // set rollover image
add(fancyJButton); // add fancyJButto to JFrame
// create new ButtonHandler for button event handling
ButtonHandler handler = new ButtonHandler();
fancyJButton.addActionListener(handler);
plainJButton.addActionListener(handler);
} // end ButtonFrame constructor
// inner class for button event handling
private class ButtonHandler implements ActionListener{ // ERROR */
// handle button event
public void actionPerfomed(ActionEvent event){
JOptionPane.showMessageDialog(ButtonFrame.this, String.format("You pressed: %s",
event.getActionCommand()));
}
}
}
/code
code = Java
//ButtonTest.java
// Testing ButtonFrame
package btest;
import btest.ButtonFrame.ButtonFrame;
import javax.swing.JFrame;
public class BTest {
public static void main(String[] args) {
ButtonFrame buttonFrame = new ButtonFrame(); // create button frame
buttonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonFrame.setSize(275, 110); // set frame size
buttonFrame.setVisible(true); // display frame
}
}
/code