使非静态方法静态



首先,也许我的标题是错误的,任何正文请为我的确切问题进行更正。对我的英语感到抱歉,如果您烦您。这是我的主帧类:

public class MainFrame extends JFrame{
    public static JTextField checksum;
    public MainFrame(){
        createComponents();
        actionEvent();
    }
    private void createComponents(){
    ....
    }
    private void actionEvent(){
        ActionListener al = new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae) {
                if (ae.getSource() == btnExem){
                actionEvent.btnPerformed(ae);
            }
            else if (ae.getSource() == jfBrowser){
            .........
            }
        }
    }
    copyBtn.addActionListener(al);
    public static void main(String[] args){
        MainFrame f = new MainFrame();
        f.setVisible(true);
        f.setResizable(false);
    }

ActionEvent类:

public class actionEvent extends MainFrame{
//example
    public static void btnPerformed(ActionEvent ae){
    checksum.setText("");
    }

我想在大型机类中设置私人的校验和属性,我在大型机类中编写一个方法setCheckSumText:

public void setChecksumText(String t){
        this.checksum.setText(t);
    }

但IDE表明BTNPerformed必须是静态的,因此我不能使用非静态的SetCheckSumText方法。我该如何修复?

您需要将static添加到setChecksumText()。注意校验和是static,它仅存在一次,每个对象不是一次,这意味着我们不用this访问它,而是通过类名来访问它(如果变量在同一类中,则可以省略类):

private static JTextField checksum;
public static void setChecksumText(String t) {
    checksum.setText(t); // or: MainFrame.checksum.setText(t);
}

最新更新