列表框 JList

package net.mindview.util;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextArea;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import static net.mindview.util.SwingConsole.*;

public class List extends JFrame {
	
	private String[] flavors = {
		"Chocolate", "Strawberry", "Vanilla Fudge Swirl",
		"Mint Chip", "Mocha Almond Fudge", "Rum Raisin",
		"Praline Cream", "Mud Pie"
	};
	
	private DefaultListModel lItems = new DefaultListModel();
	private JList lst = new JList(lItems);
	private JTextArea t = new JTextArea(flavors.length, 20);
	private JButton b = new JButton("Add Item");
	private int count = 0;
	private ActionListener bl = new ActionListener() {
		public void actionPerformed(ActionEvent e) {
			if(count < flavors.length) {
				lItems.add(0, flavors[count++]);
			}else {
				b.setEnabled(false);
			}
		}
	};
	
	private ListSelectionListener ll = new ListSelectionListener() {

		@Override
		public void valueChanged(ListSelectionEvent e) {
			
			if(e.getValueIsAdjusting()) return;  
			t.setText("");
			for(Object item : lst.getSelectedValues())
				t.append(item + "\n");
		}
		
	};
	
	public List() {
		t.setEditable(false);
		setLayout(new FlowLayout());
		// Create Borders for components:
		Border brd = BorderFactory.createMatteBorder(1, 1, 2, 2, Color.BLACK);
		lst.setBorder(brd);
		t.setBorder(brd);
		// Add the first four items to the List
		for(int i = 0; i < 4; i++ ) {
			lItems.addElement(flavors[count++]);
		}
		this.add(t);
		this.add(lst);
		this.add(b);
		lst.addListSelectionListener(ll);
		b.addActionListener(bl);
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		run(new List(), 250, 375);
	}

}

package net.mindview.util;
import javax.swing.*;
public class SwingConsole {
	public static void run(final JFrame f, final int width, final int height) {
		SwingUtilities.invokeLater(new Runnable(){
			public void run() {
				f.setTitle(f.getClass().getSimpleName());
				f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				f.setSize(width, height);
				f.setVisible(true);
			}
		});
	}
}

你可能感兴趣的:(列表框)