1.import java.awt.*;
2.import java.awt.event.*;
3.import javax.swing.*;
4.import javax.swing.event.*;
5.class ListTest extends JFrame {
6. private static final int DEFAULT_WIDTH = 400;
7. private static final int DEFAULT_HEIGHT = 300;
8. private JPanel listPanel,buttonPanel;
9. private JList wordList;
10. private JLabel label;
11. private ButtonGroup group;
12. private String prefix = " day ";
13. private String suffix = " Heppy Day ";
14. public ListTest () {
15. setTitle(" ListTest ");
16. setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
17.
18. String[]words = {" sun " , " mun " , " tue " , " wed " , " thr " , " fri " , " sat "};
19.
20. wordList = new JList(words);
21. wordList.setVisibleRowCount (4);
22. wordList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
23. JScrollPane scrollPane = new JScrollPane (wordList);
24.
25. listPanel = new JPanel ();
26. listPanel.add (scrollPane);
27. wordList.addListSelectionListener(new ListSelectionListener(){
28. public void valueChanged (ListSelectionEvent event){
29. Object[]values = wordList.getSelectedValues ();
30. //
31. StringBuffer temp = new StringBuffer (prefix);
32. for ( int i = 0; i < values.length; i++ ){
33. String word = (String)values[i];
34. //
35. temp.append(word);//
36. temp.append(" ");
37. }
38. temp.append(suffix);
39. label.setText(temp.toString());
40. }
41. });
42.
43. buttonPanel = new JPanel();
44. group = new ButtonGroup();
45. makeButton ("Vertical",JList.VERTICAL);
46. makeButton("VerticalWrap",JList.VERTICAL_WRAP);
47. makeButton("Horizontal Wrap",JList.HORIZONTAL_WRAP);
48.
49. add(listPanel,BorderLayout.NORTH);
50. label = new JLabel (prefix + suffix);
51. add(label,BorderLayout.CENTER);
52. add(buttonPanel,BorderLayout.SOUTH);
53. }
54.
55. private void makeButton(String label,final int orientation){
56. JRadioButton button = new JRadioButton(label);
57. buttonPanel.add(button);
58.
59. if (group.getButtonCount()==0)button.setSelected(true);
60. group.add(button);
61. button.addActionListener(new ActionListener(){
62. public void actionPerformed(ActionEvent event){
63. wordList.setLayoutOrientation(orientation);
64. listPanel.revalidate();
65. }
66. });
67. }
68. public static void main (String[]args){
69. JFrame frame = new ListTest();
70. frame.addWindowListener(new WindowAdapter(){
71. public void windowClosing (WindowEvent e){
72. System.exit (0);
73. }
74. });
75. frame.setVisible (true);
76. }
77.}


ไม่มีความคิดเห็น:
แสดงความคิดเห็น