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



我需要使用下面附的 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);

代码还在继续,但我认为只有这是相关的部分。我需要有一个框,询问四个值(宽度、高度、点数、要搜索的点数(。我猜必须从字符串解析为 int。

实现这一点的最佳方法是什么?

正如@XtremeBaumer告诉你的:

main 方法启动之前,您不能执行任何操作,只有当您启动时 通过CMD

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

下面是一个基于 JOptionPane.showInputDialog 中的多个输入的示例,并且为了将格式限制为integer类型,请参阅如何使 JFormattedTextField 接受没有小数点(逗号(的整数?

只需在实例化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");
}

最新更新