【问题标题】:How to make graphics disappear?如何让图形消失?
【发布时间】:2026-02-11 11:25:01
【问题描述】:

我想创建一个带有按钮的面部绘图游戏的小程序来更改面部的各个部分,但我不知道如何使用setVisible(false) 来制作例如当它在paint方法块中声明时,一个Oval会在动作监听器中消失。

//import necessary packages
public class applet1 extends Applet implements ActionListener
{
    Button b;
init()
{
    b=new Button("Oval face");
    b.addActionListener(this);
    add(b);
}
public void paint(Graphics g)
{
    g.drawOval(50,50,50,50);
}
public void actionPerformed(ActionEvent ae)
{
    g.setVisible(false); //I know this line cannot be executed but I jast want to show the idea!
}
}

【问题讨论】:

  • 1) 为什么要编写小程序?如果是老师指定的,请参考Why CS teachers should stop teaching Java applets。 2) 为什么使用 AWT?请参阅 this answer 了解放弃 AWT 使用支持 Swing 的组件的许多充分理由。
  • 是的,实际上这是一项任务,我完全同意,因为我正在学习 html 和 JavaScript,我发现与其他 PL 相比,applet 在创建基于 Web 的应用程序方面毫无用处。
  • 无论如何,谢谢!

标签: java graphics applet actionlistener paint


【解决方案1】:
  1. 在进行任何自定义绘画之前,请致电 super.paint
  2. 使用状态标志来更改 paint 的实际作用
  3. 考虑使用 Swing over AWT 并将核心应用程序包装在 JPanel 周围并将其添加到您的*容器中

也许更像...

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;

public class Content extends JPanel implements ActionListener {

    private JButton b;
    private boolean paintOval = false;

    public Content() {
        b = new JButton("Oval face");
        b.addActionListener(this);
        add(b);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
        if (paintOval) {
            g.drawOval(50, 50, 50, 50);
        }
    }

    public void actionPerformed(ActionEvent ae) {
        paintOval = false;
        repaint();
    }
}

然后将其添加到您的*容器...

public class Applet1 extends JApplet {
    public void init() {
        add(new Content());
    }
}

但如果你只是陈述,我会避免使用小程序,它们有自己的一系列问题,当你刚开始学习时可能会让生活变得困难

【讨论】:

  • 我会尝试这种方式。谢谢!