accessing variables and swing components through different threads

前端 未结 3 1251
时光取名叫无心
时光取名叫无心 2020-12-07 02:43

This question is related somewhat to the one i asked HERE. Now, i have a class "Controller" which consists of the main method and all the swing components. there i

3条回答
  •  青春惊慌失措
    2020-12-07 03:22

    A third approach would be to have your Swing component know about the model, VTOL.

    In Gravity, you'd update VTOL.altitude, then call repaint on the component. e.g.

    while (true) {
      VTOL.altitude -= 0.01;
      VTOL.makeAnyOtherChangesHereAsWell();
    
      controller.repaint();
      // sleep, break etc. left as an exercise for the reader
    }
    

    Then, in the paintComponent() method (or maybe somewhere else in all the paint calls, there's a slight chance it needs to be elsewhere...) of Controller, which you know is running on the EDT

    // update my widgets from the VTOL model - may want this in a method
    String altStr=new Integer(VTOL.altitude).toString();
    this.lblAltitude.setText(altStr);  
    // may be more, e.g. ...
    this.lblFuelSupply.setText(VTOL.getFuelSupply());
    
    super.paintComponent();  // now go draw stuff...
    

    This is a bit tighter coupled than SwingPropertyChangeSupport, but the coupling is all between very related classes, so it is "reasonable", and in some ways this may be "clearer". And the Event Dispatch Queue will combine multiple repaints so this isn't as inefficient as it first appear. If multiple threads are updating stuff and queuing up multiple repaints(), only the last repaint() actually does anything.

    A disadvantage is that if your GUI has a gazillion widgets and you update all of them every time this may get a bit slow. But processors are amazingly fast nowadays.

提交回复
热议问题