我需要在 jscrollpane 中添加一些图像,并在使用相对图像选择我的 jlist 字符串时显示正确的图像......但我有一些疑问。
public class Tela{
private JList<String> list;
public Tela(){
JFrame display = new JFrame();
display.setTitle("Maquina de Refrigerante");
String labels[] = { "Coca-Cola", "Fanta Laranja", "Fanta-Uva",
"Sprite"};
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
JPanel firstPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel secondPanel = new JPanel();
//downPanel.add(BorderLayout.SOUTH);
//downPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 30, 260));
secondPanel.setBackground(Color.WHITE);
secondPanel.setPreferredSize(new Dimension(110,110));
final JButton comprar = new JButton("Comprar");
comprar.setEnabled(false);
list = new JList<String>(labels);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
list.setSelectedIndex(0);
JScrollPane pane = new JScrollPane();
pane.getViewport().add(list);
firstPanel.add(pane);
list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int selections[] = list.getSelectedIndices();
//String selectedValue = list.getSelectedValue();
Object selectionValues[] = list.getSelectedValues();
for (int i = 0, n = selections.length; i < n; i++) {
if (i == 0) {
System.out.println("Value" + selectionValues[i] );
}}
comprar.setEnabled(true);
}
});
ImageIcon image = new ImageIcon("assets/fantalogo.jpg");
JScrollPane jsp = new JScrollPane(new JLabel(image));
panel.add(jsp);
buttonPanel.add(comprar);
buttonPanel.add(Box.createRigidArea(new Dimension(0,4)));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
panel.add(firstPanel);
panel.add(secondPanel);
panel.add(buttonPanel);
//panel.add(buttonPanel, BorderLayout.CENTER);
panel.setBackground(Color.BLACK);
display.add(panel);
display.setSize(550, 500);
display.setLocationRelativeTo(null);
display.setDefaultCloseOperation(display.EXIT_ON_CLOSE);
display.setVisible(true);
comprar.addActionListener(new Paga());
}
}
在我的代码中,我如何实现它并查看正确的输出?