1

我正在制作一个创建和显示图表的程序。

我有一个处理图形并实现鼠标侦听器(Graphstream ViewerListener)的类。为了获取事件,您需要使用循环并调用 pump() 方法,直到完成。

为了显示图表,该Graphstream库有一个 View 对象,它可以扩展并可用作常规Jpanel,只需将 View 对象设置为JFrame.

JFrame与没有菜单栏的情况一起使用时,我的课程效果很好。

但是当我将 a 设置为JMenuBarJFrame,问题就开始了。我在我的图形类中调用该方法,它进入循环内部,但是ViewerListener不起作用,就像它没有在监听事件一样。为什么?

这是我的课程代码,省略了不必要的东西

public class GeneratedGraph implements ViewerListener{  

public String[] getNodes(){
    boolean flag=true;
    startEndNodes[0]=null; startEndNodes[1]=null;
    arrayposition=0;

    while(flag){
        System.out.println("Inside the loop");
        fromViewer.pump();
        try {
            Thread.sleep(250);
           } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(startEndNodes[0]!=null && startEndNodes[1]!=null){
            flag=false;
        }
    }
    System.out.println("Outside the loop");

    return startEndNodes;
}


public void buttonPushed(String id) {  //This method fires up when you click on a node
    System.out.println("Button pushed on node "+id);

    startEndNodes[arrayposition]=id;
    arrayposition++;

    if(arrayposition>1){ arrayposition=0;}
}
}

现在,从透视角度来看,这个 WORKS 进入,抓取节点,然后很好地退出循环。(不必要的代码再次省略)

public class main extends implements ActionListener {
public static void main(String args[]){

    JFrame mainFrame = new JFrame("Graph");
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    GeneratedGraph myGraph = new GeneratedGraph(mainFrame);
    myGraph.option1(5,6);  //a method which creates a graph
    myGraph.show();

    mainFrame.pack();
    mainFrame.setVisible(true);


    String s[] = myGraph.getNodes();

}
}

但是当我添加这个时,它没有。它只是进入循环和ViewerListener从未触发的事件中,所以它被卡住了。

public class main extends implements ActionListener {
public static void main(String args[]){

    JFrame mainFrame = new JFrame("Graph");
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JMenuBar menuBar= new JMenuBar();
    mainFrame.setJMenuBar(menuBar);

    JMenu algorithmMenu = new JMenu("Algorithms");
    JMenuItem dijkstra = new JMenuItem("Dijkstra");
    dijkstra.addActionListener(this);
    dijkstra.setActionCommand("Dijkstra");
    algorithmMenu.add(dijkstra);

    menuBar.add(algorithmMenu);


    GeneratedGraph myGraph = new GeneratedGraph(mainFrame);
    myGraph.option1(5,6);  //a method which creates a graph
    myGraph.show();

    mainFrame.pack();
    mainFrame.setVisible(true);


    String s[] = myGraph.getNodes();

}
}

似乎打破一切的部分是这个 menuBar.add(algorithmMenu); 当我注释掉这个特定的行时,它工作正常。

任何想法可能导致ViewerListener不响应?它看起来很随机,以至于 aJMenuBar会破坏它。

4

0 回答 0