Java GUI多选程序

时间:2014-12-13 05:11:39

标签: java swing user-interface jlist

我在GUI上遇到了困难。

基本上我想创建一个程序,可以从给定列表中选择和添加项目,并显示添加项目的总金额(项目的价格)。因此,当我从leftlist添加商品时,价格会显示在rightlist,当我按下totalbutton时,所选商品的总价将通过{{1}显示}}。样本将是:

enter image description here

到目前为止,这就是我所做的:

JLabel

我必须在使用import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class MP2_1 extends JFrame{ private JList leftlist; private JList rightlist; private JButton addbutton; private JButton totalbutton; private static String[] items = {"item1", "item2", "item3", "item4", "item5" , "item6", "item7", "item8", "item9", "item10"}; private JButton total; public MP2_1() { super("MP2_1"); setLayout(new FlowLayout()); leftlist = new JList(items); leftlist.setVisibleRowCount(5); leftlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); add(new JScrollPane(leftlist)); addbutton = new JButton("ADD"); addbutton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent event){ rightlist.setListData(leftlist.getSelectedValuesList().toArray()); } } ); add(addbutton); rightlist = new JList(); rightlist.setVisibleRowCount(5); rightlist.setFixedCellWidth(55); rightlist.setFixedCellHeight(20); add(new JScrollPane(rightlist)); totalbutton = new JButton("Total"); totalbutton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent event){ rightlist.setListData(leftlist.getSelectedValuesList().toArray()); } } ); add(totalbutton); } public static void main(String[] args) { MP2_1 list = new MP2_1(); list.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); list.setSize(300,300); list.setVisible(true); } } 这样的结构中犯了一个错误,但我想不出任何其他方式来转移项目的价格,现在它只转移项目本身。

2 个答案:

答案 0 :(得分:1)

基于"当我从左侧列表中添加项目时,价格将显示在右侧列表中" 我可以想到几种方法,我将通过使用ListCellRenderer来演示它,它为您提供了大量的自定义功能。 我已经指出了Total值,你可以将它与标签一起使用。

  1. 创建项目对象。
  2. 创建自定义ListCellRenderer并将其与列表一起使用。
  3. package commonfloor;

    import java.awt.Color;
    import java.awt.Component;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    
    public class MP2_1 extends JFrame {
    
        private JList leftlist;
        private JList rightlist;
    
        private final JButton addbutton;
        private final JButton totalbutton;
    
        private static final Item[] items = {new Item("Item 0", 100), new Item("Item 1", 150), new Item("Item 2", 200), new Item("Item 3", 300)};
    
        private JButton bTotal;
    
        public MP2_1() {
            super("MP2_1");
            setLayout(new FlowLayout());
    
            leftlist = new JList(items);
    
            leftlist.setCellRenderer(new ItemCellRenderer(ItemCellRenderer.ITEM_NAME));
            leftlist.setVisibleRowCount(5);
    
            leftlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
            add(new JScrollPane(leftlist));
    
            addbutton = new JButton("ADD");
            addbutton.addActionListener((ActionEvent event) -> {
                rightlist.setListData(leftlist.getSelectedValuesList().toArray());
    
            });
            add(addbutton);
    
            rightlist = new JList();
            rightlist.setCellRenderer(new ItemCellRenderer(ItemCellRenderer.ITEM_PRICE));
            rightlist.setVisibleRowCount(5);
            rightlist.setFixedCellWidth(55);
            rightlist.setFixedCellHeight(20);
            add(new JScrollPane(rightlist));
    
            totalbutton = new JButton("Total");
            totalbutton.addActionListener((ActionEvent event) -> {
                int total = 0;
                for (int i = 0; i < rightlist.getModel().getSize(); i++) {
                    Item item = (Item) rightlist.getModel().getElementAt(i);
                    int itemPrice = item.getItemPrice();
                    total += itemPrice;
                }
                System.out.println("Total " + total);
                // set the total label here
            });
            add(totalbutton);
    
        }
    
        public static void main(String[] args) {
            MP2_1 list = new MP2_1();
            list.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            list.setSize(300, 300);
            list.setVisible(true);
        }
    
    }
     //Create an Item Object.  
    
    class Item {
    
        private final String itemName;
        private final int itemPrice;
    
        Item(String itemName, int itemPrice) {
            this.itemPrice = itemPrice;
            this.itemName = itemName;
        }
    
        public String getItemName() {
            return itemName;
        }
    
        public int getItemPrice() {
            return itemPrice;
        }
    
    }
    //Create a Custom  CellRenderer and use it with the Lists.
    
    class ItemCellRenderer extends JLabel implements ListCellRenderer<Object> {
    
        static int ITEM_NAME = 0;
        static int ITEM_PRICE = 1;
        private final int type;
    
        public ItemCellRenderer(int type) {
            this.type = type;
            setOpaque(true);
    
        }
    
        @Override
        public Component getListCellRendererComponent(JList<?> list,
                Object value,
                int index,
                boolean isSelected,
                boolean cellHasFocus) {
            Item item = (Item) value;
            setText(type == ITEM_NAME ? item.getItemName() : "" + item.getItemPrice());
    
            Color background;
            Color foreground;
    
            // check if this cell represents the current DnD drop location
            JList.DropLocation dropLocation = list.getDropLocation();
            if (dropLocation != null
                    && !dropLocation.isInsert()
                    && dropLocation.getIndex() == index) {
    
                background = Color.BLUE;
                foreground = Color.WHITE;
    
                // check if this cell is selected
            } else if (isSelected) {
                background = Color.RED;
                foreground = Color.WHITE;
    
                // unselected, and not the DnD drop location
            } else {
                background = Color.WHITE;
                foreground = Color.BLACK;
            }
    
            setBackground(background);
            setForeground(foreground);
    
            return this;
        }
    }
    

