有没有办法像我们使用方法JCheckBox
一样在Java中动态添加类型项?JComboBox
addItem
问问题
135 次
2 回答
1
请注意,您可能会为渲染组件使用实际的复选框,但这要短几行。
import java.awt.*;
import javax.imageio.ImageIO;
import javax.swing.*;
class JCheckList {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
JPanel gui = new JPanel(new BorderLayout());
JLabel l = new JLabel("Ctrl/shift click to select multiple");
gui.add(l, BorderLayout.PAGE_START);
JList<String> list = new JList<String>(
ImageIO.getReaderFileSuffixes());
list.setCellRenderer(new CheckListCellRenderer());
gui.add(list, BorderLayout.CENTER);
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
class CheckListCellRenderer extends DefaultListCellRenderer {
String checked = new String(Character.toChars(9745));
String unchecked = new String(Character.toChars(9746));
@Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(
list,value,index,isSelected,cellHasFocus);
if (c instanceof JLabel) {
JLabel l = (JLabel)c;
String s = (isSelected ? checked : unchecked) + (String)value;
l.setText(s);
}
return c;
}
}
于 2013-09-19T09:58:45.270 回答
1
如果您想将多个项目添加到另一个组件,这样的事情可能会很有效:
List<Component> myList = new Arraylist<Component>() //List for storage
Item myItem = new Item(); //New component
myList.add(myItem); //Store all the components to add in the list
for(int i = 0; i < myList.size; i++){
myjCheckBox.add(myList[i]); //Add all items from list to jCheckBox
}
上面的例子使用了jCheckBox中继承的这个方法,应该可以提供你所需要的
希望能帮助到你!
于 2013-09-19T08:59:36.463 回答