Почему JList неправильно отображает элементы на JPanel - PullRequest
0 голосов
/ 12 апреля 2019

Каждый класс ItemView создает свой собственный экземпляр класса элемента.Я хочу разместить несколько виджетов ItemView, каждый для каждого элемента на панели Jpanel, чтобы отображать их. Я хочу, чтобы они были активными.

ЭТО ПРОХОДИТ В МЕТОДЕ configureUi в главном классе

это то, что я получаю с помощью следующего кода : почему виджеты отображаются так, а не как на втором изображении

    JPanel board = new JPanel();
 DefaultListModel<ItemView> listModel = new DefaultListModel<>();
            listModel.addElement(itemView);
            listModel.addElement(itemView1);
            //create the Jlist
            JList<ItemView> itemsList = new JList<>(listModel);
            board.add(itemsList);

Я получаю взглянуть со следующим кодом, и вот как я хочу, чтобы он выглядел, но проблема в том, что он НЕ кликабелен, и мне нужно, чтобы он был кликабелен.

        JPanel board = new JPanel();
        Vector<ItemView> list = new Vector<>();
        list.add(itemView);
        list.add(itemView);
        list.add(itemView1);
        JList<ItemView> itemsList = new JList<>(list);

       ListModel<ItemView> model = itemsList.getModel();
        for (int i =0; i < itemsList.getModel().getSize(); i++){
            ItemView itemView = itemsList.getModel().getElementAt(i);
            board.add(itemView);
        }

не должен быть кликабельным, просто будучи элементом вJList?Как мне сделать так, чтобы отображались виджеты itemView, которые можно нажимать?

КЛАСС ПРОДУКЦИИ

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.font.TextAttribute;
import java.io.IOException;
import java.net.URL;
import java.text.AttributedString;

/** A special panel to display the detail of an item. */

@SuppressWarnings("serial")
public class ItemView extends JPanel{

    double originalPrice = 25.00;
    Item item = new Item("https://www.amazon.com/Cards-Against-Humanity-LLC-CAHUS/dp/B004S8F7QM/ref=br_asw_pdt-2?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=&pf_rd_r=5AKCTP4FR3Y4DQDMK62F&pf_rd_t=36701&pf_rd_p=da24e60a-b03f-4464-a877-3327db3bc407&pf_rd_i=desktop","Cards Against Humanity", originalPrice);

    /** Interface to notify a click on the view page icon. */
    public interface ClickListener {

        /** Callback to be invoked when the view page icon is clicked. */
        void clicked();
    }

    /** Directory for image files: src/image in Eclipse. */
    private final static String IMAGE_DIR = "image/";

    /** View-page clicking listener. */
    private ClickListener listener;

