【问题标题】:Graphics not drawing to JFrame图形不绘制到 JFrame
【发布时间】:2018-03-19 05:31:51
【问题描述】:

我觉得我已经完成了我需要做的所有事情:

  • 创建一个图形类,它有一个名为paintComponent 的void 并扩展了JComponent
  • 让paintComponent void有Graphics g作为参数,然后做Graphics2D g2d = (Graphics2D) g;
  • 将 Graphics 类添加到我的 JFrame

我找不到任何问题,所以我有点困惑。
我的代码在这里:

public static void main(String[] args) {
    DragonEscape game = new DragonEscape();
    frame.setTitle(title);
    frame.setSize(1000, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.add(new Graphicsa());
    frame.add(game);
}

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JComponent;

public class Graphicsa extends JComponent {
    private static final long serialVersionUID = 1L;

    public Graphics g;

    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g.fillRect(0, 0, 1000, 500);
        g.setColor(Color.gray);
        g.fillRect(0, 0, 100, 100);
    }

}

【问题讨论】:

  • 有人会做点什么吗
  • (1-) 耐心等待!人们在有时间的时候回答问题。不能保证什么时候会。
  • @camickr 好的。我会

标签: java swing graphics jframe


【解决方案1】:
frame.add(new Graphicsa());
frame.add(game);

JFrame的BorderLayout的CENTER只能添加一个组件。所以你的游戏组件替换了图形组件。

阅读Swing tutorial 了解 Swing 基础知识。有以下部分:

  1. 如何使用BorderLayout
  2. 自定义绘画

与这个问题直接相关的。

另外,你为什么还要尝试绘制图形?如果在我看来您只是想将背景绘制成某种颜色。只需在您的游戏组件上使用setBackground(...) 方法即可。

【讨论】:

  • 谢谢你,我没有意识到这是一件事
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
  • 2011-09-08
  • 1970-01-01
  • 2012-02-23
相关资源
最近更新 更多