gpt4 book ai didi

java - 创建后绘制组件

转载 作者:行者123 更新时间:2023-11-30 07:58:06 24 4
gpt4 key购买 nike

为了用 Java 创建我的第一个 2D 游戏,我想到使用 JFramegetContentPane(),每 50 毫秒用新 View 更新一次。

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ...
frame.setVisible(true);
// ...
Container area = frame.getContentPane();
Graphics pen = area.getGraphics();
pen.clearRect(0, 0, area.getWidth(), area.getHeight()); // Remove previous drawing
pen.drawString("Text", 50, 50);
// ...
area.repaint();

但是这不起作用;窗口没有改变。

最佳答案

正如 kiheru 已经说过的,使用 paintComponent(Graphics g) 进行自定义绘制。这是一个例子:

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class Example {

int i = 0;

public Example() {

JFrame frame = new JFrame();

frame.getContentPane().add(new DrawingPanel());

frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

ActionListener actionListener = new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

frame.getContentPane().repaint();

}

};

Timer timer = new Timer(500, actionListener); //500 = Every 500 milliseconds
timer.start();

}

class DrawingPanel extends JPanel {

@Override
public void paintComponent(Graphics g) {

super.paintComponent(g); // Removes previous graphics

Random r = new Random(); //Randomizer

//Random x- and y-coordinates
int x = r.nextInt(400);
int y = r.nextInt(400);

//Random rgb-values
int red = r.nextInt(255);
int green = r.nextInt(255);
int blue = r.nextInt(255);

//Random width and height
int width = r.nextInt(100);
int height = r.nextInt(100);

g.setColor(new Color(red, green, blue)); //Setting color of the graphics

g.fillRect(x, y, width, height); //Filling a rectangle

}

}

public static void main(String[] args) {

new Example();

}

}

关于java - 创建后绘制组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32371429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com