我想向矩形添加鼠标侦听器,以便当用户单击一个矩形并将鼠标拖动到下一个矩形时,会绘制一条线来跟踪用户的移动,并且用户所在的当前矩形必须更改颜色。我是java新手,因此您的帮助将不胜感激。
import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
public class SundayPanel extends JPanel implements MouseListener{
private Rectangle rec;
private JPanel p = new JPanel();
private Graphics graphic;
public SundayPanel()
{
setSize(1000, 150);
setBackground(Color.white);
setBorder(BorderFactory.createEtchedBorder(Color.orange, Color.red));
rec = new Rectangle(0, 0, 130, 100);
}
public void paint(Graphics g)
{
Font font = new Font("Times New Roman", Font.PLAIN, 72);
g.setFont(font);
g.setColor(Color.black);
//g.draw(rec);
g.draw3DRect(0, 0, 130, 100, true);
g.drawString("1", 50, 65);
g.draw3DRect(130, 0, 130, 100, true);
g.drawString("2", 180, 65);
g.draw3DRect(260, 0, 130, 100, true);
g.drawString("3", 300, 65);
g.draw3DRect(390, 0, 130, 100, true);
g.drawString("4", 430, 65);
g.draw3DRect(520, 0, 130, 100, true);
g.drawString("5", 550, 65);
g.draw3DRect(650, 0, 130, 100, true);
g.drawString("6", 700, 65);
g.draw3DRect(780, 0, 130, 100, true);
g.drawString("7", 820, 65);
g.draw3DRect(910, 0, 130, 100, true);
g.drawString("8", 950, 65);
g.draw3DRect(1040, 0, 130, 100, true);
g.drawString("9", 1080, 65);
g.draw3DRect(1170, 0, 130, 100, true);
g.drawString("10", 1200, 65);
}
}
import javax.swing.JFrame;
public class SundayMain extends JFrame{
/**
* @param args
*/
public static void main(String[] args) {
JFrame sunFrame = new SundayFrame("Sunday Today");
sunFrame.setVisible(true);
sunFrame.setSize(1330, 150);
sunFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class SundayFrame extends JFrame{
private SundayPanel sunPanel;
public SundayFrame(String title)
{
super(title);
sunPanel = new SundayPanel();
add(sunPanel, BorderLayout.CENTER);
}
}