2011-11-26 65 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