【问题标题】:JOption call method from String text?来自字符串文本的 JOption 调用方法?
【发布时间】:2014-05-18 22:48:17
【问题描述】:

我不太确定如何问这个问题,但就是这样。请查看我的代码(为方便起见,我将其缩写,不要担心“Sam”是临时的)

public class JeopardyGUI_Main11 extends javax.swing.JFrame {

/**
 * Creates new form JeopardyGUI_Main
 */

public JeopardyGUI_Main11() {
    initComponents();
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
public void info(){
           String[] am = new String[25];
   String[] sp = new String[25];
   String[] mu = new String[25];
   String[] spe = new String[25];
   String[] tv = new String[25];
   String[] mo = new String[25];

   String[] ama = new String[25];
   String[] spa = new String[25];
   String[] mua = new String[25];
   String[] spea = new String[25];
   String[] tva = new String[25];
   String[] moa = new String[25];

   am[0] = "Sam";ama[0] = "Sam";
   am[1] = "Sam";ama[1] = "Sam";
   ...
   am[23] = "Sam";ama[23] = "Sam";
   am[24] = "Sam";ama[24] = "Sam";

   mu[0] = "Sam";mua[0] = "Sam";
   mu[1] = "Sam";mua[1] = "Sam";
   ...
   mu[23] = "Sam";mua[23] = "Sam";
   mu[24] = "Sam";mua[24] = "Sam";



   spe[0] = "Sam";spea[0] = "Sam";
   spe[1] = "Sam";spea[1] = "Sam";
   ...
   spe[23] = "Sam";spea[23] = "Sam";
   spe[24] = "Sam";spea[24] = "Sam";


   tv[0] = "Sam";tva[0] = "Sam";
   tv[1] = "Sam";tva[1] = "Sam";
  ...
   tv[23] = "Sam";tva[23] = "Sam";
   tv[24] = "Sam";tva[24] = "Sam";


   sp[0] = "Sam";spa[0] = "Sam";
   sp[1] = "Sam";spa[1] = "Sam";
  ...
   sp[23] = "Sam";spa[23] = "Sam";
   sp[24] = "Sam";spa[24] = "Sam";


   mo[0] = "Sam";moa[0] = "Sam";
   mo[1] = "Sam";moa[1] = "Sam";
   ...
   mo[23] = "Sam";moa[23] = "Sam";
   mo[24] = "Sam";moa[24] = "Sam";

    int random_int = (int) (Math.random() * ( 0 - 24 ));  

  String am_qu = am[random_int];
  String am_an = ama[random_int];  

  String sp_qu = sp[random_int];
  String sp_an = spa[random_int];

  String mu_qu = mu[random_int];
  String mu_an = mua[random_int];

  String spe_qu = sp[random_int];
  String spe_an = spa[random_int];

  String tv_qu = tv[random_int];
  String tv_an = tva[random_int];

  String mo_qu = mo[random_int];
  String mo_an = moa[random_int];
  }

    pack();
    setLocationRelativeTo(null);
}// </editor-fold>                        

private void sp1ActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
}                                                                     


private void sp2ActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
}                                   

private void am1ActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
    Object[] options = {"Yes, please",
                "No way!"};
int n = JOptionPane.showOptionDialog(null,
""+am_qu,          <-------------------------------------AREA IN QUESTION
"",
JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,     //do not use a custom Icon
options,  //the titles of buttons
options[0]); //default button title



}                                   

private void mo1ActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
}                                   

private void am1MouseClicked(java.awt.event.MouseEvent evt) {                                 
    // TODO add your handling code here:
}                                

/**
 * @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(JeopardyGUI_Main11.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(JeopardyGUI_Main11.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(JeopardyGUI_Main11.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(JeopardyGUI_Main11.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 JeopardyGUI_Main11().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton am1;
private javax.swing.JButton am2;
private javax.swing.JButton am3;
...
private javax.swing.JButton am4;
private javax.swing.JButton am5;

// End of variables declaration                   


}

在“有问题的区域”我输入的是问题的位置。 optionDialog 框需要一个字符串作为文本,但我想用“public void info()”中的字符串替换它,该字符串将使用 Math.Random 随机化。

所以,如果我要正确运行 optionDialog,它应该显示为“Sam”(在中间的文本区域)。

对不起,如果我没有说清楚,请问有什么问题,我将等待回复,谢谢!

【问题讨论】:

  • 在您的 info 方法结束时,您有 12 个随机字符串,您是说您希望其中一个字符串成为您的 JOPtionPane 中的消息吗?
  • 是的,它们是随机发生器,我希望结果显示在 JOptionPane 的 ("") 中,使其成为“正文”。
  • 是的,但是您希望这 12 个字符串中的 1 个随机出现,还是全部出现在 ("") 中?
  • 是其中之一,因为我将使用其他随机字符串分配不同的按钮。基本上是随机化每个按钮的危险问题。 6 列不同的主题,每列有 5 个按钮选择,按钮将显示一个随机问题(我将输入代替“Sam”),然后不允许用户输入答案并将其与答案进行比较字符串。感谢您的宝贵时间!
  • 这里的主要问题是变量作用域。无论您调用该方法多少次来初始化这些变量,它们都只会持续到方法结束。考虑将他们居住的地方搬到一块田地。

标签: java string swing user-interface joptionpane


【解决方案1】:

下面是一个基本示例,说明了您可以更高效地构建程序的不同方式:

public class SO {
public static void main(String[] args) throws ClassNotFoundException{
    getinfo();//Set the random question and answer

    Object[] options = {"Yes, please", "No way!"};
    int n = JOptionPane.showOptionDialog(null,
            SO.question,//Reference the question set
            "",
            JOptionPane.YES_NO_OPTION,
            JOptionPane.PLAIN_MESSAGE,
            null,     //do not use a custom Icon
            options,  //the titles of buttons
            options[0]); //default button title

    JOptionPane.showMessageDialog(null, SO.answer);
}

public static void getinfo(){ //Will set question and answer
    int category = new Random().nextInt(2 - 0);//Random number to get a category
    int choice = new Random().nextInt(2 - 0);//Random to get a selection

    SO.question = questions[category][choice];//Get question
    SO.answer = answers[category][choice];//Answer is located in same position in answers array
}

/*Each category is represented by a seperate array within the questions
 * 2 dimensional array.  These are declared as static fields or 'Global fields'
 * This way they are easily accessible and only initialised once
 */
