simgui.java

来自「一个小型网络仿真器的实现」· Java 代码 · 共 1,854 行 · 第 1/5 页

JAVA
1,854
字号
          zoomTool=new SimDialog(mainFrame,"Zoom Tool",theSim,me()) {
              public void GUIChanged() {
                zoomSlider.setValue(calculateZoomSlide());
              }
            };
          zoomSlider=new JSlider(JSlider.HORIZONTAL,0,50,calculateZoomSlide());
          zoomSlider.addChangeListener(new ZoomListener());
          zoomSlider.setMinorTickSpacing(5);
          zoomSlider.setPaintTicks(true);
          java.util.Hashtable labelTable=new java.util.Hashtable();
          labelTable.put(new Integer(0),new JLabel("Out"));
          labelTable.put(new Integer(25),new JLabel("100%"));
          labelTable.put(new Integer(50),new JLabel("In"));
          zoomSlider.setLabelTable(labelTable);
          zoomSlider.setPaintLabels(true);

          zoomTool.GUIChanged(); //manually set its initial value
          zoomTool.getContentPane().add(zoomSlider);
          zoomTool.addWindowListener(new WindowAdapter() {
              public void windowClosed(WindowEvent e) {
                zoomTool=null;
                zoomSlider=null;
              }
            });
          zoomTool.pack();
          zoomTool.setResizable(false);

          Dimension ddim=zoomTool.getPreferredSize();
          Dimension sdim=Toolkit.getDefaultToolkit().getScreenSize();
          zoomTool.setLocation((sdim.width-ddim.width)/2,(sdim.height-ddim.height)/2);

          zoomTool.show();
        }
        else zoomTool.requestFocus();
      }
      else if(cmd.equals("New")) {
        if(!allowSimulation) return;
        if(!checkRunning()) return;

        if(JOptionPane.showConfirmDialog(mainFrame,
            "OK to clear everything?","Confirm New",
            JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION)
          return;

        doNew();
        mainFrame.repaint();
      }
      else if(cmd.equals("Start")) {
        if(!allowSimulation) return;
        startButton.setText("Pause");
        theSim.doStart();
      }
      else if(cmd.equals("Pause")) {
        if(!allowSimulation) return;
        startButton.setText("Resume");
        theSim.doPause();
      }
      else if(cmd.equals("Resume")) {
        if(!allowSimulation) return;
        startButton.setText("Pause");
        theSim.doResume();
      }
      else if(cmd.equals("Reset")) {
        if(!allowSimulation) return;
        startButton.setText("Start");
        theSim.doReset();
      }
      else if(cmd.equals("Memory Status...")) {
        if(!allowSimulation) return;

        String msg="";
        for(int i=0;i<5;i++) {
          System.gc();
          msg+="Run garbage collector...\n";
          msg+="Total Memory: "+(Runtime.getRuntime().totalMemory()/1024)+" Kbytes\n";
          msg+="Available Memory: "+(Runtime.getRuntime().freeMemory()/1024)+" Kbytes\n\n";
        }
        JOptionPane.showMessageDialog(mainFrame,msg,"Memory Status",JOptionPane.INFORMATION_MESSAGE);
        mainFrame.repaint();
      }
      else if(cmd.equals("About...")) {
        JOptionPane.showMessageDialog(mainFrame,Sim.SIM_NAME+" Version "+Sim.SIM_VERSION,
                                        "About",JOptionPane.INFORMATION_MESSAGE);
        mainFrame.repaint();
      }
      else if(cmd.equals("Quick Help...")) {
        String msg="Right-click on blank space to create new component.\n";
        msg+="Select component(s) by left-clicking/dragging.\n";
        msg+="Right-click on selected component(s) to access various commands\n";
        msg+="     which include properties, copy/paste/quick-paste.\n";
        msg+="Click the \"Connect Mode\" button to enter connect mode,\n";
        msg+="     where you can connect components by clicking each other.\n";
        msg+="E.g. Connect Application to BTE to Link To Switch and so on...\n";
        msg+="Remember to click \"End Connect\" or simply right-click to end\n";
        msg+="     the connect mode.\n";
        msg+="Use \"Fit All\" to create scroll bars if the topology exceeds\n";
        msg+="     the window size.\n";
        msg+="\nGood luck!";
        JOptionPane.showMessageDialog(mainFrame,msg,
                            "Quick Help",JOptionPane.INFORMATION_MESSAGE);
        mainFrame.repaint();
      }
      else if(cmd.equals("Exit")) {
        SimLog.close();
        System.exit(0);
      }
    }

    public void itemStateChanged(ItemEvent e) {
      Object src=e.getSource();

      if(src==fastScrollCB) {
        if(e.getStateChange()==ItemEvent.SELECTED) mainViewport.setScrollMode(JViewport.BLIT_SCROLL_MODE);
        else mainViewport.setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
      }
      else if(src==linktagCB) {
        if(e.getStateChange()==ItemEvent.SELECTED) linkTaggingDrag=true;
        else linkTaggingDrag=false;
      }
      else if(src==apptagCB) {
        if(e.getStateChange()==ItemEvent.SELECTED) appTaggingDrag=true;
        else appTaggingDrag=false;
      }
    }
  }

  private class ZoomListener implements ChangeListener {
    public void stateChanged(ChangeEvent e) {
      JSlider slider=(JSlider)e.getSource();
      int val=slider.getValue();
      if(val>25) {
        isZooming=true;
        zoomFactor=Math.pow(1.05,val-25);
        simArea.setZooming(zoomFactor);
        doFit();
      }
      else if(val<25) {
        isZooming=true;
        zoomFactor=Math.pow(0.95,25-val);
        simArea.setZooming(zoomFactor);
        doFit();
      }
      else {
        isZooming=false;
        zoomFactor=1.0;
        simArea.resetZooming();
        doFit();
      }
    }
  }

