2017-02-24 24 views
0

我具有低於此的JFrame:添加圖像和按鈕到一個JPanel

public class TestJFrame extends JFrame { 
    public RecyclingMachinesGui(String title) { 
     super (title); 

     Container container = getContentPane(); 
     container.setLayout(new FlowLayout()); 

     Panel r = new Panel(); 
     Jbutton j = new JButton("Recycle Item"); 
     r.add(j); 
     container.add(r); 

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setLocationRelativeTo(null);  
     setSize(500,500); 
     setVisible(true); 
    } 

    private class Panel extends JPanel { 
     private BufferedImage image; 

     public Panel() { 
      try { 
       image = ImageIO.read(new File("./temp.png")); 
      }catch (IOException e) { 
       e.getMessage().toString(); 
      } 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      g.drawImage(image, 0, 0, this); 
     } 
    } 
} 

在我的主要方法中的上述代碼時,我由於某種原因,運行new TestJFrame()我只看到裏面的JButton jPanel(其我添加到我的容器中),並沒有看到面板內的圖像。我的面板中的paintComponent方法沒有被調用?

我想在頂部有一張圖片,面板底部有一個按鈕。任何人都可以解釋爲什麼這不會發生?

+0

是被載入圖像,這是偉大?如果要在頂部顯示圖像並在面板上顯示按鈕,請使用「BorderLayout」,將圖像包裝在「JLabel」中並將其添加到中心位置,並將按鈕向南放置到位置 – MadProgrammer

+0

使用「面板類? – CapturedTree

+1

應用程序資源在部署時將成爲嵌入式資源,所以現在開始訪問它們是明智的做法。 [tag:embedded-resource]必須通過URL而不是文件訪問。請參閱[信息。頁面爲嵌入式資源](http://stackoverflow.com/tags/embedded-resource/info)如何形成的URL。 –

回答

2

的圖像在你Panel沒有顯示, 因爲Panel沒有適當首選大小。 因此,LayoutManager(FlowLayout)不知道將哪個大小 賦予Panel,並給它一個非常小的正方形的大小。 因此,您PanelpaintComponent實際上是調用, 但它是一種無形的小面積只有畫,

您可以輕鬆地在Panel修復它的構造器通過加載圖像後調用setPreferredSize立即 :

image = ImageIO.read(new File("./temp.png")); 
setPreferredSize(new Dimension(image.getWidth(), image.getHeight())); 
+2

*「你可以很容易地修復它..」* ..通過使用'JLabel'顯示圖像。 –

2

我想有一個在頂部的畫面,面板底部的按鈕。任何人都可以解釋爲什麼這不會發生?

好了,所以你並不真的需要自己繪製圖像,一個JLabel會做非常漂亮的本身,那麼你只需要使用一個BorderLayout到標籤的中心和按鈕添加到南部,例如...

public class TestJFrame extends JFrame { 
    public RecyclingMachinesGui(String title) { 
     super (title); 

     Container container = getContentPane(); 
     container.setLayout(new FlowLayout()); 

     JPanel r = new JPanel(new BorderLayout()); 
     try { 
      r.add(new JLabel(new ImageIcon(ImageIO.read(new File("./temp.png"))))); 
     }catch (IOException e) { 
      e.getMessage().toString(); 
     } 
     Jbutton j = new JButton("Recycle Item"); 
     r.add(j, BorderLayout.SOUTH); 
     container.add(r); 

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setLocationRelativeTo(null);  
     setSize(500,500); 
     setVisible(true); 
    } 
} 

您當前的做法將放置在圖像上的按鈕,如果你想使用的圖像作爲背景

+0

這是一個基於你的意見的想法,所以我不能100%確定它是否能滿足你的整體要求,但它是另一種實現你似乎試圖做的事情的方法;) – MadProgrammer

+0

這個方法可以讓更多感。我會用這個方法去。謝謝!出於對我的'Panel'子類的好奇,何時調用PaintComponent方法?當我實例化'Panel'子類?編輯:這正是我需要的。:) – CapturedTree

+1

@ 1290只有組件在屏幕上「實現」時纔會調用paintComponent',需要進行一些操作,但是可以說,它需要被添加到容器中,並且該容器需要在您的組件可以被繪製之前附加到可見的窗口/框架上......作爲一個簡短的描述;) – MadProgrammer