使用MouseListener绘制加权树

时间:2013-10-21 22:08:55

标签: java swing jpanel paintcomponent mouselistener

我是Java新手。我正在尝试使用GUI输入和显示加权二叉树。要创建根节点,用户单击屏幕。随后,他从一个点拖动到另一个点以创建边缘和新节点。一旦他释放鼠标,他应该被提示输入重量,然后边缘(显示重量)和新节点应该显示。

在输入中,虽然我能够创建根,但当我尝试拖动以创建下一个节点时,程序进入循环。

代码如下。

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);
}
}

1 个答案:

答案 0 :(得分:2)

Swing中的绘画可能因任何原因随时发生。正如@HoverCraftFullOfEels已经指出的那样,你应该在任何paint方法中没有应用程序,这些应该只包含绘制组件所需的功能。

首先查看Performing Custom PaintingPainting in AWT and Swing,了解有关paint子系统的更多详细信息

基本上,在paintComponent内,请先调用super.paintComponent,然后删除else阻止。

让自己成为某种模型,它包含所需的数据,然后使用paintComponent方法绘制该模型。