LAB 1_Listtest
ListTest
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class ListTest extends JFrame {
private static final int DEFAULT_WIDTH = 400;
private static final int DEFAULT_HEIGHT = 300;
private JPanel listPanel,buttonPanel;
private JList wordList;
private JLabel label;
private ButtonGroup group;
private String prefix = " day ";
private String suffix = " Heppy Day ";
public ListTest () {
setTitle(" ListTest ");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
String[]words = {" sun " , " mun " , " tue " , " wed " , " thr " , " fri " , " sat "};
wordList = new JList(words);
wordList.setVisibleRowCount (4);
wordList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollPane = new JScrollPane (wordList);
listPanel = new JPanel ();
listPanel.add (scrollPane);
wordList.addListSelectionListener(new ListSelectionListener(){
public void valueChanged (ListSelectionEvent event){
Object[]values = wordList.getSelectedValues ();
StringBuffer temp = new StringBuffer (prefix);
for ( int i = 0; i < values.length; i++ ){
String word = (String)values[i];
temp.append(word);
temp.append(" ");
}
temp.append(suffix);
label.setText(temp.toString());
}
});
buttonPanel = new JPanel();
group = new ButtonGroup();
makeButton ("Vertical",JList.VERTICAL);
makeButton("VerticalWrap",JList.VERTICAL_WRAP);
makeButton("Horizontal Wrap",JList.HORIZONTAL_WRAP);
add(listPanel,BorderLayout.NORTH);
label = new JLabel (prefix + suffix);
add(label,BorderLayout.CENTER);
add(buttonPanel,BorderLayout.SOUTH);
}
private void makeButton(String label,final int orientation){
JRadioButton button = new JRadioButton(label);
buttonPanel.add(button);
if (group.getButtonCount()==0)button.setSelected(true);
group.add(button);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
wordList.setLayoutOrientation(orientation);
listPanel.revalidate();
}
});
}
public static void main (String[]args){
JFrame frame = new ListTest();
frame.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent e){
System.exit (0);
}
});
frame.setVisible (true);
}
}
ไม่มีความคิดเห็น:
แสดงความคิดเห็น