I'm new at Java. I'm trying to use GUI to input and display a weighted binary tree. To create root node, user clicks on screen. Subsequently, he drags from one point to another to create an edge and a new node. Once he releases the mouse, he should be prompted to enter the weight, and then edge (with weight displayed) and new node should be displayed.
In the input, while I'm able to create the root, when I try to drag to create the next node, the program goes into a loop.
Code is given below.
class myPanel extends JPanel implements MouseListener, MouseMotionListener
{
int node_is_present[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; //1 if node exists, 0 otherwise
int no_of_nodes=0;
int node_coords[][]=new int[15][2]; //stores co-ordinates of each node
int weight[]=new int[15]; //stores weight of line in the order entered
int x1,x2,y1,y2;
int tracker=-1;
int SIZE=20;
public void clear()
{
x1=0;
y1=0;
x2=0;
y2=0;
}
@Override
public void mouseClicked(MouseEvent me) {}
@Override
public void mousePressed(MouseEvent me) //will store intial x,y
{
tracker=1;
x1=me.getX();
y1=me.getY();
repaint();
}
@Override
public void mouseReleased(MouseEvent me) //will store final x,y and update arrays
{
x2=me.getX();
y2=me.getY();
if(x1!=x2)
tracker=2;
node_is_present[no_of_nodes]=1;
node_coords[no_of_nodes][0]=me.getX();
node_coords[no_of_nodes][1]=me.getY();
no_of_nodes++;
repaint();
}
@Override
public void mouseEntered(MouseEvent me){}
@Override
public void mouseExited(MouseEvent me) {}
@Override
public void mouseDragged(MouseEvent me){}
@Override
public void mouseMoved(MouseEvent me) {}
public void paintComponent(Graphics g)
{
if(tracker==1 && no_of_nodes==0) //for root node
{
g.drawOval(x1-(SIZE/2),y1-(SIZE/2),SIZE,SIZE);
g.drawString(String.valueOf(no_of_nodes+1),x1-(SIZE/2),y1-(SIZE/2));
}
else if(tracker==2 && no_of_nodes>0)
{
g.drawLine(x1 -(SIZE/2) , y1 -(SIZE/2) , x2 -(SIZE/2) , y2 -(SIZE/2));
g.drawOval(x2-(SIZE/2),y2-(SIZE/2),SIZE,SIZE);
g.drawString(String.valueOf(no_of_nodes+1),x2-(SIZE/2),y2-(SIZE/2));
String str=JOptionPane.showInputDialog("Enter the weight of the edge: ");
int w=Integer.parseInt(str);
weight[no_of_nodes-1]=w;
g.drawString(String.valueOf(w),Math.round((x1+x2)/2),Math.round((y1+y2)/2));
clear();
}
}
myPanel()
{
this.setSize(1500, 500);
addMouseListener(this);
addMouseMotionListener(this);
clear();
}
}
public class tree1
{
public static void main(String[] args) {
JFrame frame=new JFrame();
myPanel panel=new myPanel();
frame.setSize(1500, 800);
frame.setLocation(0, 0);
frame.setTitle("Tree");
frame.setBounds(100,100,1500,800);
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}