-1
我找不出爲什麼MouseListener沒有響應。我有三個類 -MouseListener沒有按預期的方式響應
ButtonGr.java:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonGr extends JPanel implements ActionListener{
private String s;
public ButtonGr(){
JRadioButton line=new JRadioButton("line");
line.setActionCommand("line");
line.setSelected(true);
JRadioButton rectangle=new JRadioButton("rectangle");
rectangle.setActionCommand("rectangle");
JRadioButton ellipse=new JRadioButton("ellipse");
ellipse.setActionCommand("ellipse");
JRadioButton circle=new JRadioButton("circle");
circle.setActionCommand("circle");
ButtonGroup g=new ButtonGroup();
g.add(line);
g.add(rectangle);
g.add(ellipse);
g.add(circle);
add(line);
add(rectangle);
add(ellipse);
add(circle);
line.addActionListener(this);
rectangle.addActionListener(this);
ellipse.addActionListener(this);
circle.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
s=e.getActionCommand();
}
public String getSou(){
return s;
}
}
MouseEven.java:
import java.awt.event.*;
public class MouseEven implements MouseListener{
private String s;
private static int a;
public void mouseClicked(MouseEvent e){
s=e.getX()+" "+e.getY();
countEvent(e);
}
public void mousePressed(MouseEvent e){
s=e.getX()+" "+e.getY();
countEvent(e);
}
public void mouseReleased(MouseEvent e){
s=e.getX()+" "+e.getY();
countEvent(e);
}
public void mouseEntered(MouseEvent e){
s=e.getX()+" "+e.getY();
countEvent(e);
}
public void mouseExited(MouseEvent e){
s=e.getX()+" "+e.getY();
countEvent(e);
}
private void countEvent(MouseEvent e){
a++;
}
public String getCor(){
System.out.println(s);
return s;
}
public int getCount(){
System.out.println(a);
return a;
}
}
Tester.java:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Tester{
public static void main(String[] args){
JFrame f=new JFrame();
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
Container c=f.getContentPane();
ButtonGr bg=new ButtonGr();
c.add(bg,BorderLayout.PAGE_START);
JPanel p=new JPanel();
p.setBackground(new Color(250,250,250));
JLabel l=new JLabel("view");
p.add(l);
MouseEven me=new MouseEven();
p.addMouseListener(me);
c.add(p,BorderLayout.CENTER);
f.setSize(600,500);
f.setVisible(true);
System.out.println(me.getCor());
System.out.println(me.getCount());
}
}
我希望它寫座標控制檯上的光標。完成後,我會將其用於其他目的。