我有一个JList,其中放置了几个带有JScrollPane的JPanel: JList with JPanels
现在我的问题是,我无法滚动内部放置的JScrollPanes。只有持有Jlist的人才可以滚动。
当选择JPanel时能够滚动内部的那些将是很好的,否则应该"启用""。
这是我到目前为止所得到的:
JScrollPane scrollPane;
public TestScrollPane() {
initComponents();
scrollPane = new JScrollPane();
DefaultListModel lm1 = new DefaultListModel();
Object[] firstPages = new Object[]{getPanel(), getPanel(), getPanel(), getPanel(), getPanel(), getPanel(), getPanel(), getPanel(), getPanel(), getPanel()};
for (Object o : firstPages) {
lm1.addElement(o);
}
final JList list = new JList(lm1);
list.setVisibleRowCount(1);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setBorder(new EmptyBorder(20, 20, 20, 20));
list.setCellRenderer(new ListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
return (JPanel) value;
}
});
scrollPane = new JScrollPane(list);
this.setLayout(new BorderLayout());
this.add(scrollPane, BorderLayout.CENTER);
}
public JPanel getPanel() {
JPanel p = new JPanel();
initComponents();
String set = "test\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\ntest\n";
JTextPane text = new JTextPane();
text.setText(set);
JScrollPane scr = new JScrollPane(text);
scr.setBorder(new EmptyBorder(5, 5, 5, 5));
p.setLayout(new BorderLayout());
p.add(scr, BorderLayout.CENTER);
p.setPreferredSize(new Dimension(100, 120));
p.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
return p;
}
我该怎么做? 感谢。
答案 0 :(得分:0)
对于我的问题,我有一个适度的解决方案:
list.setSelectionModel(new DefaultListSelectionModel() {
private static final long serialVersionUID = 1L;
@Override
public void setSelectionInterval(int index0, int index1) {
if (index0 == index1) {
if (index0 != 0 && index0 != list.getModel().getSize() - 1) {
if (!isSelectedIndex(index0)) {
final int finalIndex0 = index0;
list.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
JPanel p = (JPanel) list.getModel().getElementAt(finalIndex0);
((JScrollPane) p.getComponent(0)).getVerticalScrollBar().setValue(((JScrollPane) p.getComponent(0)).getVerticalScrollBar().getValue() - e.getWheelRotation());
repaint();
p.validate();
p.repaint();
}
});
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
super.setSelectionInterval(index0, index1);
} else {
try {
MouseWheelListener[] mwls = list.getMouseWheelListeners();
for (int i = 0; i < mwls.length; i++) {
list.removeMouseWheelListener(mwls[i]);
}
} catch (Exception x) {
}
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
super.removeSelectionInterval(index0, index1);
}
}
}
}
});
使用此选择模型,我可以滚动选定的JPanel(JScrollPanes)。但我仍然无法用鼠标滚动。
因此,如果有人得到更好的解决方案,那么听到它会很高兴。
感谢。