//下面是我写的,效果如图
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
public class JListTest extends JFrame implements ActionListener{
private JList list=new JList();
List<JButton> btnList=new ArrayList<JButton>();
public JListTest(String s){
super(s);
setBounds(100,100,550,450);
setLayout(new FlowLayout());//设置为FlowLayout布局
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
list.setToolTipText("JList");//JList头
list.setBorder(BorderFactory.createTitledBorder("JList测试"));
list.setPreferredSize(new Dimension(180,300));//设置JList大小
JScrollPane pane=new JScrollPane(list);
pane.setPreferredSize(new Dimension(180,290));//设置JScrollPane大小
add(pane);
}
public void createList(int size){//建立JList方法
JButton btn;
list.setLayout(new GridLayout(2*size+1,1));
for(int i=0;i<size;i++){
btn=new JButton(2*i+"");
btn.setBackground(Color.yellow);
list.add(btn);
btn.addActionListener(this);
btnList.add(btn);
btn=new JButton((2*i+1)+"");
btn.setBackground(Color.green);
list.add(btn);
btn.addActionListener(this);
btnList.add(btn);
}
validate();//注意刷新
}
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(this,"单击了:"+e.getActionCommand());
}
public static void main(String[] args) {
new JListTest("JList测试").createList(5);
}
}
import java.awt.Color;
import java.awt.Component;
import javax.swing.*;
public class MainFrame extends JFrame {
private JList list;
public MainFrame() {
list = new JList(new String[]{"1", "2", "3"});
list.setCellRenderer(new ColorfulCellRenderer());
this.getContentPane().add(list);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 300);
}
public static void main(String[] args) {
new MainFrame();
}
}
class ColorfulCellRenderer extends JLabel implements ListCellRenderer {
private Color[] colors = new Color[]{Color.GREEN, Color.WHITE, Color.RED};
public ColorfulCellRenderer() {
setOpaque(true);
}
@Override
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
setText(value.toString());
Color background;
Color foreground;
//当前Renderer是否是拖拽目标
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsert()
&& dropLocation.getIndex() == index) {
background = Color.BLUE;
foreground = Color.WHITE;
//当前Renderer是否被选中
} else if (isSelected) {
background = Color.BLUE;
foreground = Color.WHITE;
} else {
background = colors[index%3];
foreground = Color.BLACK;
}
setBackground(background);
setForeground(foreground);
return this;
}
}