当我单击类别按钮之后的选择按钮时,为什么不打印字符串并打印空值?


package simpleclass;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SimpleClass extends BaseClass {
    JButton b1 = new JButton("Category");
    JButton b2 = new JButton("Select");
    JFrame f = new JFrame();
    SimpleClass() {
        f.add(b1);
        f.add(b2);
        f.setLayout(new GridLayout(1, 2));
        f.setSize(200, 200);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        b1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    new SubClass();
                } catch (IOException ex) {
                }
            }
        });
        b2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(astring);
            }
        });
    }
    public static void main(String[] args) {
        new SimpleClass();
    }
}
class BaseClass {
    String astring;
    public void setString(String astring) {
        this.astring = astring;
    }
}
class SubClass extends BaseClass {
    SubClass() throws FileNotFoundException {
        super.setString("WHYnull");
    }
}

在这个代码中有一个基类BaseClass和两个子类SimpleClassSubClass。有两个按钮。当按钮"Category"被按下时,String "astring"被设置为"WHYnull"。现在我的问题是,当我按"选择"按钮之后,为什么"null"被打印?变量"astring"不是排他性的吗?

您的状态:

当按下"类别"按钮时,字符串"astring"被设置为"WHYnull"。

是的,这是正确的,但它只适用于您在第一个ActionListoner中创建(并丢弃)的new SubClass()。它不会对原始程序的字段aString(当前this)产生任何影响。

我的建议:这不是一个应该用继承来解决的问题。把继承完全排除在这个图之外。

我做:

  b1.addActionListener(new ActionListener() {
     @Override
     public void actionPerformed(ActionEvent e) {
        // try {
        // new SubClass();
        // } catch (IOException ex) {
        //
        // }
        setString("Fubar");
     }
  });

还要注意,你的代码不应该有空catch块,因为这相当于在Java中闭着眼睛开车。是很刺激,但也很危险。


你问关于使用多个类的GUI,一个常见的例子是模型-视图-控制或MVC类型的程序设计,其中程序的逻辑驻留在模型中,GUI驻留在视图中,两者之间的交互驻留在控件中。例如,以您的小程序为例,可以这样做:

import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SimpleMCV {
   private static void createAndShowGui() {
      final SimpleView simpleView = new SimpleView();
      final SimpleModel simpleModel = new SimpleModel("");
      MainControl mainControl = new MainControl();
      mainControl.setUp(simpleView, simpleModel);
      JFrame frame = new JFrame("Simple GUI");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(simpleView);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
@SuppressWarnings("serial")
class SimpleView extends JPanel {
   private JTextField textField = new JTextField(10);
   public SimpleView() {
      textField.setFocusable(false);
      add(textField);
   }
   public void setTextFieldText(String text) {
      textField.setText(text);
   }
   public void addAction(Action action) {
      add(new JButton(action));
   }
}
class MainControl {
   public void setUp(final SimpleView simpleView, final SimpleModel simpleModel) {
      simpleView.addAction(new SimpleControl(simpleModel, "Fubar"));
      simpleView.addAction(new SimpleControl(simpleModel, "Snafu"));
      simpleView.addAction(new SimpleControl(simpleModel, "Bohica"));
      simpleModel.addChangeListener(new ChangeListener() {
         @Override
         public void stateChanged(ChangeEvent e) {
            simpleView.setTextFieldText(simpleModel.getSomeText());
         }
      });
   }
}
@SuppressWarnings("serial")
class SimpleControl extends AbstractAction {
   private SimpleModel simpleModel;
   public SimpleControl(SimpleModel simpleModel, String name) {
      super(name);
      int mnemonic = (int) name.charAt(0);
      putValue(MNEMONIC_KEY, mnemonic);
      this.simpleModel = simpleModel;
   }
   @Override
   public void actionPerformed(ActionEvent e) {
      simpleModel.setSomeText(e.getActionCommand());
   }
}
class SimpleModel {
   private List<ChangeListener> listenerList = new ArrayList<>();
   private String someText;
   public SimpleModel(String someText) {
      this.someText = someText;
   }
   public String getSomeText() {
      return someText;
   }
   // change text and notify all listeners
   public void setSomeText(String someText) {
      this.someText = someText;
      for (ChangeListener changeListener : listenerList) {
         changeListener.stateChanged(new ChangeEvent(this));
      }
   }
   // allow outside classes to add a ChangeListener
   public void addChangeListener(ChangeListener cl) {
      listenerList.add(cl);
   }
}

相关内容

  • 没有找到相关文章

最新更新