gpt4 book ai didi

java - Java 小程序的 "Graphics g"中的 "paint()"的值是多少?

转载 作者:行者123 更新时间:2023-11-29 07:06:04 25 4
gpt4 key购买 nike

在制作 Java 小程序方面,我是初学者,在我的第一个小程序中,我使用 paint() 绘制了一个笑脸。现在,我想让笑脸眨眼。我已经设法让我的计时器和一切都设置好了,但我需要使用 start() 方法来让计时器运行,而且似乎通过包含其他方法,paint 方法不会调用自身。因此,我假设我需要从 start() 调用 paint(),但问题是我不知道我应该将 Graphics 变量初始化为什么以使 paint() 实际工作。

中南合作商会

import java.awt.*;
import javax.swing.*;
import java.applet.Applet;
import java.awt.event.*;

public class Project2_15 extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.lightGray);
}

// This handles the starting of timer execution.
public void start()
{
Graphics g; // What do I initialize this to?
paint(g);
}

// Timer Stuff
ActionListener blinkShut;
public Project2_15(final Graphics g) {
this.blinkShut = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
g.setColor(Color.black);
}
};
}
}

最佳答案

修改后的代码如下:

import java.awt.*;
import javax.swing.*;
import java.applet.Applet;
import java.awt.event.*;

public class Project2_15 extends Applet
{

public boolean wink = false;
Timer timer;

public void paint(Graphics g)
{
super.paint(g);
// Graphics g; // What do I initialize this to? ALREADY INITIALIZED
//paint(g);
if (wink) {
g.drawLine(1,1,100,100);
} else {
g.drawOval(1,1,100,100);
}
}

// This handles the starting of timer execution. NO IT DOES NOT!
// public void start()
@Override
public void init()
{
setBackground(Color.lightGray);
timer = new Timer(250,blinkShut);
}


@Override
public void start() {
timer.start();
}

@Override
public void stop() {
timer.stop();
}
// Timer Stuff
ActionListener blinkShut = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
wink = !wink;
repaint();
}
};
}

参见 Performing Custom Painting .这与小程序或框架的基本过程相同。

  1. 将容器 (Panel/JPanel) 添加到顶级容器。
  2. 重写 paint(..) AWT 或 paintComponent(..) Swing 方法。
  3. 调用 super.. 作为第一条语句。
  4. 对提供的 Graphics 实例进行自定义绘画。

动画可以使用基于 Swing 的定时器来实现。

当然,我倾向于将步骤 1) 到 4) 替换为绘制到 JLabel/ImageIcon 中显示的 BufferedImage

关于java - Java 小程序的 "Graphics g"中的 "paint()"的值是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19613449/

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