    /** Create a new instance. */
    public ItemView() {

        setPreferredSize(new Dimension(100, 160));
        setBackground(new Color(249, 232, 239));
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                if (isViewPageClicked(e.getX(), e.getY()) && listener != null) {
                    listener.clicked();
                }
            }
        });
    }

    /** Set the view-page click listener. */
    public void setClickListener(ClickListener listener) {
        this.listener = listener;
    }

    /** Overridden here to display the details of the item. */

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Dimension dim = getSize();

        //--
        //-- WRITE YOUR CODE HERE!
        //--

        g.setColor(Color.black);
        g.setFont(new Font("Dialog", Font.PLAIN, 12));
        int x = 20, y = 30;
        g.drawImage(getImage("view.png"),x,15, null);
        y += 20;
        /* this didnt work, the text never jump to the next line...*/
        //g.drawString(item.toString(),x,y);
        g.drawString("Name:      " + item.getName(),x,y);
        y += 20;
        g.drawString("URL:         " + item.getUrl(), x, y);
        y += 20;
        g.drawString("Price:        " + item.getPrice(), x, y);
        y += 20;
        g.drawString("Change:   " + item.getPriceChange()+ "%", x, y);
        y += 20;
        g.drawString("Added:     " + item.getDate() + " ( $ "+ originalPrice +")", x, y);


    }

    /** Return true if the given screen coordinate is inside the viewPage icon. */
    private boolean isViewPageClicked(int x, int y) {
        //--
        //-- WRITE YOUR CODE HERE
        //--
        if(x == 20 && y == 30){
            return true;
        }
        else
            return new Rectangle(20, 20, 30, 20).contains(x,  y);
    }

    /** Return the image stored in the given file. */
    public Image getImage(String file) {
        try {
            URL url = new URL(getClass().getResource(IMAGE_DIR), file);
            return ImageIO.read(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

ГЛАВНЫЙ КЛАСС У меня есть кучаКОММЕНТАРИИ ЗДЕСЬ, ПОТОМУ ЧТО Я НАЧИНАЮ НА КОДИНГЕ

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Vector;


    @SuppressWarnings("serial")
    public class Main extends JFrame {

        /** Default dimension of the dialog. */
        private final static Dimension DEFAULT_SIZE = new Dimension(400, 600);

        /** Special panel to display the watched item. */
        private ItemView itemView;

    /** Message bar to display various messages. */
        private JLabel msgBar = new JLabel(" ");

        /** Create a new dialog. */
        public Main() {
            this(DEFAULT_SIZE);
        }
Item item = new Item();
        /** Create a new dialog of the given screen dimension. */
        public Main(Dimension dim) {
            super("Price Watcher");
            setSize(dim);
            configureUI();

            frameMenu();
            makeControlPanel();
            setLocationRelativeTo(null);
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            setVisible(true);
            setResizable(true);
            showMessage("Welcome!!");


        }
        /** Callback to be invoked when the refresh button is clicked.
         * Find the current price of the watched item and display it
         * along with a percentage price change. */
        private void refreshButtonClicked(ActionEvent event) {

            itemView.item.checkPrice();
            repaint();
            showMessage("Current Price: " + itemView.item.getPrice());
        }

        /** Callback to be invoked when the view-page icon is clicked.
         * Launch a (default) web browser by supplying the URL of
         * the item. */
        private void viewPageClicked() {
            try{
                Desktop.getDesktop().browse(new URL(itemView.item.getUrl()).toURI());
            }catch(Exception e){}

            showMessage("View clicked!");
        }

        /** Configure UI. */
        /*we create the itemview here, for the set item, but now we have to create more and manage them*/
        private void configureUI() {

            setLayout(new BorderLayout());

            JPanel board = new JPanel();
            board.setBackground(Color.white);
            board.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createEmptyBorder(10,16,0,16),
                    BorderFactory.createLineBorder(Color.pink)));
            board.setLayout(new GridLayout(3,1));

            ItemView itemView1 = new ItemView();

            itemView.setClickListener(this::viewPageClicked);

            DefaultListModel<ItemView> listModel = new DefaultListModel<>();
            listModel.addElement(itemView);
            listModel.addElement(itemView1);
            //create the list
            JList<ItemView> itemsList = new JList<>(listModel);
            board.add(itemsList);

            add(new JScrollPane(itemsList));


           /* Vector<ItemView> list = new Vector<>();
            list.add(itemView);
            list.add(itemView);
            list.add(itemView1);
            JList<ItemView> itemsList = new JList<>(list);

           ListModel<ItemView> model = itemsList.getModel();
            for (int i =0; i < itemsList.getModel().getSize(); i++){
                ItemView itemView = itemsList.getModel().getElementAt(i);
                board.add(itemView);
            }*/
            board.add(itemsList);


            add(board, BorderLayout.CENTER);
            msgBar.setBorder(BorderFactory.createEmptyBorder(10,16,10,0));
            add(msgBar, BorderLayout.SOUTH);
        }

        /** Create a control panel consisting of a refresh button. which is inside the frame, not part of the frame en si*/
        private JPanel makeControlPanel() {
            JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            //JButton allItems = new JButton(getImage("image/screen.png"));
            //allItems.setPreferredSize(new Dimension(20,20));
            //add.setPreferredSize(new Dimension(10, 10));
            //panel.add(allItems);
            ///JButton refreshButton = new JButton("Refresh");
            //refreshButton.setFocusPainted(false);
            //refreshButton.addActionListener(this::refreshButtonClicked);
            //panel.add(refreshButton);
            return panel;
        }

        /** Show briefly the given string in the message bar. */
        private void showMessage(String msg) {
            msgBar.setText(msg);
            new Thread(() -> {
                try {
                    Thread.sleep(3 * 1000); // 3 seconds
                } catch (InterruptedException e) {
                }
                if (msg.equals(msgBar.getText())) {
                    SwingUtilities.invokeLater(() -> msgBar.setText(" "));
                }
            }).start();
        }
        private void frameMenu(){
            JMenuBar menuBar = new JMenuBar();
            JMenu appMenu = new JMenu("App");
            JMenu itemMenu = new JMenu("Item");
            JMenu sortMenu = new JMenu("Sort");

            JMenuItem myItem;
            //appMenu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");

            myItem = new JMenuItem("About",getImage("image/info.png"));
            appMenu.add(myItem);
            myItem = new JMenuItem("Exit");
            appMenu.add(myItem);
            menuBar.add(appMenu);


            //
            myItem = new JMenuItem("Check prices", getImage("image/check0.png"));
            myItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.ALT_MASK));
            itemMenu.add(myItem);

            myItem = new JMenuItem("Add item",getImage("image/add.png"));
            myItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.ALT_MASK));
            itemMenu.add(myItem);

            itemMenu.addSeparator();

            myItem = new JMenuItem("Search",getImage("image/search.png"));
            myItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK));

            itemMenu.add(myItem);
            myItem = new JMenuItem("Select first",getImage("image/first.png"));
            myItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.ALT_MASK));

            itemMenu.add(myItem);
            myItem = new JMenuItem("Select last",getImage("image/last.png"));
            myItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.ALT_MASK));

            itemMenu.add(myItem);
            itemMenu.addSeparator();

            // NEW SUBMENU
            //a submenu(add a menu to another menu like itemMenu)
            JMenu selected = new JMenu("Selected");

            myItem = new JMenuItem("Price",getImage("image/check.png"));
            myItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.ALT_MASK));

            selected.add(myItem);
            myItem = new JMenuItem("View",getImage("image/link.png"));
            myItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.ALT_MASK));

            selected.add(myItem);
            myItem = new JMenuItem("Edit",getImage("image/edit.png"));
            myItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.ALT_MASK));

            selected.add(myItem);
            myItem = new JMenuItem("Remove",getImage("image/delete.png"));
            myItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.ALT_MASK));

            selected.add(myItem);
            selected.addSeparator();
            myItem = new JMenuItem("Copy name");
            selected.add(myItem);
            myItem = new JMenuItem("Copy url");
            selected.add(myItem);
            myItem = new JMenuItem("Copy item");
            selected.add(myItem);


            itemMenu.add(selected);
            menuBar.add(itemMenu);


            //add items in menu to group so only one can be selected at a time
            ButtonGroup group = new ButtonGroup();


            JRadioButtonMenuItem myItemR = new JRadioButtonMenuItem("Add oldest");
            sortMenu.add(myItemR);
            group.add(myItemR);

            myItemR = new JRadioButtonMenuItem("Add newest");
            sortMenu.add(myItemR);
            group.add(myItemR);

            sortMenu.addSeparator();

            myItemR = new JRadioButtonMenuItem("Name ascending");
            sortMenu.add(myItemR);
            group.add(myItemR);

            myItemR = new JRadioButtonMenuItem("Name descending");
            sortMenu.add(myItemR);
            group.add(myItemR);

            sortMenu.addSeparator();

            myItemR = new JRadioButtonMenuItem("Price Change (%)");
            sortMenu.add(myItemR);
            group.add(myItemR);

            myItemR = new JRadioButtonMenuItem("Price low ($)");
            sortMenu.add(myItemR);
            group.add(myItemR);

            myItemR = new JRadioButtonMenuItem("Price high ($)");
            sortMenu.add(myItemR);
            group.add(myItemR);

            menuBar.add(sortMenu);
            setJMenuBar(menuBar);
            menuBar.add(sortMenu);

            setJMenuBar(menuBar);

            /*Create a JToolbar to the frame*/
            JToolBar toolbar = new JToolBar();
            toolbar.setPreferredSize(new Dimension(35, 30));
            add(toolbar, BorderLayout.PAGE_START);


            JButton refresh = new JButton(getImage("image/refresh.png"));
            refresh.setPreferredSize(new Dimension(1,20));
            refresh.setToolTipText("Check all prices");
            toolbar.add(refresh);
            refresh.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
          // ----> /*I need to check for all items in the jlist...*/
                    itemView.item.checkPrice();
                    repaint();
                    showMessage("Current Price: " + itemView.item.getPrice());                }
            });

            JButton add = new JButton(getImage("image/add.png"));
            add.setPreferredSize(new Dimension(20,20));
            add.setToolTipText("Add an item");
            toolbar.add(add);
            add.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //JOptionPane.showMessageDialog(frame, "Calendar clicked");

                }
            });

            JButton search = new JButton(getImage("image/search.png"));
            search.setPreferredSize(new Dimension(20,20));
            search.setToolTipText("Search items");
            toolbar.add(search);
            search.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //JOptionPane.showMessageDialog(frame, "Calendar clicked");
                }
            });
            JButton selFirst = new JButton(getImage("image/first.png"));
            selFirst.setPreferredSize(new Dimension(20,20));
            selFirst.setToolTipText("Select first item");
            toolbar.add(selFirst);
            selFirst.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //JOptionPane.showMessageDialog(frame, "Calendar clicked");
                }
            });
            JButton selectLast = new JButton(getImage("image/last.png"));
            selectLast.setPreferredSize(new Dimension(20,20));
            selectLast.setToolTipText("Select last item");
            toolbar.add(selectLast);
            selFirst.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //JOptionPane.showMessageDialog(frame, "Calendar clicked");
                }
            });
            //separator
            toolbar.addSeparator();

            JButton check = new JButton(getImage("image/check.png"));
            check.setPreferredSize(new Dimension(20,20));
            check.setToolTipText("Check price of selected item");

            toolbar.add(check);
            check.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //JOptionPane.showMessageDialog(frame, "Calendar clicked");
                }
            });
            JButton openLink = new JButton(getImage("image/link.png"));
            openLink.setPreferredSize(new Dimension(20,20));
            openLink.setToolTipText("View web page of selected item");

            toolbar.add(openLink);
            openLink.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //JOptionPane.showMessageDialog(frame, "Calendar clicked");
                }
            });
            JButton edit = new JButton(getImage("image/edit.png"));
            edit.setPreferredSize(new Dimension(20,20));
            edit.setToolTipText("Edit selected item");

            toolbar.add(edit);
            edit.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //JOptionPane.showMessageDialog(frame, "Calendar clicked");
                }
            });
            JButton delete = new JButton(getImage("image/delete.png"));
            delete.setPreferredSize(new Dimension(20,20));
            delete.setToolTipText("Delete selected item");

            toolbar.add(delete);
            delete.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //JOptionPane.showMessageDialog(frame, "Calendar clicked");
                }
            });
            toolbar.addSeparator();

            JButton info = new JButton(getImage("image/info.png"));
            info.setPreferredSize(new Dimension(20,20));
            toolbar.add(info);
            info.setToolTipText("Show app information");
            info.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //JOptionPane.showMessageDialog(frame, "Calendar clicked");
                }
            });
        }
    public ImageIcon getImage(String file){
        try {
            return new ImageIcon(ImageIO.read(getClass().getResource(file)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {

            new Main();
        }
    }
/*
* JButton delete = new JButton(getImage("image/add.png"));
            delete.setPreferredSize(new Dimension(20,20));

            try {
                Image img = ImageIO.read(getClass().getResource("image/delete.png"));
                delete.setIcon(new ImageIcon(img));
            } catch (Exception ex) {
                System.out.println(ex);
            }
            //add.setPreferredSize(new Dimension(10, 10));
            toolbar.add(delete);*/

Класс товара

package pricewatcher.HW2;

import java.text.DecimalFormat;
import java.util.Date;

public class Item {

        private String url;
        private String name;
        private double price;
        private double priceChange;//percentage
        private Date date;
        priceFinder pf = new priceFinder();
        DecimalFormat formatter = new DecimalFormat("#0.00");

        public Item(){
            date = new Date();
        }
        /**
         * Item constructor
         * @param url link to the item
         * @param name name of the item
         * @param price price of item
         * */
        public Item(String url, String name, double price) {
            this.url = url;
            this.name = name;
            this.price = price;
            this.priceChange = 0.0;
            this.date = new Date();
        }

        public String getUrl() {
            return url;
        }

        public String getName() {
            return name;
        }

        public double getPrice() {//current price
            return Double.parseDouble(formatter.format(price));
        }

        public Date getDate() {
            return date;
        }

        public double getprice() {
        return price;
    }

        public double getPriceChange() {
        return Double.parseDouble(formatter.format(priceChange));
    }

        public void setPrice(double price) {
            this.price = price;
        }

        public void setPriceChange(double priceChange) {
            this.priceChange = priceChange;
        }

        public void setDate(Date date) {
            this.date = date;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public void setName(String name) {
            this.name = name;
        }

    /**
     * checks the price and if there is a change in the price
     * it then calculates the price difference
     * */

    public void checkPrice(){

        double tmp = getPrice();//original price

        setPrice(pf.simulatedPrice());// change the price
        if (tmp != getPrice()){
            double newPrice = tmp - getPrice();
            double tmp2 = ( tmp + getPrice() ) / 2;
            double j = (newPrice / tmp2) * 100;
            setPriceChange(j);
        }
    }
        /*
        * String representation of the Item object*/
        public String toString(){

            return
                "Name:   " + getName() +
                "\nUrl:    " + getUrl()+
                "\nPrice:  $" + getPrice()+
                "\nChange: " + formatter.format(getPriceChange()) + "%"+
                "\nAdded:  " + getDate();
            }
        }

класс поиска цен

package pricewatcher.HW2;

import java.util.Random;

public class priceFinder {
    public priceFinder(){

    }
    /**
     * simulates a price for the fixed item
     * */
    public double simulatedPrice(){
        Random random = new Random();
        double simulatedPrice = random.nextInt(100);
        return simulatedPrice;
    }
}
...