我有这段代码,如何在 java 中将它从控制台传输到 GUI?

I have this code, how can I transfer it from console to GUI in java?

我有这段代码,在控制台上完成并运行良好,但我需要将它转移到 GUI,例如我有 4 个操作,它们是计算和处理中位数、众数、均值和标准差。因此,我需要有 4 个文本字段输入和一个按钮来计算 4 个操作,并在程序本身或弹出窗口中显示。

import javax.sound.midi.SysexMessage;
import java.util.Arrays;
import java.util.*;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.text.Text;
import java.applet.*;
import javax.swing.*;

public class FinalProg {

    Button button;

    public static void main(String[] args)
    {


//        int[] dataSet = {1,2,3,4,345,312,756,0,-234321132,234};
//        int[] dataSet = {5,3,2,5,2,5,758,345,32,231,5,5,5,2,2};

//        Scanner scanner = new Scanner(System.in);
//        String input = scanner.nextLine();
//
//
//
//
//
//
//
//
//
//        int [] dataSet = new int[input.length()];

        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine(); //Numbers inputted from user in your case
        String[] list;             //List to store individual numbers
        list = input.split(" ");     // Regex to split the String so you get each number

        //Mean
        int sum = 0;

        for (String n : list) {
            sum += Integer.parseInt(n);
        }

        System.out.println("The mean of the data set is  " +
                ((double) sum / list.length));


        //Median
        Arrays.sort(list);
//            if (list.length  % 2 != 0) {
//                System.out.println("The median of the data set is: " + Double.parseDouble(list[list.length / 2]));
//            } else {
//                float median = (Integer.parseInt(list[list.length/2]+Integer.parseInt(list[(list.length/2)-1])) / 2f );
//                System.out.println("The median of the data set is: " + median);
////                System.out.println("The median of the data set is: " + Double.parseDouble(list[list.length / 2] + list[list.length / 2 - 1]) / 2.0);
//            }

        if (list.length % 2 == 0) {
            System.out.println("The median of the data set is: " + Double.parseDouble(list[list.length / 2]) + Double.parseDouble(list[list.length / 2 - 1]) / 2);
        } else {
//                float median = (Integer.parseInt(list[list.length/2]+Integer.parseInt(list[(list.length/2)-1])) / 2f );
            System.out.println("The median of the data set is: " + list[list.length / 2]);
//                System.out.println("The median of the data set is: " + Double.parseDouble(list[list.length / 2] + list[list.length / 2 - 1]) / 2.0);
        }


        //Mode

        int maxNumber = -1;
        int maxAppearances = -1;

        for (int i = 0; i < list.length; i++) {
            int count = 0;

            for (int j = 0; j < list.length; j++) {
//                    if (list[i] == list[j]) {
//                        count++;
//                    }
                if (list[i].equals(list[j])) {
                    count++;
                }
            }
            if (count > maxAppearances) {
                maxNumber = Integer.parseInt(list[i]);
                maxAppearances = count;
            }
            count = 0;
        }

        System.out.println("The mode of the data set: " + maxNumber);


        //STDV

        double STDVsum = 0.0, standardDeviation = 0.0;
        int length = list.length;
        for (String num : list) {
            STDVsum += Double.parseDouble(num);
        }
        double mean = STDVsum / length;
//        for(String num: list) {
//            standardDeviation += Double.parseDouble(Math.pow(num - mean, 2)); // It says operator - doesn't apply...
//        }
        for (String num : list) {
            int num_to_Integer = Integer.parseInt(num);
            standardDeviation += Math.pow(num_to_Integer - mean, 2); //No need to parse now
        }
        System.out.println("STDV " + Math.sqrt(standardDeviation / length));

    }



}

从控制台程序迁移到 GUI 程序需要的不仅仅是更改主要方法。 GUI 程序是事件驱动的。

事件驱动的意思是,例如,一个按钮被按下,一个事件被触发。作为程序员,您负责编写触发该事件时发生的事情。

我的一些建议。

  • 你应该通过教程学习一些基础知识 components and how they work. Some of the basic ones are JLabel, JTextField, JButton
  • 你肯定需要关注如何写event listeners。 您可能想要关注的一些基本事件是 ActionListener for button presses MouseListener 鼠标事件。
  • 您可以使用 Java Swing 轻松创建表单并实现它 功能。它始终是一个很好的起点。一旦掌握了基础知识,就可以继续学习更复杂的内容 material.
  • 使用一些高级 IDE,例如 NetBeans, Eclipse, IntelliJ, etc. Here are some basic projects to start from NetBeans

从技术上讲,如果我回答你的问题,

您可以使用 Java Swing.

将控制台应用程序转换为 GUI 应用程序
  • 您正在从控制台获取输入。取而代之的是,您可以使用 JTextFieldsJTextArea 随您希望获得输入。
  • 你可以使用一些 JButtons 来触发需要的进程 在填充 JTextFields 后执行。
  • 您可以使用 JTextArea 来写入您在控制台上写入的内容,而不是将您通常写入的内容写入控制台。如果你有系列或句子,你可以使用 JTextArea 的 append() 方法。

下面是我使用 NetBeans 在 Swing 中创建的代码 IDE,

import java.util.Arrays;

public class Whosebug extends javax.swing.JFrame {

    String[] list;

