gpt4 book ai didi

java - 在 jscrollpane 中添加图像列表并显示它

转载 作者:行者123 更新时间:2023-12-02 06:38:04 27 4
gpt4 key购买 nike

我需要在 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());
}


}

在我的代码中我如何实现它并查看正确的输出?

最佳答案

查看 How to Use Combo Boxes 上的 Swing 教程中的部分。您会发现一个几乎完全符合您要求的示例。该示例使用组合框,但 JList 的代码非常相似。也就是说,组合框包含一个字符串列表,当您选择一个项目时,会显示匹配的图像。

关于java - 在 jscrollpane 中添加图像列表并显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19430466/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com