JSpinner and ChangeListener |
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.JFrame; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerListModel; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** * @web http://java-buddy.blogspot.com/ */ public class JavaMyFrame extends JFrame implements ActionListener, ChangeListener{ JSpinner jSpinner1; 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)); SpinnerListModel modelDayOfWeek = new SpinnerListModel(DayOfWeek); jSpinner1 = new JSpinner(modelDayOfWeek); jSpinner1.addChangeListener(this); textField2 = new JTextField(20); labelInfo = new Label(); panel.add(jSpinner1); 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)jSpinner1.getValue()); if(e.getSource() == buttonAccept){ labelInfo.setText("by buttonAccept"); }else{ labelInfo.setText("unknow source"); } } @Override public void stateChanged(ChangeEvent e) { textField2.setText((String)jSpinner1.getValue()); if(e.getSource() == jSpinner1){ labelInfo.setText("by jSpinner1"); } } }
No comments:
Post a Comment