private static String[][] questions = new String[][]{ 
    {"Question 1, category 1", "Question 2 category 1"},//questions[0][*] for one category 
    {"Question 1 category 2", "Question 2 category 2"}//questions[1][*] on another category
};

/*The answers array mirrors the other array so each answer in this 2D array 
 * is in the same position as the relevant question in the questions array
 * 
 */
private static String[][] answers = new String[][]{ 
    {"Answer 1 category 1", "Answer 2 category 1"}, //answers[0][*] for questions [0][*]  
    {"Answer 1 category 2", "Answer 2 category 2"}//answers[1][*] for questions [1][*]
};

//These will each hold a question and an answer
private static String question;
private static String answer;

}

我已经把它缩小了很多,所以你可以感受一下它是如何工作的。向您建议的“全局变量”位于底部。这有望让您获得 JOPtionPane 所需的问题和答案,并防止您的阵列不断重新初始化。

再一次,如果不确定,请回复我,我会看看我能做什么。 祝你好运!

【讨论】:

  • 你真的很接近回答我(也有这样的细节!)但这是我的目标,String am 是一个包含关于 (am)erica 的问题的类别,String ama 有所有问题的答案都按顺序(am)erica(a)nswer。整个程序应该是一个危险的游戏,有不同的类别和对应的答案。
  • @Magiichalo 我已经重新调整了我的答案,以证明您可以实现我认为您所追求的目标,看看它是否有帮助
  • 我在一个空白类中尝试了它并且它可以工作,现在将它修复到我现有的代码中。谢谢你的一百万天才!
  • 还有一件事,它不允许我添加额外的问题。
【解决方案2】:

我不确定我是否理解您的程序,但我假设您尝试在 info() 方法中实例化一些 String,然后在 am1ActionPerformed() 方法中使用这些 String 的值。现在,我也不太了解您的问题,但我在您的代码中看到的是范围问题。

您尝试在 am1ActionPerformed() 方法中访问的字符串 am_qu 不存在,因为它是在 info() 方法中创建和销毁的。如果您想在其他方法中使用它,请尝试将其设为全局变量。


更新

找不到符号的原因是因为作用域不存在。我不知道您所说的“我添加了 Global 而不是 void info()”是什么意思,但是您创建全局变量的方式是将其声明在类内部但在其他所有内容之外;

考虑以下几点:

public class TempClass{
    public String globVar;       //global variable
    public void method1(){
        globVar ="hello";        // Same global variable
    }
    public void method2(){
        globVar ="world!";        // same here too
    }
}

这里同一个变量 globVar 可以被 method1() 和 method2() 访问并且可以被两者修改。在 method1 之后调用 method2() 将替换 globVar 的值 现在考虑一个局部变量。

public class TempClass{

    public void method1(){
        String localVar;       //local variable is declared
        localVar = "Hello";    //value assigned to local Variable
    }                          //localVar is destroyed

    public void method2(){
        String localVar;       // different localVar to method1
        localVar = "world";    // value assigned to localVar
    }                          // localVar destroyed
}

这里使用了两个不同的变量,尽管它们的名称相同。不仅如此,当方法退出时它们会被销毁并且不能在其他任何地方使用。 最后考虑一下你目前在做什么

public class TempClass{

    public void method1(){
        String localVar;           //local variable is declared
        localVar = "Hello World";  //value assigned to local Variable
    }                              //localVar is destroyed

    public void method2(){
        System.out.println(localVar);  // Error. localVar does not exist
    }                                  
}

所以你可以看到你的变量在你使用它之前就被破坏了。您需要在全局范围内声明它。

【讨论】:

  • 我添加了Global 而不是void info(),这没问题,但现在am[0] = "Sam";ama[0] = "Sam"; 都给出了错误,找不到符号。
  • 感谢您的选择。我很感激。
猜你喜欢
  • 1970-01-01
  • 2013-05-26
  • 2023-03-23
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
  • 2019-09-24
  • 1970-01-01
  • 2020-02-27
相关资源
最近更新 更多