Event-Driven Painting With Data Model
Hey all.
Studying computer science at the moment, however still a pretty weak programmer, prefer the math sides of things tbh. Currently I'm doing a project that involves Java2D and the visualisation of a data model (a Binary Tree). Note: I'm not asking anyone to write up the code for me, I just want to know whether I'm thinking along the right lines when concerned with paintComponent() and repaint(), I can easily "put" graphical objects on the screen with certain attritbutes, however I can't seem to get them onto the screen when I, say, click a button? I'm thinking that I've got the logic of the paint() method mixed up. :confused:
So I have "Main" class. Thats the JFrame and all the buttons and that jazz. This includes inner classes for the ActionListener Buttons.
Code:
class InsertListener implements ActionListener{
public void actionPerformed(ActionEvent event){
try{
String value = inputBox.getText();
Integer newValue = Integer.parseInt(value);
NumberList.add(newValue);
System.out.println("The value " + newValue + " was added to the list");
System.out.println("The List Contains: " + NumberList.toString());
}
catch(Exception e){}
repaint();
}
}
I have a "Canvas" class which extends JPanel so I can draw onto it with the paintComponent() method, the nodes of binary tree:
Code:
public class DrawingCanvas extends JPanel{
private static int xOrigin = 0;
private static int yOrigin = 0;
public DrawingCanvas(){
this.setPreferredSize(new Dimension (600,550));
}
public void paintComponent(){
//code to draw stuff in here;
}
}
However, since, the nodes need to have their own attributes, such as "value" of node (as a string), I was considering having a "seperate" class for the properties of this node (drawing a rectangle, having three attributes such as string [value] and xOrigin, yOrigin [to help "paint" onto the canvas]).
So in effect, I shift the paintComponent() method to the "node" class rather than the canvas class? So every time, I click that insert button, a node object is created of type GraphicsNode and is painted onto the canvas?
Is this the right logic for painting in java or am I going about it the wrong way?