日期:2014-05-20  浏览次数:20759 次

求助:关于鼠标事件的问题?
先看下代码,我想实现的就是,利用鼠标事件,当选择其中一个矩形框的时候,使得矩形框变成红色,并且把其对应的内容给显示出来,其中关于内容的显示部分已经完成,就是下面代码.关于当选择一个矩形框的时候使得矩形眶变成红色,我做不好,关于绘制部分很不熟悉,请各位帮忙.谢谢了!
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseAdapter;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class RectChoose extends JFrame {
private static final long serialVersionUID = 1L;
int[] a = { 100, 200, 300 ,99};
int[] b = { 50, 150, 250 ,49};
int[] c = { 50, 50, 50 ,80};
int[] d = { 50, 50, 50 ,80};
String[] str = { "显示第一个", "显示第二个", "显示第三个" ,"显示第四个"};
JPanel jp = new MyJPanel();
final JTextField jt = new JTextField();
 
public static void main(String[] args) {
new RectChoose();
}
 
public RectChoose(){
add(jp, BorderLayout.CENTER);
add(jt, BorderLayout.NORTH);
jp.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
int x=e.getX();
int y=e.getY();
ArrayList list = new ArrayList();
int k=0;
for(int i=0;i<4;i++){
if(x>=a[i]&&x<=(a[i]+c[i])&&y>=b[i]&&y<=(b[i]+d[i])){
list.add(i);
Integer[] nums = (Integer[]) list.toArray(new Integer[0]);
k++;
if(k==1)
jt.setText(str[i]);
else if(k==2){
int a1=nums[0];
int a2=nums[1];
if((a[a1]+c[a1])<(a[a2]+c[a2]))
jt.setText(str[a1]);
else
jt.setText(str[a2]);
}
}
}
}
 
});
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
 
class MyJPanel extends JPanel{
public void paint(Graphics g) {
for(int i=0;i<4;i++){
g.drawRect(a[i], b[i], c[i], d[i]);
}
}
}
}


------解决方案--------------------
给你改好了,试试吧。
另外建议楼主用J2D对象绘制矩形,不然代码太乱。
Java code
 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class RectChoose extends JFrame {
private static final long serialVersionUID = 5616139155213961945L;
private int chooseIndex;
int[] a = { 100, 200, 300, 99 };
int[] b = { 50, 150, 250, 49 };
int[] c = { 50, 50, 50, 80 };
int[] d = { 50, 50, 50, 80 };
String[] str = { "显示第一个", "显示第二个", "显示第三个", "显示第四个" };
JPanel jp = new MyJPanel();
final JTextField jt = new JTextField();

public static void main(String[] args) {
new RectChoose();
}

public RectChoose() {
add(jp, BorderLayout.CENTER);
add(jt, BorderLayout.NORTH);
jp.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
ArrayList <Integer> list = new ArrayList <Integer>();