我不知道为什么,但是什么也没出现?
我想有一个小房子。
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.*;
public class color extends JApplet
{
public void init()
{
addMouseListener(new MyMouseListener());
getContentPane().setBackground(Color.white);
}
public class MyMouseListener implements MouseListener
{
public void mouseClicked(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
boolean closeDoors = true;
if(x>330 && x<280 && y>20 && y<20)
{
closeDoors = false;
repaint();
}
}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
}
public void paint ( Graphics g, boolean closeDoors)
{
super.paint (g);
do
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
}
while (closeDoors = true);
if (closeDoors = false);
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawLine (180, 120, 100, 120);
g.drawLine (400, 120, 480, 120);
g.drawLine (140, 75, 140, 160);
g.drawLine (450, 75, 450, 160);
g.drawRect (50, 50, 500, 350);
g.drawRect (100, 75, 80, 80);
g.drawRect (400, 75, 80, 80);
g.drawRect (240, 200, 125, 200);
g.drawOval (330,280, 20, 20);
}
}
}
最佳答案
我会尽力帮助您步入正轨:-)
您可能已经知道这一点,但是如果您不使用IDE,建议您使用appletviewer来开发小程序,而不要使用浏览器。只是值得深思的:-)
首先,Toader Mihai Claudiu的建议是正确的。更改
do
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
}
while (closeDoors = true);
if (closeDoors = false);
{
进入
if (closeDoors)
{
g.drawLine (35, 50, 570, 50);
g.drawLine (35, 50, 250, 0);
g.drawLine (250, 0, 570, 50);
g.drawRect (50, 50, 500, 350);
g.fillRect (100, 75, 80, 80);
g.fillRect (400, 75, 80, 80);
g.fillRect (240, 200, 125, 200);
}
else
{
否则,只要closeDoors为true,就将进行绘画。您只需要油漆一次。 Java会要求您在必要时再次绘制(例如,当您调用repaint()时)。
另外,将
closeDoors
设置为成员变量。换句话说,具有:public class color extends JApplet
{
public boolean closeDoors = false;
而且,当您在点击侦听器中切换closeDoors的值时,可以将其简化为:
int x = e.getX();
int y = e.getY();
if(x>330 && x<280 && y>20 && y<20)
{
closeDoors = !closeDoors;
repaint();
}
当您单击特定区域时,这将反转closeDoors的值。换句话说,如果
closeDoors
是true
,它将被设置为false
,反之亦然。请注意,您的代码
if(x>330 && x<280 && y>20 && y<20)
可能根本无法工作,因为y
永远不能同时大于20和小于20。我将让您使用它来找出有效的方法:-)。希望这可以帮助。
只是一个小细节,但是您可能应该调用类
Color
而不是color
来遵循Java的standard naming convention,或者如果您不想与java.awt.Color冲突,则可以使用其他名称。