2017-03-28 5 views
-1

以下に添付のKDTreeTester.javaファイルを使用してさまざまなテストを実行する必要があります。実行を終了してファイルを再コンパイルするたびに値(w、h、n、x)を変更するのはかなり非効率的です。メインプログラムが起動する前にJFrame Javaファイルでユーザー入力を取得

これは、メインプログラムが開く前に値を入力するだけで大​​変便利だと思ったときです。

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); 

コードは続きますが、関連する部分だけだと思います。 4つの値(幅、高さ、ポイント数、検索するポイント数)を求めるボックスが必要です。 StringからStringに解析する必要があります。

これを実装するにはどうすればよいですか?

+0

cmdで起動した場合にのみ、メインメソッドが起動する前に何もできません。あなたはカスタムJDialogを使うことができます – XtremeBaumer

+0

'JFrame'を使っているなら、' JTextField'を使って入力を集めてみませんか? –

答えて

0

@XtremeBaumerはあなたに言ったよう:

mainメソッドが起動する前に、あなたが何かを傾ける、あなたはCMD

経由 を開始する場合にのみ、しかし、あなたが意味する場合は、あなたの前に、入力値を求めますメインフレームが表示されたら、JOptionPaneを使用して値を収集することができます。ここで

Multiple input in JOptionPane.showInputDialogと、ちょうどあなたのKDTreeVisualizationをインスタンス化する前にこれを呼び出して、あなたがそれらを持っていたら、それらの入力パラメータでそれを呼び出すHow to make JFormattedTextField accept integer without decimal point (comma)?

に、integerタイプにフォーマットを制限するに基づく例です。

私は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"); 
} 
関連する問題