一个JButton根据用户输入调用成员函数

时间:2012-08-05 21:30:42

标签: java swing jbutton jradiobutton

鉴于GUI应用程序,用户将选择两个单选按钮之一,JRadioButton aJRadioButton b。根据他的选择,他将输入不同的输入。但是,要计算公式,他将点击常规按钮JButton c

然而,当在ActionListener中调用两个以上的成员函数时会出现问题。


      c = new JButton( "c" );
      c.addActionListener( new ActionListener() {
        @Override
        public void actionPerformed( ActionEvent e ) {
          cActionPerformed( e );
        }
      });

ActionEvent内,我们有,


    public void cActionPerformed( ActionEvent ev ) {
      try {
        double f = foo.blah( x, y );
        double b = bar.meh( y, z );
      }
      catch( NumberFormatException e ) {
        JOptionPane.showConfirmDialog(
        null, "Error message.", "Error", JOptionPane.CANCEL_OPTION
        );
      }
    }

但是,程序只在调用堆栈中向下一级,返回catch异常对话框。如何设置,以便当用户按下按钮c时,根据是否选择ab,他分别获得fb

3 个答案:

答案 0 :(得分:0)

您可以使用从getSource()继承的EventObject方法来区分事件的来源。

示例:

  public void actionPerformed(ActionEvent event) {
    if (event.getSource() == button1) {
      setSize(300, 200);
      doLayout();
    } else if (event.getSource() == button2) {
      setSize(400, 300);
      doLayout();
    } else if (event.getSource() == button3) {
      setSize(500, 400);
      doLayout();
    }

答案 1 :(得分:0)

您可以使用单选按钮的isSelected()选项。

JRadioButton f = new JRadioButton();
JRadioButton b = new JRadioButton();

public void cActionPerformed( ActionEvent ev ) {
      try {
        if(f.isSelected()){

            double f = foo.blah( x, y );

         } else if(b.isSelected()){

            double b = bar.meh( y, z );

         } else { // If none is selected
            // Do something
         }
      }
      catch( NumberFormatException e ) {
        JOptionPane.showConfirmDialog(
        null, "Error message.", "Error", JOptionPane.CANCEL_OPTION
        );
    }
}

答案 2 :(得分:0)

程序进入catch块的问题与确定选择了哪个单选按钮无关。它可以进入catch块的唯一方法是抛出NumberFormatException。可以抛出NumberFormatException的唯一方法是来自foo.blah( x, y );bar.meh( y, z );

所以 - 你需要弄清楚为什么你的函数首先抛出异常。然后你可以申请La bla bla的答案。

确定错误发生位置的一个好方法是在e.printStackTrace()中使用catch。这将打印到控制台输出的堆栈跟踪,指向导致问题的确切代码行。

相关问题