简体   繁体   English

如何使用NetBeans在Java中将主类链接到jframe表单

[英]how to link a main class to a jframe form in java using netbeans

Good day! 美好的一天!

I have created a code using Netbeans and it executes the processes just fine. 我使用Netbeans创建了一个代码,它可以很好地执行进程。 Now, i want my input to given and output to be displayed through a user interface. 现在,我希望给定输入并通过用户界面显示输出。 I have then created a 2 Jframes, 1 to collect the user's input and the other to display the results after execution by the code. 然后,我创建了2个Jframe,其中1个用于收集用户的输入,另一个创建由代码执行后显示结果。

But, i am unable to link the interface to the main class(called NgramBetaE) as i am not aware of how i can do so. 但是,我无法将接口链接到主类(称为NgramBetaE),因为我不知道该怎么做。

I highly welcome suggestions. 我非常欢迎您提出建议。

The main class in its entirety is; 整个主要类别是:

package ngrambetae;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;


/**
 *
 * @author 201102144
 */
 public class NgramBetaE {



static LinkedList<String> allWords = new LinkedList<String>();
static LinkedList<String> distinctWords = new LinkedList<String>();
static String[] hashmapWord = null;
static int wordCount;
public static HashMap<String,HashMap<String, Integer>> hashmap = new HashMap<>();
public static HashMap<String,HashMap<String, Integer>> bigramMap = new HashMap<>();


/**
 * @param args the command line arguments
 */
public static void main(String[] args) {


    //prompt user input
    Scanner input = new Scanner(System.in);

    //read words from collected corpus; a number of .txt files
            File directory = new File("Corpus");
            File[] listOfFiles = directory.listFiles();//To read from all listed iles in the "directory"

            int lineNumber = 0;
            String line;
            String files;
            String delimiters = "[()?!:;,.\\s]+";

           //reading from a list of text files 
            for (File file : listOfFiles) {
                if (file.isFile()) {
                    files = file.getName();
                    try {
                        if (files.endsWith(".txt") || files.endsWith(".TXT")) {  //ensures a file being read is a text file 
                        BufferedReader br = new BufferedReader(new FileReader(file)); 


                        while ((line = br.readLine()) != null) {
                                line = line.toLowerCase();

                                hashmapWord = line.split(delimiters);


                                //CALCULATING UNIGRAMS                                
                                for(int s = 0; s < hashmapWord.length; s++){

                                    String read = hashmapWord[s];

                                    allWords.add(read);

                                    //count the total number of words in all the text files combined
                                    //TEST
                                    wordCount = 0;                                                                   
                                        for (int i = 0; i < allWords.size(); i++){
                                        wordCount ++;                                        
                                }   

                                }

                                //CALCULATING BIGRAM FREQUENCIES
                                for(int s = 0; s < hashmapWord.length -1; s++){

                                    String read = hashmapWord[s];
                                    final String read1 = hashmapWord[s + 1];

                                    HashMap<String, Integer> counter = bigramMap.get(read);
                                        if (null == counter) {
                                            counter = new HashMap<String, Integer>();
                                            bigramMap.put(read, counter);
                                        }
                                        Integer count = counter.get(read1);
                                        counter.put(read1, count == null ? 1 : count + 1);


                                }

                                //CALCULATING TRIGRAM FREQUENCIES
                                for(int s = 0; s < hashmapWord.length - 2; s++){

                                    String read = hashmapWord[s];
                                    String read1 = hashmapWord[s + 1];
                                    final String read2 = hashmapWord[s + 2];

                                    String readTrigrams = read + " " + read1;

                                    HashMap<String, Integer> counter = hashmap.get(readTrigrams);
                                        if (null == counter) {
                                            counter = new HashMap<String, Integer>();
                                            hashmap.put(readTrigrams, counter);
                                        }
                                        Integer count = counter.get(read2);
                                        counter.put(read2, count == null ? 1 : count + 1);

                                }

                        }
                            br.close();

                        }
                    } catch (NullPointerException | IOException e) {
                        e.printStackTrace();
                        System.out.println("Unable to read files: " + e);
                    }

            }
            }


            //COMPUTING THE TOTAL NUMBER OF WORDS FROM ALL THE TEXT FILES COMBINED
            System.out.println("THE TOTAL NUMBER OF WORDS IN COLLECTED CORPUS IS : \t" + wordCount + "\n"); 

                for(int i = 0, size = allWords.size(); i < size; i++){
                    String distinctWord = allWords.get(i);

                    //adding a word into the 'distinctWords' list if it doesn't already occur                
                    if(!distinctWords.contains(distinctWord)){
                        distinctWords.add(distinctWord);

                    }
                }                    


            //PRINTING THE DISTINCT WORDS
            System.out.println("THE DISTINCT WORDS IN TOTAL ARE :\t " + distinctWords.size() + "\n"); 


            System.out.println("PRINTING CONTENTS OF THE BIGRAMS HASHMAP... ");
            System.out.println(bigramMap);
            System.out.println("================================================================================================================================================================================================================================================================================================================\n");



            System.out.println("PRINTING CONTENTS OF THE TRIGRAMS HASHMAP... ");
            System.out.println(hashmap);
            System.out.println("================================================================================================================================================================================================================================================================================================================\n");


        //QUITTING APPLICATION

        String userInput = null;
        while(true) {

                System.out.println("\n**********************************************************************************************************************************************************************************************************************************");
                System.out.println("\n\n\t\tPLEASE ENTER A WORD OR PHRASE YOU WOULD LIKE A PREDICTION OF THE NEXT WORD FROM:");
                System.out.println("\t\t\t\t(OR TYPE IN  'Q' OR 'q' TO QUIT)");

                userInput = input.nextLine();                    
                    if (userInput.equalsIgnoreCase("Q")) break;

                    //FORMAT USER INPUT
                    String[] users = userInput.toLowerCase().split("[?!,.\\s]+");
                    if (users.length < 2) {
                        userInput = users[0];

                        //System.out.println("\nENTRY '" + userInput + "' IS TOO SHORT TO PREDICT NEXT WORD. PLEASE ENTER 2 OR MORE WORDS");

                        //CALCULATING BIGRAM PROBABILITY

                        int sum = 0;
                        try {
                            for(String s : bigramMap.get(userInput).keySet()) {
                                sum += bigramMap.get(userInput).get(s);
                            }


                            String stringHolder = null;
                            double numHolder = 0.0;
                            for(String s : bigramMap.get(userInput).keySet()) {
                                //System.out.println("TWO"); 
                                double x = Math.round(bigramMap.get(userInput).put(s, bigramMap.get(userInput).get(s))/ (double)sum *100 );

                                if(s != null){
                                    if(numHolder < x ){

                                        stringHolder = s;
                                        numHolder = x;

                                    } 

                                }

                            }
                            System.out.println("\nNEXT WORD PREDICTED IS '" + stringHolder + "'");
                            System.out.println("ITS PROBABILITY OF OCCURRENCE IS " + numHolder + "%"); 

                        } catch (Exception NullPointerException) {
                            System.out.println("\nSORRY. MATCH NOT FOUND.");
                        }

                    } else {
                        userInput = users[users.length - 2] + " " + users[users.length - 1];



//                        System.out.println("FROM USER WE GET....");
//                        System.out.println(bigrams.get(userInput).keySet());

                    /* CALCULATING TRIGRAM PROBABILITY*/
                        int sum = 0;
                        try {
                            for(String s : hashmap.get(userInput).keySet()) {
                                sum += hashmap.get(userInput).get(s);
                            }

                            String stringHolder = null;
                            double numHolder = 0.0;
                            for(String s : hashmap.get(userInput).keySet()) {
                                //System.out.println("TWO"); 
                                double x = Math.round(hashmap.get(userInput).put(s, hashmap.get(userInput).get(s))/ (double)sum *100 );

                                if(s != null){
                                    if(numHolder < x ){

                                        stringHolder = s;
                                        numHolder = x;

                                    } 

                                }

                            }
                            System.out.println("\nNEXT WORD PREDICTED IS '" + stringHolder + "'");
                            System.out.println("ITS PROBABILITY OF OCCURRENCE IS " + numHolder + "%"); 

                        } catch (Exception NullPointerException) {
                            System.out.println("\nSORRY. MATCH NOT FOUND.");
                        }
                    } 
            }

        input.close();
}

    }

