我有JList
个ChartPanel
个。当我试图选择元素时,我无法直观地看到列表中实际选择了哪些元素。在程序级别,侦听器正常工作。
如何直观地选择列表中的图表面板?或者如何用不透明度颜色叠加这些元素?
以下是基于此example的代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.util.Random;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
/**
* @see https://stackoverflow.com/a/40445144/230513
*/
public class ThumbnailChartsJList{
public static JScrollPane scrollPane;
public static JList chartList;
private static final int W = 200;
private static final int H = W;
private static final int N = 100;
private static final int NumberCharts = 20;
private static final Random random = new Random();
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame("Test");
JPanel panel = new JPanel(new BorderLayout());
ChartPanel chartp = createChart();
DefaultListModel listModel = new DefaultListModel();
for (int i=0; i<NumberCharts; i++){
listModel.addElement(chartp);
}
chartList = new JList(listModel);
chartList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
chartList.setCellRenderer(new ListRenderer());
chartList.setVisibleRowCount(0); //0 - dynamic rows
chartList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
chartList.setSelectionForeground(Color.RED);
scrollPane = new JScrollPane(chartList,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scrollPane, BorderLayout.CENTER);
f.setPreferredSize(new Dimension(900,700));
f.setContentPane(panel);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
});
}
private static ChartPanel createChart() {
final XYSeries series = new XYSeries("Data");
for (int i = 0; i < random.nextInt(N) + N; i++) {
series.add(i, random.nextGaussian());
}
XYSeriesCollection dataset = new XYSeriesCollection(series);
JFreeChart chart = ChartFactory.createXYLineChart("Random", "Domain",
"Range", dataset, PlotOrientation.VERTICAL, false, false, false);
ChartPanel chartPanel = new ChartPanel(chart, W, H, W, H, W, H,
false, true, true, true, true, true){
@Override
public Dimension getPreferredSize() {
return new Dimension(W, H);}
};
chartPanel.getChart().removeLegend();
return chartPanel;
}
static class ListRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList chartList, Object
value, int index, boolean isSelected, boolean cellHasFocus) {
return (ChartPanel) value;
}
}
}