根据下拉选项显示图像

时间:2016-01-23 12:05:58

标签: java image swing hashmap jframe

所以我要做的就是让用户从JComboBox中选择一个选项,然后在组合框显示缩略图旁边。

我创建了一个文件名列表,该列表从hashmap获取所有文件名,下拉列表中包含这些项的名称,例如

stock.put("00", new Item("Bath towel", 5.50, 10, "bathTowel.jpg"));

现在名称为Bath Towel,文件名为bathTowel.jpg。在我的actionlistener中,我不确定如何将文件名与项目名称相关联。

当用户选择浴巾时,我的动作监听器将捕获此名称,如何将浴巾与我的hashmap联系以获取文件名bathTowel.jpg

我的JComboBox课程:

public class StockDropdown extends StockData {
    JComboBox stockOptions = new JComboBox(); 
    List<String> filename = new ArrayList<String>();

    private JLabel imgDis;
    StockData sD;


    public StockDropdown(){
        for(String key : StockData.getStock().keySet())  {
          stockOptions.addItem(StockData.getName(key));
          filename.add(StockData.getFilename(key));
        }
        stockOptions.addItemListener(
            new ItemListener() {
               @Override
                public void itemStateChanged(ItemEvent ie) {
                    if(ie.getStateChange() == ItemEvent.SELECTED){
                        String temp = stockOptions.getSelectedItem().toString();
                        String filePath;

                        for(String key : sD.getStock().keySet())  {
                            if(temp.equals(sD.getName(key))) {
                                filePath = sD.getFilename(key);
                                remove(imgDis);
                                imgDis = new JLabel(setImageSize(filePath));
                                c.gridy = 1;
                                add(imgDis,c);
                                repaint();
                                revalidate();
                            }
                        }
                    }
                }
            }
        );
    }

    private ImageIcon setImageSize(String path) {
        ImageIcon image1 = new ImageIcon(path);
        Image image2 = image1.getImage().getScaledInstance(200,200,0);
        return new ImageIcon(image2);
    };


    public JComboBox getComboBox(){
        return stockOptions;
    }

}

我的班级数据:

public class StockData {
    private static class Item {
        private final String name;
        private final double price;
        private int quantity;
        private String filename;

        Item(String n, double p, int q, String f) {
            name = n;
            price = p;
            quantity = q;
            filename = f;
        }

        public String getName() {
            return name;
        }

        public double getPrice() {
            return price;
        }

        public int getQuantity() {
            return quantity;
        }

        public String getFilename() {
            return filename;
        }
    }

    public final static Map<String, Item> stock = new HashMap();

    static {
        stock.put("00", new Item("Bath towel", 5.50, 10, "bathTowel.jpg"));
        stock.put("11", new Item("Plebney light", 20.00, 5, "gorillaSuit.jpg"));
        stock.put("22", new Item("Gorilla suit", 30.00, 7, "oven.jpg"));
        stock.put("33", new Item("Whizz games console", 50.00, 8, "plebneyLight.jpg"));
        stock.put("44", new Item("Oven", 200.00, 4, "whizzGamesConsole.jpg"));
    }

    public static Map<String, Item> getStock() {
       return stock;
     }

    public static String getName(String key) {
        Item item = stock.get(key);
        if (item == null)
            return null;
        return item.getName();
    }

    public static double getPrice(String key) {
        Item item = stock.get(key);
        if (item == null)
            return -1.0;
        return item.getPrice();
    }

    public static int getQuantity(String key) {
        Item item = stock.get(key);
        if (item == null)
            return -1;
        return item.getQuantity();
    }
    public static String getFilename(String key) {
        Item item = stock.get(key);
        if (item == null)
            return null;
        return item.getFilename();
    }

    public static void update(String key, int extra) {
        Item item = stock.get(key);
        if (item != null)
            item.quantity += extra;
    }
}

我用来显示JComboBox的类:

