如果在Rectangle startButton中单击鼠标,我的代码设置为布尔boxDetect将设置为true的位置。其余的只是格式化没什么特别的!这是在按下矩形之前的初始屏幕,一旦进入矩形并按下它,它应该将屏幕重新绘制为400,400点的矩形。
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
public class spaceInvadersIntroScreen implements MouseListener
{
private JFrame frame;
private MyPanel panel;
private double startButtonX = 0;
private double startButtonY = 0;
private Rectangle startButton;
private Boolean boxDetect = false;
public static void main(String[] args){ new spaceInvadersIntroScreen(); }
public spaceInvadersIntroScreen()
{
frame = new JFrame("Space Invaders");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
startButtonX = screenSize.getWidth() / 2; //Finds the X value of the center of the screen
startButtonY = screenSize.getHeight() / 2; //Finds the Y value of the center of the screen
frame.setSize(screenSize); //width and height
panel = new MyPanel();
frame.getContentPane().add(panel);
frame.setVisible(true);
startButton = new Rectangle((int)(startButtonX - 200), (int)(startButtonY - 75), 400, 150); //Creates Rectangle in the middle of the screen
}
class MyPanel extends JPanel
{
private static final long serialVersionUID = 1L;
public void paint(Graphics g)
{
if(boxDetect == false)
{
Graphics2D g2d = (Graphics2D) g;
//Background
g2d.setColor(Color.BLACK);
g2d.fillRect(0,0, 1440, 870);
//Code for an X centered title regardless of the screen length
String title = "SPACE INVADERS";
Font textFont = new Font("monospaced", Font.BOLD, 150);
FontMetrics textMetrics = g2d.getFontMetrics(textFont);
g2d.setFont(textFont);
int centeredX = (this.getWidth()/2) - (textMetrics.stringWidth(title)/2);
//Prints SPACE INVADERS to the screen
g2d.setColor(Color.WHITE);
g2d.setFont(textFont);
g2d.drawString(title, centeredX, 200);
//draw the Button
g2d.setColor(Color.white);
g2d.fill(startButton);
}
else
{
g.setColor(Color.black);
g.drawRect(400, 400, 400, 400);
}
}
}
@Override
public void mouseReleased(MouseEvent e)
{
double xCoord = e.getX();
double yCoord = e.getY();
if(startButton.contains(xCoord,yCoord) == true)
{
boxDetect = true;
}
panel.repaint();
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
}
答案 0 :(得分:1)
您需要 添加 MouseListener才能正常工作。问题:你在哪里打addMouseListener(...)
?答:你没有。解决方案:调用此方法将MouseListener添加到需要它的组件中。