    /**
     * Creates new form Whosebug
     */
    public Whosebug() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        inputTxt = new javax.swing.JTextField();
        scrollPane = new javax.swing.JScrollPane();
        consoleTxt = new javax.swing.JTextArea();
        stdvBtn = new javax.swing.JButton();
        modeBtn = new javax.swing.JButton();
        medianBtn = new javax.swing.JButton();
        meanBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        inputTxt.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                inputTxtKeyReleased(evt);
            }
        });

        consoleTxt.setColumns(20);
        consoleTxt.setRows(5);
        scrollPane.setViewportView(consoleTxt);

        stdvBtn.setText("STDV");
        stdvBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stdvBtnActionPerformed(evt);
            }
        });

        modeBtn.setText("Mode");
        modeBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modeBtnActionPerformed(evt);
            }
        });

        medianBtn.setText("Median");
        medianBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                medianBtnActionPerformed(evt);
            }
        });

        meanBtn.setText("Mean");
        meanBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                meanBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(inputTxt)
                    .addComponent(scrollPane)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addGap(0, 370, Short.MAX_VALUE)
                        .addComponent(meanBtn)
                        .addGap(18, 18, 18)
                        .addComponent(medianBtn)
                        .addGap(18, 18, 18)
                        .addComponent(modeBtn)
                        .addGap(18, 18, 18)
                        .addComponent(stdvBtn)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(inputTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 78, Short.MAX_VALUE)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(stdvBtn)
                    .addComponent(modeBtn)
                    .addComponent(medianBtn)
                    .addComponent(meanBtn))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        setSize(new java.awt.Dimension(730, 381));
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void inputTxtKeyReleased(java.awt.event.KeyEvent evt) {                                     
        list = inputTxt.getText().split(" ");
    }                                    

    private void meanBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
        int sum = 0;

        for (String n : list) {
            sum += Integer.parseInt(n);
        }
        consoleTxt.append("The mean of the data set is  " + ((double) sum / list.length) + "\n");
    }                                       

    private void medianBtnActionPerformed(java.awt.event.ActionEvent evt) {                                          
        Arrays.sort(list);

        if (list.length % 2 == 0) {
            consoleTxt.append("The median of the data set is: " + Double.parseDouble(list[list.length / 2]) + Double.parseDouble(list[list.length / 2 - 1]) / 2 + "\n");
        } else {
            consoleTxt.append("The median of the data set is: " + list[list.length / 2] + "\n");
        }
    }                                         

    private void modeBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
        int maxNumber = -1;
        int maxAppearances = -1;

        for (int i = 0; i < list.length; i++) {
            int count = 0;

            for (int j = 0; j < list.length; j++) {
                if (list[i].equals(list[j])) {
                    count++;
                }
            }
            if (count > maxAppearances) {
                maxNumber = Integer.parseInt(list[i]);
                maxAppearances = count;
            }
            count = 0;
        }

        consoleTxt.append("The mode of the data set: " + maxNumber + "\n");
    }                                       

    private void stdvBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
        double STDVsum = 0.0, standardDeviation = 0.0;
        int length = list.length;

        for (String num : list) {
            STDVsum += Double.parseDouble(num);
        }

        double mean = STDVsum / length;

        for (String num : list) {
            int num_to_Integer = Integer.parseInt(num);
            standardDeviation += Math.pow(num_to_Integer - mean, 2);
        }

        consoleTxt.append("STDV " + Math.sqrt(standardDeviation / length) + "\n");
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Whosebug.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Whosebug.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Whosebug.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Whosebug.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Whosebug().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextArea consoleTxt;
    private javax.swing.JTextField inputTxt;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JButton meanBtn;
    private javax.swing.JButton medianBtn;
    private javax.swing.JButton modeBtn;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JButton stdvBtn;
    // End of variables declaration                   
}

如果你通过代码,

Used components JTextField, JTextArea, JButton, JPanel, JFrame.

private javax.swing.JTextArea consoleTxt;
private javax.swing.JTextField inputTxt;
private javax.swing.JPanel mainPanel;
private javax.swing.JButton meanBtn;
private javax.swing.JButton medianBtn;
private javax.swing.JButton modeBtn;
private javax.swing.JButton stdvBtn;

Used ActionListeners to trigger the functions.

例如 ActionListener 调用一个函数(在你的情况下找到平均值)一旦按下平均值按钮它将触发 meanBtnActionPerformed(evt); 函数。

meanBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                meanBtnActionPerformed(evt);
            }
        });

里面有什么meanBtnActionPerformed(evt);.

private void meanBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
        int sum = 0;

        for (String n : list) {
            sum += Integer.parseInt(n);
        }
        consoleTxt.append("The mean of the data set is  " + ((double) sum / list.length) + "\n");
    }

另一件主要的事情是,在您的控制台应用程序中,当您键入数字并输入它时,String[] list 将填充。为此,我使用了 KeyListener。当用户按下或释放键盘键时,具有键盘焦点的组件会触发按键事件。因此,在您的情况下,当您键入 10 20 30 40 50 时,它将通过调用 inputTxtKeyReleased(evt); 函数将这些数字添加到列表中。

inputTxt.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                inputTxtKeyReleased(evt);
            }
        });

所以我建议检查代码,尝试一下,浏览 java 文档并从教程中学习。编码愉快!