Reputation: 15
I've got a problem that I'm trying to solve for hours, and I'd be glad if you could help me. My program is a kind of graph drawing program with Swing GUI. I've got a Draw2 class for drawing, overriding paintcomponent. There is a control class for the GUI. The control and drawing window are seperate JFrames-s. What I'm trying to do is to draw at button click but I've got problems with the communication between objects. I've tried to implement the drawing to button click with an if condition in the paintcomponent method, if the boolean is true the method should draw, if it's not it shouldn't. I'd change the boolen to true in the button's actionlistener and repaint the window. How can I reach the instance of Draw2 in the DrawAction method? Sorry if my question is very stupid but i've just begun learning Java. (I've seen a similar topic here but I didn't really understood the answer there) So the relevant part of my code:
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);
}
Thanks in advance
Upvotes: 1
Views: 755
Reputation: 5745
I would extend the createControl(frame)
so it would also take Draw2
as an argument:
createControl(frame, gp)
.
This new builder method would set an instance of Draw2
inside your Control
class.
public class Control extends JPanel
{
private JButton jButton1;
private JButton jButton2;
private Draw2 draw;
Upvotes: 2