public class PurchaseStock extends JFrame implements ActionListener {

    StockDropdown stockDropdown = new StockDropdown();


    public PurchaseStock(){
        setLayout(new BorderLayout());
        setBounds(100, 100, 450, 300);
        setTitle("Update Stock");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel top = new JPanel();
        add("North", top);
        JPanel middle = new JPanel();
        add("Center", middle);


        top.add(stockDropdown.getComboBox());

        setResizable(false);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent ae) {

    }
}

1 个答案:

答案 0 :(得分:1)

您已经非常接近您的代码实现目标。要做你想做的事,你可以使用。

public void itemStateChanged(ItemEvent ie) {
    if(ie.getStateChange() == ItemEvent.SELECTED){
        String temp = stockOptions.getSelectedItem().toString();
        String filePath;

        for(String key : sD.getStock().keySet())  {
            if(temp.equals(sD.getName(key))) {
                filePath = sD.getFilename(key);
            }
        }
    }
}

我用你的代码做了一个简单的例子,向你展示一个简单的实现。我不得不稍微改变你的代码,但我保留了尽可能多的代码。

<强> StockData.java

import java.util.*;

public class StockData {

    private static class Item {
        Item(String n, double p, int q, String f) {
            name = n;
            price = p;
            quantity = q;
            filename = f;
        }

        // get methods
        public String getName() {
            return name;
        }

        public double getPrice() {
            return price;
        }

        public int getQuantity() {
            return quantity;
        }

        public String getFilename() {
            return filename;
        }

        // instance variables 
        private final String name;
        private final double price;
        private int quantity;
        private String filename;
    }

    public final static Map<String, Item> stock = new HashMap();

    static {
        // if you want to have extra stock items, put them in here
        // use the same style - keys should be Strings
        stock.put("00", new Item("Bath towel", 5.50, 10, "images/crazyEmoji.jpg"));
        stock.put("11", new Item("Plebney light", 20.00, 5, "images/sadEmoji.png"));
        stock.put("22", new Item("Gorilla suit", 30.00, 7, "images/scaredEmoji.jpg"));
        stock.put("33", new Item("Whizz games console", 50.00, 8, "images/winkEmoji.png"));
        stock.put("44", new Item("Oven", 200.00, 4, "images/zippedEmoji.jpg"));
    }

    public static Map<String, Item> getStock() {
       return stock;
    }

    public static String getName(String key) {
        Item item = stock.get(key);
        if (item == null) {
            return null; // null means no such item
        } else {
            return item.getName();
        }
    }

    public static double getPrice(String key) {
        Item item = stock.get(key);
        if (item == null) {
            return -1.0; // negative price means no such item
        } else {
            return item.getPrice();
        }
    }

    public static int getQuantity(String key) {
        Item item = stock.get(key);
        if (item == null) {
            return -1; // negative quantity means no such item
        } else {
            return item.getQuantity();
        }
    }
    public static String getFilename(String key) {
        Item item = stock.get(key);
        if (item == null) {
            return null; // null means no such item
        } else {
            return item.getFilename();
        }
    }

    public static void update(String key, int extra) {
        Item item = stock.get(key);
        if (item != null) {
            item.quantity += extra;
        }
    }


}

<强> StockDropdown.java

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.Image;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Dimension;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.util.List;
import java.util.ArrayList;

public class StockDropdown extends JFrame {
    private JComboBox stockOptions = new JComboBox();
    private JLabel imgDis;
    private List<String> filename = new ArrayList<String>();
    StockData sD;

