在主程序启动之前,在JFrame Java文件中获取用户输入

时间:2017-03-28 12:26:15

标签: java jframe user-input

我需要使用下面附带的KDTreeTester.java文件进行各种测试运行。每次完成运行并重新编译文件时,更改值(w,h,n,x)都是非常低效的。

那时我觉得在主程序打开之前输入值会非常方便。

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Main program that starts the KDTree visualization
 */
 public class KDTreeTester extends JFrame{

  int w=400;    //width of the window
  int h=400;    //height of the window
  int n=20;     //number of points
  int x=5;      //number of points to be searched (has to be smaller than n)
  KDTreeVisualization vis;  //the visualization

  public KDTreeTester(){

    //  Initialize the visualization and add it to the main frame. 
    vis = new KDTreeVisualization(w, h, n);
    add(vis);

代码继续,但我认为只有相关部分。 我需要一个盒子来询问四个值(宽度,高度,点数,要搜索的点数)。我必须将它从String解析为int。

实施此方法的最佳方式是什么?

1 个答案:

答案 0 :(得分:0)

正如@XtremeBaumer告诉你的那样:

  

只有在你开始的时候,你才能在主方法开始之前做任何事情   通过cmd

但是,如果您的意思是在显示主框架之前询问输入值,则可以使用JOptionPane来收集值。

以下是基于Multiple input in JOptionPane.showInputDialog的示例,并且要将格式限制为integer类型,请How to make JFormattedTextField accept integer without decimal point (comma)?

在实例化KDTreeVisualization之前调用此方法,并在获得这些参数后使用这些输入参数调用它。

我不会从你JFrame的构造函数中调用它,而是在实例化JFrame之前,或者甚至通过自定义菜单/按钮/你可以添加到框架中的任何内容

NumberFormat integerFieldFormatter = NumberFormat.getIntegerInstance();

JFormattedTextField nField = new JFormattedTextField(integerFieldFormatter);
JFormattedTextField xField = new JFormattedTextField(integerFieldFormatter);
JFormattedTextField widthField = new JFormattedTextField(integerFieldFormatter);
JFormattedTextField heightField = new JFormattedTextField(integerFieldFormatter);

Object[] message = {

        "Width :", widthField,
        "Height :", heightField,
        "n :", nField,
        "x :", xField
};

int option = JOptionPane.showConfirmDialog(null, message, "Enter values", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {

    try {
        int n = Integer.parseInt(nField.getText());
        int x = Integer.parseInt(xField.getText());
        int width = Integer.parseInt(xField.getText());
        int height = Integer.parseInt(xField.getText());

        // do stuff with the values, like instantitate your object with those parameters
        // new KDTreeVisualization(width, height, n)

    } catch (NumberFormatException e) {

        JOptionPane.showMessageDialog(null, "At least one of the values is invalid", "Error",
                JOptionPane.ERROR_MESSAGE);
    }

} else {
    System.out.println("Input cancelled");
}