簡體   English   中英

從另一個類錯誤Java調用方法

[英]Calling a method from another class error Java

我試圖從另一個類的ActionListener訪問另一個類中的方法,但是,ActionListener中的nameWelcome出現語法錯誤消息,要求我為其創建變量。 我已經創建了一個對象並將其引用到我要訪問的類。 我不知道我在哪里犯錯:

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

public class mathMulti extends JFrame {
    JButton nextButton;
    TextField nameField;
    JLabel fullName;
    JFrame frameOne;
    JPanel panelOne;

    public mathMulti() {

        frameStart();

    }

    public void frameStart() {


        frameOne = new JFrame();
        frameOne.setSize(500, 500);
        frameOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panelOne = new JPanel(new GridBagLayout());
        panelOne.setBackground(Color.gray);
        frameOne.add(panelOne);

        GridBagConstraints g = new GridBagConstraints();
        fullName = new JLabel("Full Name: ");
        g.insets = new Insets(-390, -195, 0, 0);
        g.gridx = 0;
        g.gridy = 0;
        panelOne.add(fullName, g);

        nameField = new TextField(30);
        g.insets = new Insets(10, 10, 10, 10);
        g.gridx = 1;
        g.gridy = 0;
        g.weightx = 0;
        g.weighty = 0;
        g.ipady = 6;
        panelOne.add(nameField, g);

        nextButton = new JButton(" NEXT " + '\u25BA');
        g.insets = new Insets(60, 5, 5, 5);
        g.gridx = 2;
        g.gridy = 5;
        g.weightx = 0;
        g.weighty = 0;

        nextButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

               mathApo mathA =  new mathApo();
               mathA.frameNext();
               nameWelcome.setText(nameField.getText());
               frameOne.dispose();

            }

        });

        panelOne.add(nextButton, g);

        frameOne.setVisible(true);

    }


    public class mathApo extends JFrame {

          JFrame frameTwo;
          JPanel panelTwo;
          JLabel nameWelcome;

        public mathApo() {

            frameNext();

        }

        public void frameNext() {

            frameTwo = new JFrame();
            frameTwo.setSize(500, 500);
            frameTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            panelTwo = new JPanel(new GridBagLayout());
            panelTwo.setBackground(Color.gray);
            frameTwo.add(panelTwo);

            nameWelcome = new JLabel("Welcome, ");
            panelTwo.add(nameWelcome);

            frameTwo.setVisible(true);
        }

    }

}

就像用戶Worthless在評論中指出的那樣,您正在調用變量nameWelcome就像它是mathMulti類中的一個字段一樣,但實際上它是mathApo類中的一個字段。

所以這:

nameWelcome.setText(nameField.getText()); 

確實應該是:

mathA.nameWelcome.setText(nameField.getText());

另外,即使它不是很重要,Java中的慣例還是大寫類名的首字母。 因此,將代替mathApomathMulti ,而是MathApoMathMulti

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM