我无法弄清楚为什么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());
}
}
我希望它在控制台上编写光标的坐标。完成后,我将把它用于其他目的。
答案 0 :(得分:1)
控制台唯一打印坐标的是getCor()
方法。一旦你构建了你的框架,它只会在主要方法中调用一次。如果你想在每次改变时打印坐标,那么你应该......这样做:从你的鼠标监听器方法打印corrdinates。
此外,请缩进您的代码,并为您的方法,变量和类选择更好的名称。 s
和a
是非常糟糕的名字。 ButtonGr
的可读性远低于ButtonGroup
。 getCor
的可读性远低于getCoordinates