Java Swing中检查框如何嵌入到列表框中?
麻烦你贴出代码好吗? 展开
兄弟实现这个技术真的好难!因为JList没有像JTable那样的编辑器。而只有绘制器。所以再JList中还必须加上事件才能实现选中状态的效果。如果你想添加的是下拉列表框那我就没办法了!(估计JList不能实现)代码我已经给你写好了,没有加注释。用了三个内部类。如果你有什么问题就问我,我QQ:316378193
代码如下:
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.*;
public class Test extends JFrame {
private static final long serialVersionUID = 1L;
private FreeList list;
public Test() {
list = new FreeList();
setLayout(new GridLayout(1, 1));
getContentPane().add(list);
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private class FreeList extends JList implements MouseListener{
private static final long serialVersionUID = 1L;
private DefaultListModel model;
private Random random;
private CellRenderer cell;
public FreeList() {
model = new DefaultListModel();
cell = new CellRenderer();
random = new Random();
for (int i = 0; i < 10; i++) {
int a = random.nextInt(9999999);
CheckBox box=new CheckBox(a);
model.add(i, box);
}
setModel(model);
setCellRenderer(cell);
addMouseListener(this);
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
Object temp=this.getSelectedValue();
JCheckBox selectBox=(JCheckBox)temp;
if(selectBox.isSelected()) {
selectBox.setSelected(false);
}
else {
selectBox.setSelected(true);
}
repaint();
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0) {
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
}
private class CheckBox extends JCheckBox {
private int number;
public CheckBox(int number) {
super();
this.number=number;
}
public String toString() {
return String.valueOf(number);
}
}
private class CellRenderer implements ListCellRenderer {
private JCheckBox box;
@Override
public Component getListCellRendererComponent(JList arg0, Object arg1,
int arg2, boolean arg3, boolean arg4) {
// TODO Auto-generated method stub
box = new JCheckBox();
box.setText(arg1.toString());
if (arg3) {
box.setBackground(Color.BLUE);
} else {
box.setBackground(Color.WHITE);
}
JCheckBox selectBox=(JCheckBox)arg1;
box.setSelected(selectBox.isSelected());
return box;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Test();
}
}