2014-04-13 25 views
0

我很難搞清楚如何移動和圖像到窗口中的不同位置。我閱讀了BorderLayout,但我不知道如何實現它。我想讓圖像位於文本區域之上,但我不知道如何在對話框中對其進行操作。如何在對話框中使用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

回答

2

你會需要一個邊界佈局的額外的JPanel。對於那個容器,你可以像這樣將圖標添加到北方,並將滾動窗格添加到中心。

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

+0

感謝很多人非常有幫助! – Eric

+0

很高興我能幫到你。 –