JFrame和JPanel的不同背景颜色

时间:2015-12-15 07:57:32

标签: java swing

我想在JFrame上绘制JPanel。 JFrame的背景颜色对于JPanel是不同的。到目前为止,这是我的代码:

    Camera.PictureCallback mPicture = new Camera.PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        File pictureFile = getOutputMediaFile();

        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
        }
    }

};

当我运行代码时,颜色为红色。黄色(JFrame)上不是红色(JPanel)。怎么解决?

1 个答案:

答案 0 :(得分:-1)

您的问题是JPanelJFrame的尺寸相同。原因由Arvind解释。

以下代码段会将JPanel分配到North区域,并在其周围添加一个粗蓝色边框以供演示。

public void showFrame() {
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setPreferredSize(new Dimension(500, 500));
    this.getContentPane().setBackground(Color.yellow);
    JPanel p = new JPanel();
    p.setPreferredSize(new Dimension(400, 400));
    p.setBackground(Color.red);
    Border border = BorderFactory.createLineBorder(Color.blue, 10);
    border.isBorderOpaque();
    p.setBorder(border);
    this.add(p, BorderLayout.NORTH);
    this.pack();
    this.setVisible(true);
}

public static void main(String[] args) {
    new DifferentColor().showFrame();
}

还可以查看Swing tutorial about use of panels