import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MyButtonApplication implements ActionListener { public Component createComponents() { JButton button1 = new JButton("Button 1"); button1.setMnemonic(KeyEvent.VK_B); button1.addActionListener(this); button1.setActionCommand("B1"); JButton button2 = new JButton("Button 2"); button2.setMnemonic(KeyEvent.VK_U); button2.addActionListener(this); button2.setActionCommand("B2"); JButton button3 = new JButton("Quit"); button3.setMnemonic(KeyEvent.VK_Q); button3.addActionListener(this); button3.setActionCommand("QUIT"); /* * An easy way to put space between a top-level container * and its contents is to put the contents in a JPanel * that has an "empty" border. */ JPanel pane = new JPanel(); // uses flow layout by default pane.add(button1); pane.add(button2); pane.add(button3); pane.setBorder(BorderFactory.createEmptyBorder( 30, //top 30, //left 10, //bottom 30) //right ); return pane; } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("B1")) System.out.println("Button 1"); if (e.getActionCommand().equals("B2")) System.out.println("Button 2"); if (e.getActionCommand().equals("QUIT")) System.exit(0); } /** * Create the GUI and show it For thread safety, this method should be * invoked from the event-dispatching thread. */ private static void createAndShowGUI() { //Set the look and feel. try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("Couldn't get system look and feel for some reason."); System.err.println("Using the default look and feel."); e.printStackTrace(); } //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("MyButtonApplication"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MyButtonApplication app = new MyButtonApplication(); Component contents = app.createComponents(); frame.getContentPane().add(contents); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }