JComponent没有在JPanel中绘图

时间:2016-05-26 16:41:57

标签: java swing

Swing普通客户的简单问题。

想法是加载图像并通过JComponent对象将其用作JPanel的背景。它似乎加载得很好,因为来自src方法的图像信息正在正确加载并且toString()方法正在运行,但由于某种原因,它无法在JFrame内正确呈现,从而导致空帧。这是代码:

RicochetFrame.java

paintComponent()

RicochetStartPanel.java

public class RicochetFrame extends JFrame {
  RicochetStartPanel startPanel;

  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                RicochetFrame window = new RicochetFrame();
                window.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
   }

  public RicochetFrame() throws IOException {
    startPanel = new RicochetStartPanel();

    this.getContentPane().add(startPanel);

    this.setBounds(0, 0, 500, 500);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //this.pack();
    this.setVisible(true);
  }

}

RicochetImagePanel.Java

public class RicochetStartPanel extends JPanel {
  RicochetStartPanel() throws IOException {
    BufferedImage myImage = ImageIO.read(new File("frame_bg.jpg"));
    this.add(new RicochetImagePanel(myImage));

    this.setVisible(true);

    this.validate();
    this.repaint();
  }

}

1 个答案:

答案 0 :(得分:2)

您的response正在调整其首选尺寸=> [0,0]。覆盖其RicochetImagePanel以返回图像的尺寸(如果不为null)。更好的是,为什么不简单地在JLabel中将图像显示为ImageIcon?