如何在对话框中使用BorderLayout?

时间:2014-04-13 16:56:51

标签: java eclipse user-interface jpanel

我无法弄清楚如何移动和成像到窗口中的不同位置。我读到了BorderLayout,但我不确定如何实现它。我希望图像在文本区域上方,但我不知道我是如何在对话框中进行的。

b3.addActionListener(new ActionListener() {
        /**
         * Displays the arraylist.
         */
        public void actionPerformed(ActionEvent e) {

            if (cars.size()>0){

                ImageIcon icon = new ImageIcon(Window.class.getResource("/car.png"));
                StringBuilder sb = new StringBuilder();


                for(int i=0; i < cars.size(); i++) {
                    sb.append("Car " + (i+1) + ": " + cars.get(i) + "\n");
                }

                Font font = new Font("Times New Roman", Font.PLAIN, 14);
                JTextArea textArea = new JTextArea(sb.toString());
                JScrollPane scrollPane = new JScrollPane(textArea); 
                textArea.setFont(font);
                textArea.setForeground(Color.BLACK);
                textArea.setLineWrap(true);
                textArea.setEditable(false);
                textArea.setWrapStyleWord(true); 
                scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
                scrollPane.setPreferredSize(new Dimension( 100, 125 ));
                JOptionPane.showMessageDialog(null, scrollPane, "Inventory", JOptionPane.PLAIN_MESSAGE, icon);
            }
            else {
                JOptionPane.showMessageDialog(null, "No cars available in inventory", "Error", JOptionPane.ERROR_MESSAGE);
            }


        }

    });

Pic

1 个答案:

答案 0 :(得分:2)

您需要一个带边框布局的额外JPanel。对于该容器,您可以将图标添加到North,将滚动窗格添加到中心,如下所示。

JPanel contents = new JPanel(new BorderLayout());

JLabel carImage = new JLabel(icon);

contents.add(carImage, BorderLayout.NORTH);
contents.add(scrollPane, BorderLayout.CENTER);

JOptionPane.showMessageDialog(null, contents, "Inventory", JOptionPane.PLAIN_MESSAGE);

产生类似的东西:

enter image description here