Example of JList and ListSelectionListener |
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.JList; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; /** * @web http://java-buddy.blogspot.com/ */ public class JavaMyFrame extends JFrame implements ActionListener, ListSelectionListener{ JList jList1; 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 vPanel = new JPanel(); vPanel.setLayout(new BoxLayout(vPanel, BoxLayout.Y_AXIS)); JPanel hPanel = new JPanel(); hPanel.setLayout(new BoxLayout(hPanel, BoxLayout.X_AXIS)); jList1 = new JList(DayOfWeek); jList1.addListSelectionListener(this); textField2 = new JTextField(20); labelInfo = new Label(); vPanel.add(textField2); vPanel.add(labelInfo); hPanel.add(jList1); hPanel.add(vPanel); buttonAccept = new JButton("Accept"); buttonAccept.addActionListener(this); getContentPane().add(hPanel, BorderLayout.CENTER); getContentPane().add(buttonAccept, BorderLayout.PAGE_END); } @Override public void actionPerformed(ActionEvent e) { textField2.setText((String)jList1.getSelectedValue()); if(e.getSource() == buttonAccept){ labelInfo.setText("by buttonAccept"); }else{ labelInfo.setText("unknow source"); } } @Override public void valueChanged(ListSelectionEvent e) { textField2.setText((String)jList1.getSelectedValue()); labelInfo.setText("by jList1"); } }
Java buddies - I salute to your sincere efforts. Your examples are very well selected and coded using comprehensive approach. Thanks to all the team members involved in this endeavour.
ReplyDeleteNiamatUllah