My first Jframe which i would like to appear upon running the project has got a single textbox and a single button; 我想在运行该项目时出现的第一个Jframe有一个文本框和一个按钮。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    String usersInput = jTextField1.getText(); 

    Interface1 s = new Interface1();
    s.setVisible(true);
    dispose();

}   

i would like for the user to enter data in the textbox and when they click on the button 'predict next word' then the output from the code execution is displayed on the second jframe which has got 3 labels and relative text areas. 我希望用户在文本框中输入数据,然后单击“预测下一个单词”按钮,然后代码执行的输出将显示在第二个jframe上,它具有3个标签和相对文本区域。

NOTE; 注意; i couldn't paste the screenshots but if you run the NgramBetaE class you will get an idea of how the interfaces will be as i tried to explain them. 我无法粘贴屏幕截图,但是如果您运行NgramBetaE类,您将对接口的外观有所了解,因为我试图对其进行解释。

Thank you 谢谢

Don't even try to link your GUI code to your NgramBetaE code as you've more work to do since the NgramBetaE is little more than one huge static main method that gets user input from the console with a Scanner and outputs to the console via printlns. 甚至不要尝试将您的GUI代码链接到您的NgramBetaE代码,因为您需要做更多的工作,因为NgramBetaE仅仅是一种巨大的静态主方法,该方法通过扫描仪从控制台获取用户输入,并通过printlns。 Melding these two is like trying to put a square peg into a round hole. 融合这两个就像试图将一个方形的钉子插入一个圆孔。

