2013-11-20 96 views
4

我目前正在學習Java,並且暫時停滯不前。在JFrame中顯示圖像

我正在尋找一種方法將圖像添加到我的JFrame中。 我發現這個在互聯網上:

ImageIcon image = new ImageIcon("path & name & extension"); 
JLabel imageLabel = new JLabel(image); 

它實現我自己的代碼之後,它看起來像這樣(這僅僅是相關部分):

class Game1 extends JFrame 
{ 
    public static Display f = new Display(); 
    public Game1() 
    { 
     Game1.f.setSize(1000, 750); 
     Game1.f.setResizable(false); 
     Game1.f.setVisible(true); 
     Game1.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     Game1.f.setTitle("Online First Person Shooter"); 

     ImageIcon image = new ImageIcon("C:\\Users\\Meneer\\Pictures\\image.png"); 
     JLabel imageLabel = new JLabel(image); 
     add(imageLabel); 
     } 
} 

class Display extends JFrame 
{ 
} 

當運行這段代碼,它不給我任何錯誤,但它也不顯示圖片。我看到一些問題和人們遇到同樣的問題,但他們的代碼與我的代碼完全不同,他們使用其他方式顯示圖像。

+0

'add(imageLable)'後面保留'setVisible(true)'.. –

回答

2

創建Jlabel

imageLabel.setBounds(10, 10, 400, 400); 
imageLabel.setVisible(true); 

還設置了佈局的JFrame

Game.f.setLayout(new FlowLayout); 
+0

它沒有幫助他 – alex2410

+0

@ alex2410,不用麻煩。 OP認爲這是最好的答案;) – Sage

+0

它做了alex2410。感謝這個答案AJ :)! – user2988879

0

你所添加的標籤錯誤JFrame之後做到這一點。另外,將setVisible()移動到最後。

import javax.swing.*; 
class Game1 extends JFrame 
{ 
    public static Display f = new Display(); 
    public Game1() 
    { 
     // .... 
     Game1.f.add(imageLabel); 
     Game1.f.setVisible(true); 
    } 
} 
6
  1. 你不不需要在Game內使用另一個JFrame實例JFrame
  2. 從構造函數調用setVisible(flag)是不可取的。而是從外面初始化JFrame,把你的setVisible(true)內部事件調度線程使用SwingUtilities.invokeLater(Runnable)
  3. 不要被JFramesetSize(Dimension)給予尺寸暗示維持Swing的GUI呈現規則。相反,在您的組件上使用適當的佈局,在將所有相關組件添加到JFrame之後,請致電pack()
  4. 嘗試使用JScrollPaneJLabel以獲得更好的用戶體驗,圖像大於標籤尺寸。

所有以上描述的是在下面的例子中提出:

 class Game1 extends JFrame 
    { 
     public Game1() 
     { 
     // setSize(1000, 750); <---- do not do it 
     // setResizable(false); <----- do not do it either, unless any good reason 

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setTitle("Online First Person Shooter"); 

     ImageIcon image = new ImageIcon("C:\\Users\\Meneer\\Pictures\\image.png"); 
     JLabel label = new JLabel(image); 
     JScrollPane scrollPane = new JScrollPane(label); 
     scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 
     scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); 
     add(scrollPane, BorderLayout.CENTER); 
     pack(); 
     } 

    public static void main(String[] args) 
    { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new Game1().setVisible(true); 
      } 
     }); 

     } 
    } 
0

你的下一個問題你把你的JLabelGame1,但你顯示另一個畫面(Display f)。將add(imageLabel);更改爲Game1.f.add(imageLabel);

建議:根據你的問題

1):Game1延伸JFrame似乎Display也是一個幀中,僅使用一個框架中顯示的內容。

2)使用pack()方法,而不是setSize(1000, 750);

3)調用setVisible(true);在施工結束。 4)使用LayoutManager來佈局組件。