//helper class for "glocal set value" function
  private class GSDialogListener implements ActionListener {
    JDialog dialog=null;
    JComboBox cbParams=null;
    JTextField txtVal=null;
    JButton btnOKNext=null;
    JButton btnOK=null;
    JButton btnCancel=null;
    java.util.List sel=null; //selected components

    GSDialogListener(java.util.List theSel,String [] paramnames) {
      sel = theSel;

      dialog=new JDialog(mainFrame,"Global Set Value",true);
      dialog.getContentPane().setLayout(new GridLayout(3,1));
      JPanel aPanel=new JPanel();
      aPanel.add(new JLabel("Parameters:"));
      aPanel.add(cbParams=new JComboBox(paramnames));
      cbParams.setSelectedIndex(0);
      dialog.getContentPane().add(aPanel);
      aPanel=new JPanel();
      aPanel.add(new JLabel("Value:"));
      aPanel.add(txtVal=new JTextField(10));
      dialog.getContentPane().add(aPanel);
      aPanel=new JPanel();
      aPanel.add(btnOKNext=new JButton("OK & Next"));
      aPanel.add(btnOK=new JButton("OK"));
      aPanel.add(btnCancel=new JButton("Cancel"));
      dialog.getContentPane().add(aPanel);
      dialog.getRootPane().setDefaultButton(btnOKNext);
      btnOKNext.addActionListener(this);
      btnOK.addActionListener(this);
      btnCancel.addActionListener(this);

      dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
      dialog.pack();
      dialog.setResizable(false);

      dialog.addWindowListener(new WindowAdapter() {
          public void windowOpened(WindowEvent e) {
            txtVal.requestFocus();
          }
        });

      Dimension ddim=dialog.getPreferredSize();
      Dimension sdim=Toolkit.getDefaultToolkit().getScreenSize();
      dialog.setLocation((sdim.width-ddim.width)/2,(sdim.height-ddim.height)/2);
      dialog.show();
    }

    private void doOK() {
      String paramname=(String)cbParams.getSelectedItem();
      String val=txtVal.getText();
      int i,j;
      boolean failed=false;
      for(i=0;i<sel.size();i++) {
        SimComponent thisComp=(SimComponent)sel.get(i);
        SimParameter [] params=thisComp.getParameters();
        for(j=0;j<params.length;j++) {
          if(params[j].getName().equals(paramname)) {
            if(!params[j].globalSetValue(val)) failed=true;
            break;
          }
        }
      }
      if(failed) {
        JOptionPane.showMessageDialog(mainFrame,
          "At lest one parameter is not set.",
          "Info",JOptionPane.INFORMATION_MESSAGE);
      }
    }

    public void actionPerformed(ActionEvent e) {
      if(e.getSource() == btnOKNext) {
        if(!txtVal.getText().equals(""))
          doOK();
        if(cbParams.getSelectedIndex()<cbParams.getItemCount()-1)
          cbParams.setSelectedIndex(cbParams.getSelectedIndex()+1);
        txtVal.setText("");
      }
      else if(e.getSource() == btnOK) {
        doOK();
        dialog.dispose();
      }
      else  {
        dialog.dispose();
      }
    }
  }

  private class NewCompListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      //make sure simulation not running!
      if(!checkRunning()) return;

      String command=e.getActionCommand();

      //search for '.'
      int index=command.indexOf('.');
      if(index==-1) return; //must not be!!!
      String compClass=command.substring(0,index);
      String compType=command.substring(index+1);

      //obtain Java class name (fully qualified)
      String className=Sim.SIM_COMP_PACKAGE+"."+compType;

      //ask user for component name
      String newCompName;
      for(;;) {
        newCompName = JOptionPane.showInputDialog(mainFrame,
          "Component Name:","New Component ("+compClass+">"+compType+")",
          JOptionPane.QUESTION_MESSAGE);
        if(newCompName==null) return;

        newCompName = newCompName.trim();
        if(newCompName.length()<1) {
          JOptionPane.showMessageDialog(mainFrame,
            "Name cannot be blank!",
            "Error",JOptionPane.INFORMATION_MESSAGE);
          continue;
        }
        if(theSim.isCompNameDuplicate(newCompName)) {
          JOptionPane.showMessageDialog(mainFrame,
            "Duplicate component name, try another one...",
            "Error",JOptionPane.INFORMATION_MESSAGE);
          continue;
        }
        break;
      }

      //go!
      generateComponent(className,compClass,newCompName,lastActivate);
      mainFrame.repaint();
    }
  }

  SimGUI(Sim aSim) {
    theSim=aSim;

    mainFrame=new JFrame(Sim.SIM_NAME);

    cmdListener=new CommandListener();
    createMainMenu(cmdListener);
    createCompMenu(new NewCompListener());
    createPanels(cmdListener);

    openDialogs=new java.util.ArrayList();
    meterDialogs=new java.util.ArrayList();
    customDialogs=new java.util.ArrayList();

    Dimension scrsize=Toolkit.getDefaultToolkit().getScreenSize();
    mainFrame.setBounds(50,50,scrsize.width-100,scrsize.height-100);
    mainFrame.validate();
    mainFrame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          SimLog.close();
          System.exit(0);
        }
      });
    mainFrame.show();
  }


