2014-09-06 63 views
-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()); 
} 

} 

我希望它寫座標控制檯上的光標。完成後,我會將其用於其他目的。

回答

1

打印座標到控制檯的唯一方法是getCor()方法。一旦你建立了框架,它只會在主要方法中調用一次。如果你想在每次改變時打印座標,那麼你應該......做到這一點:從你的鼠標監聽器方法打印corrdinates。

此外,請縮進您的代碼,併爲您的方法,變量和類選擇更好的名稱。 sa是很差的名字。 ButtonGrButtonGroup可讀性差得多。 getCorgetCoordinates

相關問題