2013-11-20 97 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来布局组件。