【问题标题】:I have this code, how can I transfer it from console to GUI in java?我有这段代码,如何将它从控制台传输到 java 中的 GUI?
【发布时间】:2019-09-09 02:03:37
【问题描述】:

我有这段代码,在控制台上完成并且功能非常好,但我需要将它转移到 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));

    }



}

【问题讨论】:

  • 或 JavaFx。您可以从 Youtube 上的数千个视频教程或任何关于 gui 的 Java 书籍中学习它。既然你已经走到这一步,那就不会那么困难了。你会很容易掌握它。
  • 另见calculator example。它使用ScriptEngine 来评估文本字段中的表达式。

标签: java user-interface median mode


【解决方案1】:

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

我所说的事件驱动的意思是,例如,一个按钮被按下,一个事件被触发。作为程序员,您有责任对触发该事件时发生的情况进行编码。

所以我的一些建议。

  • 您应该阅读教程并学习一些基础知识 components 以及它们是如何工作的。一些基本的是JLabelJTextField, JButton
  • 你肯定需要专注于如何写event listeners。 您可能需要关注的一些基本问题是 ActionListener 用于按钮按下 MouseListener 用于鼠标事件。
  • 您可以使用Java Swing 轻松创建表单并实现其 功能。它始终是一个很好的起点。一旦你掌握了基础知识,就可以继续学习一些更复杂的材料。
  • 使用一些高级 IDE,例如 NetBeansEclipseIntelliJ 等。下面是一些从 NetBeans 开始的基本项目。

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

您可以使用 Java Swing 将控制台应用程序转换为 GUI 应用程序。

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

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

import java.util.Arrays;

public class StackOverflow extends javax.swing.JFrame {

    String[] list;

    /**
     * Creates new form StackOverflow
     */
    public StackOverflow() {
        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(StackOverflow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(StackOverflow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(StackOverflow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(StackOverflow.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 StackOverflow().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                   
}

如果你通过代码,

使用的组件JTextFieldJTextAreaJButtonJPanelJFrame.

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;

使用ActionListeners触发函数。

例如,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 文档并从教程中学习。快乐编码!

【讨论】:

  • 伙计,你是救世主!你不知道我有多担心它。非常感谢你这样做并解释它。
  • 很高兴知道它帮助了兄弟:)
猜你喜欢
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多