问题
I need to create a Java Swing JList
with three Components.
Each JList row should have one JCheckBox, one ImageIcon and one JLabel. The problem is that JLabel could have only two elements. So i need a methode to add a JCheckBox...
Jlist with three components:-
回答1:
Without any real information, the best I can suggest is start by having a look at Concepts: Editors and Renderers and Writing a Custom Cell Renderer for how cell renders work.
Based on you basic requirements, you need to start with a container class of some sort and add your components to it, you then need to populate the values of the components each time getListCellRendererComponent
is called with the data it provides.
You will also need to take care of the selection rendering, since that's normally taken care of by the DefaultListCellRenderer
As an example...
public static class CustomListCellRenderer extends JPanel implements ListCellRenderer<Data> {
private static final Border DEFAULT_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);
private JCheckBox checkBox;
private JLabel label;
public CustomListCellRenderer() {
setOpaque(false);
setLayout(new FlowLayout(FlowLayout.LEFT));
setBorder(DEFAULT_NO_FOCUS_BORDER);
checkBox = new JCheckBox();
label = new JLabel();
checkBox.setOpaque(false);
add(checkBox);
add(label);
}
@Override
public Component getListCellRendererComponent(JList<? extends Data> list, Data value, int index, boolean isSelected, boolean cellHasFocus) {
checkBox.setSelected(value.isSelecetd());
label.setIcon(new ImageIcon(value.getImage()));
label.setText(value.getText());
Color fg = list.getForeground();
if (isSelected) {
setBackground(list.getSelectionBackground());
fg = list.getSelectionForeground();
}
label.setForeground(fg);
setOpaque(isSelected);
Border border = null;
if (cellHasFocus) {
if (isSelected) {
border = UIManager.getBorder("List.focusSelectedCellHighlightBorder");
}
if (border == null) {
border = UIManager.getBorder("List.focusCellHighlightBorder");
}
} else {
border = DEFAULT_NO_FOCUS_BORDER;
}
setBorder(border);
return this;
}
}
来源:https://stackoverflow.com/questions/36442522/java-gui-swing-jlist-with-three-components