Using ActionListener to update variables in other classes

青春壹個敷衍的年華 提交于 2019-12-12 03:06:32

问题


I am designing an applet so it allows a user to plot a graph. I am having problems to construct a code which from another file (ControlsB.java) the variables in the Graph.java file are updated. Below is my code:

 import java.awt.*;
import javax.swing.*;


 public class Calculator extends JFrame{

/**
 * 
 */
private static final long serialVersionUID = 1L;
private static final int HORIZONTAL_SCROLLBAR_NEVER = 0;
private static final int VERTICAL_SCROLLBAR_ALWAYS = 0;

public static void main (String[] args){

    JFrame calculator = new JFrame("My Simple Calculator");

    calculator.setSize(500,500);

JPanel panel = new JPanel();

panel.setLayout(new BorderLayout());

Box a = Box.createHorizontalBox();

JTextArea text = new JTextArea(10,15);

JScrollPane scroll = new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

Box b = Box.createHorizontalBox();


//JToolBar tool = new JToolBar(SwingConstants.HORIZONTAL);
JButton add = new JButton("+");
JButton minus = new JButton("-");
JButton multi = new JButton("x");
JButton div = new JButton("/");
JButton c = new JButton("C");
JButton eq = new JButton("=");

JTextField field = new JTextField(10);

JButton enter = new JButton("Enter");

b.add(add);
b.add(minus);
b.add(multi);
b.add(div);
b.add(c);
b.add(eq);

a.add(field);
a.add(enter);

panel.add(scroll,BorderLayout.NORTH);
panel.add(b,BorderLayout.CENTER);
panel.add(a,BorderLayout.SOUTH);

calculator.setContentPane(panel);
calculator.setVisible(true);
}

 }

Now my main concerns are in the ControlsB.java file, where I want that when the user inputs the the x-axis and y-axis ranges and hits the button Resize the variables in the graph.java file are updated accordingly and thus the graph resizes.

The variables which I am talking about in Graph.java file are in lines between 57 and 65.

Thanks


回答1:


Typically if you need to share data between several classes, and make updates to that data from several classes you put your data in a so-called 'Model', and share that model between the different classes. Your view will be a (visual) representation of the data in the model, and your action listener just operates on the model.

If you make sure the model is observable, the view can just update itself when the data is changed. So your ActionListener just changes the data, the model let all interested parties know it has been changed (in your case the graph), and if needed those interested parties react on that change (an update of your graph).

As I find code more illustrating than text in most case I put together a rather dumb example, but which illustrates what I mean. I have one model (DataModel) which is visualized in a view (DataPanel), and an external class makes regular updates on the model (the Timer in my example), and the view gets updated while the Timer only knows of the DataModel and not of the DataPanel.

Oh yes, the code is rather long, but you threw a lot of code at us as well.

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class ActionListenerDemo {

  private static class DataModel{
    private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport( this );

    private String data="";

    public void addPropertyChangeListener( PropertyChangeListener listener ) {
      propertyChangeSupport.addPropertyChangeListener( listener );
    }

    public String getData() {
      return data;
    }

    public void setData( String aData ) {
      String old = data;
      data = aData;
      propertyChangeSupport.firePropertyChange( "data", old, data );
    }
  }

  private static class DataPanel extends JFrame{
    private final DataModel dataModel;
    private final JLabel label;
    private DataPanel( DataModel aDataModel ) throws HeadlessException {
      dataModel = aDataModel;
      dataModel.addPropertyChangeListener( new PropertyChangeListener() {
        @Override
        public void propertyChange( PropertyChangeEvent evt ) {
          updateUIFromModel();
        }
      } );
      label = new JLabel( dataModel.getData() );
      add( label );
    }
    private void updateUIFromModel(){
      label.setText( dataModel.getData() );
    }
  }

  public static void main( String[] args ) {
    final DataModel model = new DataModel();
    model.setData( "Change me and watch the UI update !" );
    EventQueue.invokeLater( new Runnable() {
      @Override
      public void run() {
        DataPanel dataPanel = new DataPanel( model );
        dataPanel.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        dataPanel.pack();
        dataPanel.setVisible( true );
      }
    } );
    Timer timer = new Timer( 1000, new ActionListener() {
      private String[] values = {"Data changed", "More changes", "Lorem ipsum" };
      private int counter = 0;
      @Override
      public void actionPerformed( ActionEvent e ) {
        counter = counter%values.length;
        model.setData( values[counter] );
        counter++;
      }
    } );
    timer.setRepeats( true );
    timer.start();
  }
}


来源:https://stackoverflow.com/questions/11073039/using-actionlistener-to-update-variables-in-other-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!