我想创建一个带有脸部绘图游戏的小程序,其中包含用于更改脸部各部分的按钮,但我不知道如何使用setVisible(false)
来制作例如当在paint方法块中声明它时,在操作侦听器内消失的椭圆。
//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!
}
}
答案 0 :(得分:1)
super.paint
paint
实际执行的操作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());
}
}
但是,如果您只是在说明,我会避免使用applet,他们会遇到一系列问题,如果您只是在学习,这会让生活变得困难