2011-11-26 69 views
1

我有一个问题,我试图解决几个小时,如果你能帮助我,我会很高兴。我的程序是一种使用Swing GUI的图形绘制程序。 我有一个绘图的Draw2类,覆盖paintcomponent。有一个GUI的控制类。控制和绘图窗口是单独的JFrames-s。我试图做的是画按钮点击,但我有对象之间的沟通问题。 我试图实现绘图到按钮点击与paintcomponent方法中的if条件,如果布尔值为true,该方法应该绘制,如果它不应该绘制。我会在按钮的actionlistener中将boolen更改为true并重新绘制窗口。如何在DrawAction方法中到达Draw2的实例?对不起,如果我的问题很愚蠢,但我刚开始学习Java。 (我在这里看到了类似的话题,但我真的不明白答案了)所以我的代码的相关部分:绘图按钮点击

public class Draw2 extends JPanel{ 
    boolean toDraw; 

public void paintComponent (Graphics g) { 
    super.paintComponent(g); 
    if (toDraw == true){ 
     //Draw Graph 
    } 
} 

}

public class Control extends JPanel{ 
private JButton jButton1; 
private JButton jButton2; 

void createControl(){ 
    JButton1 = new JButton("Draw"); 
    jButton1.addActionListener(new DrawAction()); 

    //Other JTextfields, JComboBoxes, etc. with groupLayout 
} 

//inner class: 
public class DrawAction implements ActionListener{ 
    public void actionPerformed(ActionEvent arg0) { 
     //How should I change toDraw in the instance of Draw2 
     //repaint the "canvas"   
    } 
} 

}

public static void main(String[] args){ 

    JFrame frame = new JFrame("Control"); 
    JFrame frame2 = new JFrame("Draw"); 


    Draw2 gp = new Draw2(); 
    control cont = new control(); 
    cont.createControl(frame); 



    gp.setPreferredSize(new Dimension(0,0)); 

    //Control Frame 
    frame.setSize(800,330); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.add(cont, BorderLayout.NORTH); 
    frame.setVisible(true); 

    //Drawing Frame 
    frame2.setSize(800,600); 
    frame2.setLocation(0, 330); 
    frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    frame2.add(gp); 
    frame2.setVisible(true);   
} 

在此先感谢

+0

如需更快获得更好的帮助,请发布[SSCCE](http://sscce.org/)。 –

回答

2

我会延长createControl(frame)所以它也将需要Draw2作为参数:

createControl(frame, gp)

这个新的构建器方法将在您的Control类中设置一个Draw2的实例。

public class Control extends JPanel 
{ 
    private JButton jButton1; 
    private JButton jButton2; 
    private Draw2 draw; 
+0

非常感谢,它解决了我的问题 – user1067279