答案 1 :(得分:0)

我检查了上面的例子,发现了两件事。一旦我们点击添加按钮将项目添加到右侧列表,它就不会保留列表中先前选择的项目。第二件事是你使用String来显示列表中的项目,但我们需要还有列表对象的价格。

要使与项目I关联的价格创建另一个类,其中包含项目名称以及将在列表中使用的价格。下面是Item类,检查toString方法的注释,以便正确理解和使用它与JList。

public class Item {

    private String itemName;
    private Integer itemPrice;

    public Item(){}
    public Item(String itemName, int itemPrice){
        this.itemName = itemName;
        this.itemPrice = itemPrice;
    }
    public String getItemName() {
        return itemName;
    }
    public void setItemName(String itemName) {
        this.itemName = itemName;
    }
    public Integer getItemPrice() {
        return itemPrice;
    }
    public void setItemPrice(Integer itemPrice) {
        this.itemPrice = itemPrice;
    }
    @Override
    /*
     * This is very important to override as it will be used by JList to show the item name
     */
    public String toString(){
        return this.itemName;
    }
}

我已修改原始类以使用上面的Item类,它将实现您在问题中描述的内容。请注意,我已将Integer用于您的商品价格,您可以将其修改为Double。还要检查下面代码中的注释,以了解课程中所做的更改。

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.swing.*;

public class MP2_1 extends JFrame {
    private JList leftlist;
    private JList rightlist;

    private JButton addbutton;
    private JButton totalbutton;
    private JLabel totalLabel;


    public MP2_1() {

        super("MP2_1");
        setLayout(new FlowLayout());

        // preparing item list it might be coming from somewhere else
        List<Item> itemList = new ArrayList<Item>();
        itemList.add(new Item("Item 1", 100));
        itemList.add(new Item("Item 2", 400));
        itemList.add(new Item("Item 3", 500));
        itemList.add(new Item("Item 4", 600));
        itemList.add(new Item("Item 5", 800));
        itemList.add(new Item("Item 6", 300));
        itemList.add(new Item("Item 7", 200));
        itemList.add(new Item("Item 8", 300));
        itemList.add(new Item("Item 9", 400));

        leftlist = new JList(itemList.toArray());
        leftlist.setVisibleRowCount(5);
        leftlist
                .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        add(new JScrollPane(leftlist));

        addbutton = new JButton("ADD");
        addbutton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //make sure you preserve the previously selected list items
                int size = rightlist.getModel().getSize();
                Set objects = new LinkedHashSet();
                for (int i = 0; i < size; i++) {
                    objects.add(rightlist.getModel().getElementAt(i));
                }
                objects.addAll(Arrays.asList(leftlist.getSelectedValues()));

                rightlist.setListData(objects.toArray());
            }
        });
        add(addbutton);

        rightlist = new JList();
        rightlist.setVisibleRowCount(5);
        rightlist.setFixedCellWidth(55);
        rightlist.setFixedCellHeight(20);
        add(new JScrollPane(rightlist));

        totalbutton = new JButton("Total");
        totalbutton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                // iterate over item objects and calculate the total
                int size = rightlist.getModel().getSize();
                Integer totalAmount = 0;
                for (int i = 0; i < size; i++) {
                    Object obj = leftlist.getModel().getElementAt(i);
                    Item item = (Item) obj;
                    totalAmount += item.getItemPrice();
                }
                //update the total Amount label
                totalLabel.setText("Total Amount : " + totalAmount);
            }
        });
        add(totalbutton);

        totalLabel = new JLabel("Total Amount : ");

        add(totalLabel);

    }

    public static void main(String[] args) {
        MP2_1 list = new MP2_1();
        list.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        list.setSize(300, 300);
        list.setVisible(true);
    }
}

我没有努力纠正用户界面,但其功能足以描述您的需求。