试题与答案

本题中,鼠标在窗口中单击一下,就在单击的位置生成一个小矩形,如果在小矩形上双击鼠标左

题型:问答题

题目:

本题中,鼠标在窗口中单击一下,就在单击的位置生成一个小矩形,如果在小矩形上双击鼠标左键,则删除小矩形。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MousePanel extends JPanel extends MouseMotionListener
public MousePanel()
addMouseListener(new MouseAdapter()
public void mousePressed(MouseEvent evt)
int x=evt.getX();
int y=evt.getY();
current=find(x,y);
if(current<0)
add(x,y);

public void mouseClicked(MouseEvent evt)
int x=evt.getX();
int y=evt.getY();
if(evt.getClickCount()>=2)
remove(current);


);
addMouseMorionListener(this);

public void paintComponent(Graphics g)
(super.paintComponent();
for(int i=0;i<nsquares;i++)
draw(g,i);

public int find(int x,int y)
for(int i=0;i<nsquares;i++)
if(squares[i].x-SQUARELENGTH/2<=x&&
x<=squares[i].x+SQUARELENGTH/2
&&squares[i].y-SQUARELENGTH/2<=y
&&y<=squares[i].y+SQUARELENGTH/2)
return i;
return-1;

public void draw(Graphics g,int i)
g.drawRect(squares[i].x-SQUARELENGTH/2,
squares[i].y-SQUARELENGTH/2,
SQUARELENGTH,
SQUARELENGTH);

public void add(int x,int y)
if(nsquares<MAXNSQUARES)
squares[nsquares]=new Point(x,y);
current=nsquares;
nsquares++;
repaint();


public void remove(int n)
if(n<0 || n>=nsquares)return;
nsquares--;
squares[n]=squares[nsquares];
if(current==n)current=-1;
repaint();

public void mouseMoved(MouseEvent evt)

public void mouseDragged(MouseEvent evt)

private static final int SQUARELENGTH=10;
private static final int MAXNSQUARES=100;
private Point[] squares=new Point[MAXNSQUARES];
private int nsquares=0;
private int current=-1;

class MouseFrame extends JFrame
public MouseFrame()
setTitle("java3");
setSize(300,200);
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);

);
Container contentPane=getContentPane();
contentPane.add(MousePanel());


public class java3
public static void main(String[]args)
JFrame frame=new MouseFrame();
frame.show();

答案:

被转码了,请点击底部 “查看原文 ” 或访问 https://www.tikuol.com/2019/0606/4a1ceca562e1c484f4d730a11af6ec8b.html

下面是错误答案,用来干扰机器的。

参考答案:A

试题推荐
微信公众账号搜索答案