Instead re-write the whole thing with an eye towards object-oriented coding, including creation of an OOP-compliant model class with instance fields and methods, and a single GUI that gets the input and displays it, that holds an instance of the model class and that calls instance methods on this instance. 而是着眼于面向对象的编码来重写整个过程,包括创建具有实例字段和方法的,与OOP兼容的模型类,以及用于获取输入并显示它的单个GUI,其中包含模型的实例类,并在此实例上调用实例方法。


Consider creating non-GUI classes and methods for -- 考虑为以下项目创建非GUI类和方法:

  • Reading in data from your text files 从文本文件中读取数据
  • Analyzing and hashing the data held in the text files including calculating word frequencies etc... 分析和散列文本文件中包含的数据,包括计算单词频率等...
  • Returning needed data after analysis in whatever data form it may be needed. 分析后以任何可能的数据形式返回所需的数据。
  • A method for allowing input of a String/phrase for testing, with return its predicted probability 一种允许输入字符串/短语进行测试并返回其预测概率的方法

Then create GUI code for: 然后为以下内容创建GUI代码:

  • Getting selected text file from the user. 从用户获取选定的文本文件。 A JFileChooser and supporting code works well here. JFileChooser和支持的代码在这里效果很好。
  • Button to start analysis 按钮开始分析
  • JTextField to allow entering of phrase JTextField允许输入短语
  • JTextArea or perhaps JTable to display results of analysis JTextArea或JTable可以显示分析结果

Note that you should avoid having more than one JFrame in your GUI. 请注意,您应该避免在GUI中使用多个JFrame。 For more on this, please have a look at The Use of Multiple JFrames, Good/Bad Practice? 有关更多信息,请查看“使用多个JFrame,良好/不良实践?”。

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

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