簡體   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