[英]How to use JOptionPane to input data into an array
我如何創建一個數組,我希望一個數組中有8個值,但用戶輸入了它們?
這就是我到目前為止
import javax.swing.JOptionPane;
public class Southside Report {
public static void main(String[] args) {
int FINAL MIN_STAFF = 7;
int total_staff = 0;
double[] num_students = 8;
您應該將array
聲明為:
double[] num_students = new double[8];
並且int FINAL MIN_STAFF = 7;
應該是FINAL int MIN_STAFF = 7;
然后,您可以使用JOptionPane
通過以下方式分配值:
int i=0;
while(i<8){
try{
num_students[i]=Double.parseDouble(JOptionPane.showInputDialog("Enter Number:"));
i++;
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Please enter valid number");
}
}
看看JOptionPane 。 選項窗格非常可定制。 除了您的代碼無法編譯外,我認為您只希望用戶在一個對話框中輸入8個文本,並且可以使用optionPane進行幾乎沒有自定義的操作,例如下面的示例。
import java.util.ArrayList;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JOptionPaneTest {
public static final int OPTIONS = 8;
private List<JTextField> textfields = new ArrayList<>(OPTIONS);
private JPanel panel;
public JOptionPaneTest(){
panel = new JPanel();
for(int i =0;i< OPTIONS;i++){
JTextField textfield = new JTextField(5);
textfields.add(textfield);
panel.add(new JLabel(Integer.toString(i+1)+": "));
panel.add(textfield);
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
JOptionPaneTest example = new JOptionPaneTest();
int result = JOptionPane.showConfirmDialog(null, example.panel,
"Please Enter Values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
for(JTextField textfield : example.textfields){
System.out.println(textfield.getText());
}
}
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
並輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.