/////////////////////////////// helpers ///////////////////////////////////

  private SimGUI me() { return this; }

  private void doNew() {
    windowCloseAll();

    theSim.doNew();

    currentFile=null;
    mainFrame.setTitle(Sim.SIM_NAME);
  }

  private void doSaveAs() {
    if(fileChooser==null) {
      fileChooser=new JFileChooser(System.getProperty("user.dir"));
    }
    else {
      fileChooser.rescanCurrentDirectory();
    }
    if(fileChooser.showSaveDialog(mainFrame) != JFileChooser.APPROVE_OPTION) {
      mainFrame.repaint();
      return;
    }

    File theFile=fileChooser.getSelectedFile();
    if(theSim.saveSim(theFile)) {
      currentFile = theFile;
      mainFrame.setTitle(Sim.SIM_NAME+" - "+currentFile.getName());
    }
    else {
      JOptionPane.showMessageDialog(mainFrame,"Error saving to file "+theFile.getName(),
                                      "Error",JOptionPane.ERROR_MESSAGE);
      mainFrame.repaint();
    }
  }

  private int calculateZoomSlide() {
    int val=25;
    if(zoomFactor>1.0) {
      val=(int)(Math.log(zoomFactor)/Math.log(1.05) + 25);
      if(val>50) val=50;
    }
    else if(zoomFactor<1.0) {
      val=(int)(25 - Math.log(zoomFactor)/Math.log(0.95));
      if(val<0) val=0;
    }
    return val;
  }

  private void windowCloseAll() {
    java.util.ListIterator iter=openDialogs.listIterator();
    while(iter.hasNext()) {
      JDialog dialog=(JDialog)iter.next();
      dialog.dispose();
      iter.remove();

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?