JComboBox and ActionListener |
package javamyframe; import java.awt.BorderLayout; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; /** * @web http://java-buddy.blogspot.com/ */ public class JavaMyFrame extends JFrame implements ActionListener{ JComboBox jComboBox1; JTextField textField2; Label labelInfo; JButton buttonAccept; static final String DayOfWeek[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}; public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { JavaMyFrame myFrame = new JavaMyFrame(); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.prepareUI(); myFrame.pack(); myFrame.setVisible(true); } private void prepareUI(){ JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); jComboBox1 = new JComboBox(DayOfWeek); jComboBox1.setSelectedIndex(1); jComboBox1.addActionListener(this); textField2 = new JTextField(20); labelInfo = new Label(); panel.add(jComboBox1); panel.add(textField2); panel.add(labelInfo); buttonAccept = new JButton("Accept"); buttonAccept.addActionListener(this); getContentPane().add(panel, BorderLayout.CENTER); getContentPane().add(buttonAccept, BorderLayout.PAGE_END); } @Override public void actionPerformed(ActionEvent e) { textField2.setText((String)jComboBox1.getSelectedItem()); if(e.getSource() == jComboBox1){ labelInfo.setText("by jComboBox1"); }else if(e.getSource() == buttonAccept){ labelInfo.setText("by buttonAccept"); }else{ labelInfo.setText("unknow source"); } } }
No comments:
Post a Comment