我需要JList
来包含JPanel
,但是,这是不可能的,因此我通过使用GridLyayout
制作副本。它工作正常,但是,我想要一个绝对的'维度设置为所有网格,或者至少具有它,因此屏幕上只显示10个,其余部分位于屏幕下方,因为容器是滚动窗格。为了澄清,网格布局有1行和0(或x)列。
有人有任何想法吗?
答案 0 :(得分:3)
我需要
JList
来包含JPanel
,但是,这是不可能的
当然有可能。让它们看起来很漂亮的秘诀在于渲染。
import java.awt.*;
import java.util.Vector;
import javax.swing.*;
class PanelsInList {
JPanel ui = null;
Color[] colors = {
Color.RED, Color.GREEN, Color.BLUE,
Color.MAGENTA, Color.PINK, Color.YELLOW,
Color.BLACK, Color.GRAY, Color.WHITE
};
PanelsInList() {
initUi();
}
public final void initUi() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout());
Vector<JPanel> listContent = new Vector<JPanel>();
for (int ii=1; ii<colors.length+1; ii++) {
Color c = colors[(ii-1)%colors.length];
listContent.add(getPanel(c,ii));
}
JList<JPanel> list = new JList<JPanel>(listContent);
// the secret to getting them to look nice is in the rendering
list.setCellRenderer(new PanelCellRenderer());
list.setVisibleRowCount(3);
ui.add(new JScrollPane(list));
}
class PanelCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(
list, value, index, isSelected, cellHasFocus);
JPanel p = null;
if (value instanceof JPanel && c instanceof JLabel) {
p = (JPanel)value;
JLabel l = (JLabel)c;
p.setBackground(l.getBackground());
p.setForeground(l.getForeground());
p.setBorder(l.getBorder());
}
return p;
}
}
public JPanel getPanel(Color color, int n) {
JPanel p = new JPanel(new GridLayout());
JLabel l = new JLabel(
"Label " + n, new ColoredIcon(color), SwingConstants.LEADING);
p.add(l);
return p;
}
class ColoredIcon implements Icon {
int sz = 16;
Color color;
ColoredIcon(Color color) {
this.color = color;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(color);
g.fillRect(0, 0, sz, sz);
}
@Override
public int getIconWidth() {
return sz;
}
@Override
public int getIconHeight() {
return sz;
}
}
public JComponent getUi() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
PanelsInList pil = new PanelsInList();
JOptionPane.showMessageDialog(null, pil.getUi());
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}