    StockDropdown() {
        super("Fist Window");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();

        for(String key : sD.getStock().keySet())  {
          stockOptions.addItem(sD.getName(key));
          filename.add(sD.getFilename(key));
        }

        stockOptions.addItemListener(
            new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent ie) {
                    if(ie.getStateChange() == ItemEvent.SELECTED){
                        String temp = stockOptions.getSelectedItem().toString();
                        String filePath;

                        for(String key : sD.getStock().keySet())  {
                            if(temp.equals(sD.getName(key))) {
                                filePath = sD.getFilename(key);
                                remove(imgDis);
                                imgDis = new JLabel(setImageSize(filePath));
                                c.gridy = 1;
                                add(imgDis,c);
                                repaint();
                                revalidate();
                            }
                        }
                    }
                }
            }
        );
        c.gridy = 0;
        add(stockOptions,c);


        imgDis = new JLabel(setImageSize("images/crazyEmoji.jpg"));
        c.gridy = 1;
        imgDis.setPreferredSize(new Dimension(200,200));
        add(imgDis,c);

        pack();
        setVisible(true);
    }

    private ImageIcon setImageSize(String path) {
        ImageIcon image1 = new ImageIcon(path);
        Image image2 = image1.getImage().getScaledInstance(200,200,0);
        return new ImageIcon(image2);
    };

    public JComboBox getComboBox(){
        return stockOptions;
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                StockDropdown frame = new StockDropdown();
            }
        });
    }
}

这会产生类似

的东西

enter image description here Option 1

如果你没注意到我也改变了图像

修改

而不是在单独的类中使JComboBox与您的JFrame类相同。

例如,使用您正在使用的布局以避免混淆。

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import java.awt.Image;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.ArrayList;

public class PurchaseStock  extends JFrame implements ActionListener {
    private JComboBox stockOptions = new JComboBox();
    private JLabel imgDis;
    private List<String> filename = new ArrayList<String>();
    StockData sD;

    PurchaseStock () {
        super("Fist Window");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JPanel top = new JPanel();
        add("North", top);
        JPanel middle = new JPanel();
        add("Center", middle);

        for(String key : sD.getStock().keySet())  {
          stockOptions.addItem(sD.getName(key));
          filename.add(sD.getFilename(key));
        }

        stockOptions.addItemListener(
            new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent ie) {
                    if(ie.getStateChange() == ItemEvent.SELECTED){
                        String temp = stockOptions.getSelectedItem().toString();
                        String filePath;

                        for(String key : sD.getStock().keySet())  {
                            if(temp.equals(sD.getName(key))) {
                                filePath = sD.getFilename(key);
                                middle.remove(imgDis);
                                imgDis = new JLabel(setImageSize(filePath));
                                middle.add(imgDis);
                                middle.repaint();
                                middle.revalidate();
                            }
                        }
                    }
                }
            }
        );

        top.add(stockOptions);



        imgDis = new JLabel(setImageSize("images/crazyEmoji.jpg"));
        imgDis.setPreferredSize(new Dimension(200,200));
        middle.add(imgDis);

        pack();
        setVisible(true);
    }

    private ImageIcon setImageSize(String path) {
        ImageIcon image1 = new ImageIcon(path);
        Image image2 = image1.getImage().getScaledInstance(200,200,0);
        return new ImageIcon(image2);
    };

    public JComboBox getComboBox(){
        return stockOptions;
    }

    @Override
    public void actionPerformed(ActionEvent ae) {

    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PurchaseStock  frame = new PurchaseStock ();
            }
        });
    }
}

修改2

以下是您的三个班级

<强> StockData.java

import java.util.*;

public class StockData {

    private static class Item {
        Item(String n, double p, int q, String f) {
            name = n;
            price = p;
            quantity = q;
            filename = f;
        }

        // get methods
        public String getName() {
            return name;
        }

        public double getPrice() {
            return price;
        }

        public int getQuantity() {
            return quantity;
        }

        public String getFilename() {
            return filename;
        }

        // instance variables 
        private final String name;
        private final double price;
        private int quantity;
        private String filename;
    }

    public final static Map<String, Item> stock = new HashMap();

