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

时间:2013-10-17 15:08:25

标签: java swing jscrollpane jlabel jlist

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


}

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

1 个答案:

答案 0 :(得分:2)

查看How to Use Combo Boxes上Swing教程中的部分。你找到一个几乎完全符合你想要的例子。该示例使用组合框,但JList的代码将非常相似。即组合框包含一个字符串列表,当您选择一个项目时,将显示匹配的图像。