尝试使用JFrame和JPanel绘制窗口黑色

时间:2014-05-07 11:47:55

标签: java swing jframe jpanel paint

我制作了一个JFrame,并为其添加了一个JPanel。我试图将窗户漆成黑色,但它不起作用!提前谢谢。

这是我的主要课程!

package com.lootdatdungeon.net;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;

public class Main {

public static void main(String[] args){

    initWindow();

}

public static void initWindow(){

    Window window = new Window();
    Thread windowThread = new Thread(window);
    windowThread.start();

}

}

好的,这是我的Window类!

package com.lootdatdungeon.net;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Window extends JFrame implements Runnable{

private static final long serialVersionUID = 1L;
private static final int HEIGHT = 240;
private static final int WIDTH = 320;
private static final int SCALE = 2;

private BufferedImage image;
private Graphics2D g;

private boolean running = true;

public Window(){

    System.out.println("Window object made");

    JFrame frame = new JFrame("Loot dat dungeon");
    JPanel panel = new JPanel();

    frame.setSize(WIDTH*SCALE,HEIGHT*SCALE);
    frame.setVisible(true);
    frame.setResizable(false);
    frame.add(panel);

    image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
    g = (Graphics2D) image.getGraphics();

}

public void Draw(Graphics g){

    System.out.println("Draw method ran");
    g.setColor(Color.BLACK);
    g.drawRect(0, 0, WIDTH, HEIGHT);


}

@Override
public void run() {
    while(running){
    Draw(g);
    }
}

}

2 个答案:

答案 0 :(得分:1)

使用paintComponent()

的overriiden JPanel方法,只需这样做
JPanel panel = new JPanel() {
    @Override
    public void paintComponent(Graphics g) {
        // don't forget to call it
        super.paintComponent(g);
        // set color
        g.setColor(Color.BLACK);
        // fill a rect that cover whole panel with specified color
        g.fillRect(0, 0, getWidth(), getHeight());
    }
};

注意:在这种情况下不需要Thread和BufferedImage。

答案 1 :(得分:0)

您应该阅读http://www.gametutorial.net/article/Java-game-framework

如果你想创建游戏,该网站有很多好消息。那是我开始的。