    static {
        // if you want to have extra stock items, put them in here
        // use the same style - keys should be Strings
        stock.put("00", new Item("Bath towel", 5.50, 10, "images/crazyEmoji.jpg"));
        stock.put("11", new Item("Plebney light", 20.00, 5, "images/sadEmoji.png"));
        stock.put("22", new Item("Gorilla suit", 30.00, 7, "images/scaredEmoji.jpg"));
        stock.put("33", new Item("Whizz games console", 50.00, 8, "images/winkEmoji.png"));
        stock.put("44", new Item("Oven", 200.00, 4, "images/zippedEmoji.jpg"));
    }

    public static Map<String, Item> getStock() {
       return stock;
    }

    public static String getName(String key) {
        Item item = stock.get(key);
        if (item == null) {
            return null; // null means no such item
        } else {
            return item.getName();
        }
    }

    public static double getPrice(String key) {
        Item item = stock.get(key);
        if (item == null) {
            return -1.0; // negative price means no such item
        } else {
            return item.getPrice();
        }
    }

    public static int getQuantity(String key) {
        Item item = stock.get(key);
        if (item == null) {
            return -1; // negative quantity means no such item
        } else {
            return item.getQuantity();
        }
    }
    public static String getFilename(String key) {
        Item item = stock.get(key);
        if (item == null) {
            return null; // null means no such item
        } else {
            return item.getFilename();
        }
    }

    public static void update(String key, int extra) {
        Item item = stock.get(key);
        if (item != null) {
            item.quantity += extra;
        }
    }


}

<强> StockDropdown.java

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.Image;
import java.awt.Dimension;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.util.List;
import java.util.ArrayList;

public class StockDropdown extends JComboBox {
    List<String> filename = new ArrayList<String>();

    private JLabel imgDis;
    StockData sD;
    PurchaseStock pS;


    public StockDropdown(PurchaseStock pS) {
        this.pS = pS;

        imgDis = new JLabel(setImageSize("images/crazyEmoji.jpg"));
        imgDis.setPreferredSize(new Dimension(200,200));
        pS.getMiddle().add(imgDis);
        pS.getMiddle().repaint();
        pS.getMiddle().revalidate();

        for(String key : sD.getStock().keySet())  {
          addItem(sD.getName(key));
        }

        addItemListener(
            new ItemListener() {
               @Override
                public void itemStateChanged(ItemEvent ie) {
                    if(ie.getStateChange() == ItemEvent.SELECTED){
                        String temp = getSelectedItem().toString();
                        String filePath;

                        for(String key : sD.getStock().keySet())  {
                            if(temp.equals(sD.getName(key))) {
                                filePath = sD.getFilename(key);
                                pS.getMiddle().remove(imgDis);
                                imgDis = new JLabel(setImageSize(filePath));
                                pS.getMiddle().add(imgDis);
                                pS.getMiddle().repaint();
                                pS.getMiddle().revalidate();
                            }
                        }
                    }
                }
            }
        );
    }

    private ImageIcon setImageSize(String path) {
        ImageIcon image1 = new ImageIcon(path);
        Image image2 = image1.getImage().getScaledInstance(200,200,0);
        return new ImageIcon(image2);
    };
}

<强> PurchaseStock.java

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class PurchaseStock  extends JFrame implements ActionListener {
    private JPanel top = new JPanel();
    private JPanel middle = new JPanel();
    StockData sD;

    PurchaseStock () {
        super("Fist Window");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        add("North", top);
        add("Center", middle);

        top.add(new StockDropdown(this));

        pack();
        setVisible(true);
    }

    public JPanel getMiddle() {
        return middle;
    }

    @Override
    public void actionPerformed(ActionEvent ae) {

    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                PurchaseStock  frame = new PurchaseStock();
            }
        });
    }
}

这会将JComboBox代码与JFrame课程分开,但我仍然认为将JComboBoxJFrame放在一起会更好。这也使用BorderLayout以避免混淆。