2017-02-24 66 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