Java Reference
In-Depth Information
Display 18.4
Using Icons (part 2 of 2)
45 buttonPanel.add(sadButton);
46 add(buttonPanel, BorderLayout.SOUTH);
47 message = new JTextField(TEXT_FIELD_SIZE);
48 add(message, BorderLayout.CENTER);
49 }
50 public void actionPerformed(ActionEvent e)
51 {
52 String actionCommand = e.getActionCommand();
53 if (actionCommand.equals("Happy"))
54 message.setText(
55 "Smile and the world smiles with you!");
56 else if (actionCommand.equals("Sad"))
57 message.setText(
58 "Cheer up. It can't be that bad.");
59 else
60 message.setText("Unexpected Error.");
61 }
62 }
R ESULTING GUI 1
View after clicking the "Sad" button.
button with
only an icon
You can produce a button or menu item with (just) an icon on it by giving the
ImageIcon object as an argument to the JButton or JMenuItem constructor. For example,
ImageIcon happyIcon = new ImageIcon("smiley.gif");
JButton smileButton = new JButton(happyIcon);
JMenuItem happyChoice = new JMenuItem(happyIcon);
If you create a button or menu item in this way and do not add text with the method
setText, you should use setActionCommand to explicitly give the button or menu
item an action command, because there is no string on the button or menu item.
1 Java, Duke, and all Java-based trademarks and logos are trademarks or registered trademarks of
Oracle, Inc. in the United States and other countries.
 
 
Search WWH ::




Custom Search