繁体   English   中英

如何从java中的类调用另一个类

[英]How do I call a another class from a class in java

我试图调用同一目录中的另一个类并进行编译。 当我调用另一个类时,我一直收到错误符号。 任何人都可以查看我的代码,看看我做错了什么。

这是代码:

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

public class NameGameFrame extends JFrame
{
    public static String name;
    static JTextField textfield = new JTextField(20);
    static JTextArea  textarea = new JTextArea(30,30);

    public static void main( String[] args)
    {

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Name Game");
        frame.setLocation(500,400);
        frame.setSize(800,800);

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();

        JLabel label = new JLabel("Enter the Name or Partial Name to search:");
        c.gridx = 0;
        c.gridy = 0;
        c.insets = new Insets(2,2,2,2);

        panel.add(label,c);

        c.gridx = 0;
        c.gridy = 1;
        panel.add(textarea,c);

        JButton button = new JButton("Search");
        c.gridx = 1;
        c.gridy = 1;
        panel.add(button,c);

        c.gridx = 1;
        c.gridy = 0;
        panel.add(textfield,c);

        frame.getContentPane().add(panel, BorderLayout.NORTH);
        frame.pack();
        frame.setVisible(true);

        button.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae)
            {
                name = textfield.getText();
                java.io.File file = new java.io.File("namesdata.txt");
                try
                {
                    Scanner input = new Scanner(file);
                    num = input.nextLine();
                    while (input.hasNext())
                    {
                        NameRecord(name); 
                    }
                }
                catch(FileNotFoundException e)
                {
                    System.err.format("File does not exist\n");
                }
                textarea.setText(fields[0]);
            }
        });

    }
}

NameRecord是我正在调用的另一个类的名称。 我还需要在我调用的第二个文件类的标题中添加一些内容吗?

你不能打电话给班级。 您可以调用方法和构造函数。

你的陈述NameRecord(name); 是胡说八道。 我想你想调用构造函数:

NameRecord record = new NameRecord(name);

您需要在要调用其方法的类中引用NameRecord实例。 我没有看到一个。 我错过了吗? 如果没有,请添加一个。

我不相信这是合法的Java:

while (input.hasNext())
{
    NameRecord(name); 
}

你需要调用new来调用构造函数,正如我看到Martijn指出的那样。

代替这个

  while (input.hasNext())
                {
                    NameRecord(name); 
                }

你必须做一个该类的对象

     while (input.hasNext())
                {
                    NameRecord record = new NameRecord(name); 
                }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM