【问题标题】:JPanel not showing up on JFrameJPanel 未显示在 JFrame 上
【发布时间】:2014-10-02 10:25:36
【问题描述】:

我正在尝试在 JPanel 上绘制一些填充的矩形并将该面板添加到 JFrame,但是当我运行程序时,我看到的只是 JFrame。我使用 frame.add(new RectanglePanel()); 添加了 JPanel,所以我不确定为什么面板没有出现。

框架类:

package h02;

import javax.swing.*;

// frame and its properties

public class RectangleFrame extends JFrame {

public RectangleFrame() {

    // JFrame object

    JFrame frame = new JFrame();

    // properties

    frame.setSize(300, 200);
    frame.setLocationRelativeTo(null); // frame in centre
    frame.setTitle("Drawing rectangles");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new RectanglePanel());
    frame.setVisible(true);

}


public static void main(String[] args) {
    new RectangleFrame();

    }

}

面板类:

package h02;

import javax.swing.*;
import java.awt.*;

public class RectanglePanel extends JPanel {

// drawing the rectangles

public void PaintComponent(Graphics g) {
    super.paintComponent(g);

    g.fillRect(110, 110, 20, 20);
    g.fillRect(10, 10, 30, 120);
    g.fillRect(60, 10, 60, 100);
    g.fillRect(150, 10, 10, 20);
    g.fillRect(240, 10, 10, 20);
    g.fillRect(190, 30, 80, 30);
    g.fillRect(210, 50, 60, 20);
    g.fillRect(190, 70, 80, 50);
    g.fillRect(300, 30, 50, 90);
    g.fillRect(330, 10, 30, 20);
    }

}

【问题讨论】:

  • 我不确定这是否能解决问题,但请尝试使用frame.add(panel, BorderLayout.CENTER) 添加面板。我认为您的面板目前没有正确调整大小,只有框架的内容窗格是(并且您没有在框架或框架的内容窗格上绘画)。您还可以使用 Dimension 设置首选大小,它会覆盖当前 LayoutManager 设置的大小。只是建议
  • 你在哪里设置矩形的颜色?添加“g.setColor(Color.RED);”给你paintComponent方法。如果您在构造函数中创建 JFrame,则不需要扩展 JFrame。
  • @VinceEmigh 我尝试使用 frame.add(panel, BorderLayout.CENTER) 但这并没有改变任何东西。我不确定如何使用维度,因为我以前从未使用过它,我必须查一下。
  • @Zyion Nowhere,fillRect 只是让矩形完全变黑对吗?
  • @Zyion 添加 g.setColor(Color.RED);也不会改变任何东西。

标签: java swing jframe jpanel awt


【解决方案1】:
public void PaintComponent(Graphics g) {

应该是

@Override
protected void paintComponent(Graphics g) {

【讨论】:

  • 是的,这是我的错误。这是我第一次这样做,所以 PaintComponent 没有给出错误的事实(或者应该它?它没有在 Eclipse 中)让我不怀疑它是否正确。
  • 1+ 到答案。 @Kristoffer:这就是为什么你应该总是在你的重写方法前面加上 @Override 注释,因为这样编译器标记你的错误。对于 wiskeyspider,方法签名应该是 protected 而不是 public。不需要让它比它必须的更明显。
  • 只有在方法上有@Override 注解时才会报错
  • @Kristoffer 这就是为什么你应该使用 Override 注释
  • @HovercraftFullOfEels(编辑:和其他人,但首先是充满鳗鱼的气垫船:P)感谢@Override 提示!
【解决方案2】:

为什么不直接使用诸如 Netbeans 提供的拖放编辑器而不是硬代码?

我发现它更有效率和效果。

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 2012-10-17
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多