【发布时间】:2014-03-12 18:55:11
【问题描述】:
public class TesterApplication {
static JPanel CenterPanel;
public static void main(String[] args){
/* get image MapImg */
JFrame frame=new JFrame();
CenterPanel = new JPanel(){
@Override
protected void paintComponent(Graphics g){
g.drawImage(MapImg, 0, 0, null);
}
};
CenterPanel.addMouseListener(new LineBuildListener(new TesterApplication()));
frame.getContentPane().add(BorderLayout.CENTER, CenterPanel);
frame.setSize(x, y);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
现在是内部类
class LineBuildListener implements MouseListener {
TesterApplication TA;
int xFirstClick;
int yFirstClick;
int ClickCounter=0;
int xClick;
int yClick;
LineBuildListener(TesterApplication TA){
this.TA=TA;
}
@Override
public void mouseClicked(MouseEvent e) {
xFirstClick=xClick;
yFirstClick=yClick;
xClick=e.getX();
yClick=e.getY();
TA.CenterPanel.getGraphics().fillOval(xClick, yClick, 10, 10);
if(ClickCounter!=0){
SecondClick();
ClickCounter++;
}else{
ClickCounter++;
}
System.out.println(ClickCounter);
}
public void SecondClick(){
TA.CenterPanel.getGraphics().drawLine(xClick, yClick, xFirstClick,yFirstClick);
}
}
同时我第一次单击时,我的 GUI 闪烁,单击计数器打印我已经单击了 1 次,但我没有得到我的第一个圆圈。如果我继续点击一切正常,它会打印下一个圆圈,增加计数器并在它们之间画线,所以我不明白为什么第一个圆圈丢失了
【问题讨论】:
-
你为什么要传入一个新的 TesterApplication 到你的鼠标监听器中?然后,您将拥有它的两个实例。在 TesterApplication 的主要方法中,将“new TesterApplication()”更改为“this”。
-
我收到错误“无法从静态上下文引用的非静态变量”