package component.button;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.net.URL;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
public class ButtonDemo implements ActionListener
{
private JFrame frame;
private JPanel panel;
private JButton imageButton, textButton, imageTextButton;
private String imagePath = "images/middle.gif";
public ButtonDemo()
{
frame = new JFrame("Button Demo");
panel = new JPanel();
}
private void createAndDisplayGUI()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textButton = new JButton("Click me to disable the next button");
textButton.setVerticalTextPosition(AbstractButton.CENTER);
textButton.setHorizontalTextPosition(AbstractButton.CENTER);
textButton.setMnemonic(KeyEvent.VK_T);
textButton.setDisplayedMnemonicIndex(9);
imageButton = new JButton(getImage(imagePath));
imageButton.setMnemonic(KeyEvent.VK_I);
imageButton.setEnabled(false);
imageTextButton = new JButton(
"Click me to disable the next button"
, getImage(imagePath));
imageTextButton.setVerticalTextPosition(AbstractButton.BOTTOM);
imageTextButton.setHorizontalTextPosition(AbstractButton.CENTER);
imageTextButton.setMnemonic(KeyEvent.VK_B);
imageTextButton.setDisplayedMnemonicIndex(16);
imageTextButton.setEnabled(false);
imageButton.addActionListener(this);
textButton.addActionListener(this);
imageTextButton.addActionListener(this);
panel.add(textButton);
panel.add(imageButton);
panel.add(imageTextButton);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (button == textButton)
{
imageButton.setEnabled(true);
textButton.setEnabled(false);
imageTextButton.setEnabled(false);
}
else if (button == imageButton)
{
imageButton.setEnabled(false);
textButton.setEnabled(false);
imageTextButton.setEnabled(true);
}
else if (button == imageTextButton)
{
imageButton.setEnabled(false);
textButton.setEnabled(true);
imageTextButton.setEnabled(false);
}
}
private ImageIcon getImage(String path)
{
URL url = ClassLoader.getSystemResource(path);
if (url != null)
return (new ImageIcon(url));
return null;
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
ButtonDemo bd = new ButtonDemo();
bd.createAndDisplayGUI();
}
});
}
}