我有一个程序,根据选择的单选按钮,可以计算2个变量中的1个。我正在尝试使用getValueJFormattedText字段中获取一个值并将其显示在另一个JFormattedText字段中(最终,我将对该数字进行一些计算)。

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;

public class FutureValueFrame extends JFrame
{
    public FutureValueFrame()
    {
        setTitle("Sample App");
        setSize(400,400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }


    public static void main(String[] args)
    {
        JFrame f = new FutureValueFrame();

        //GUI and BUTTONS
        JRadioButton monthlyRadioButton = new JRadioButton("Monthly Payment");
        JRadioButton loanAmountButton = new JRadioButton("Loan Amount");
        ButtonGroup selection = new ButtonGroup();
        selection.add(monthlyRadioButton);
        selection.add(loanAmountButton);

        JFormattedTextField loanAmountField = new JFormattedTextField(new DecimalFormat("####.##"));
        JFormattedTextField interestRateField = new JFormattedTextField(new DecimalFormat("####.##"));
        JFormattedTextField yearField = new JFormattedTextField(new DecimalFormat("####.##"));
        JFormattedTextField monthlyPaymentField = new JFormattedTextField(new DecimalFormat("####.##"));


        JPanel menuPanel = new JPanel();
        menuPanel.setLayout(new GridLayout(1,2));

        //ACTION LISTENER FOR RADIO BUTTONS
        monthlyRadioButton.addActionListener(new SelectionListener(monthlyRadioButton, loanAmountButton, loanAmountField, monthlyPaymentField));
        loanAmountButton.addActionListener(new SelectionListener(monthlyRadioButton, loanAmountButton, loanAmountField, monthlyPaymentField));

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new GridLayout(1,2));
        topPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        topPanel.add(monthlyRadioButton);
        topPanel.add(loanAmountButton);

        JPanel botPanel = new JPanel();
        botPanel.setLayout(new GridLayout(4,2));

        botPanel.add(new JLabel("Loan Amount:"));
        botPanel.add(loanAmountField);

        botPanel.add(new JLabel("Yearly Interest Rate:"));
        botPanel.add(interestRateField);

        botPanel.add(new JLabel("Number of Years:"));
        botPanel.add(yearField);

        botPanel.add(new JLabel("Monthly Payment:"));
        botPanel.add(monthlyPaymentField);

        JPanel container = new JPanel();
        container.setLayout(new GridLayout(3,1));
        container.add(topPanel);
        container.add(botPanel);
        container.add(menuPanel);

        f.add(container);

        JButton calculateButton = new JButton("Calculate");

        calculateButton.addActionListener(new CalculateMonthlyListener(loanAmountField, interestRateField, yearField, monthlyPaymentField, selection, monthlyRadioButton, loanAmountButton));


        JButton exitButton = new JButton("Exit");
        exitButton.addActionListener(new ExitListener());

        menuPanel.add(calculateButton);
        menuPanel.add(exitButton);

        f.setVisible(true);
        f.setLocationRelativeTo(null);
    }

    class CalculateMonthlyListener implements ActionListener
    {
        private JFormattedTextField loanAmountField;
        private JFormattedTextField monthlyPaymentField;
        private JFormattedTextField interestRateField;
        private JFormattedTextField yearField;
        private double result;
        private ButtonGroup selection;
        private JRadioButton monthlyRadioButton;
        private JRadioButton loanAmountButton;

        public CalculateMonthlyListener (JFormattedTextField loanAmountField,
                                        JFormattedTextField interestRateField,
                                        JFormattedTextField yearField,
                                        JFormattedTextField monthlyPaymentField,
                                        ButtonGroup selection,
                                        JRadioButton monthlyRadioButton,
                                        JRadioButton loanAmountButton)
        {
            this.interestRateField = interestRateField;
            this.yearField = yearField;
            this.loanAmountField = loanAmountField;
            this.selection = selection;
            this.monthlyRadioButton = monthlyRadioButton;
            this.loanAmountButton = loanAmountButton;
            this.monthlyPaymentField = monthlyPaymentField;
        }

        public void actionPerformed(ActionEvent e)
        {
            if (selection.getSelection().equals(monthlyRadioButton.getModel()))
            {
                result  = ((Double) interestRateField.getValue()).floatValue();
                monthlyPaymentField.setValue(new Double(result));
                System.out.println("You selected monthly");
            }
            else
            {
                loanAmountField.setValue(new Double(12.22));
                System.out.println("You selected loan");
            }
        }
    }

    class ExitListener implements ActionListener
    {
        public void actionPerformed(ActionEvent event)
        {
            //f.dispose();
            System.exit(0);
            //System.out.println("You clicked exit");
        }
    }

    class SelectionListener implements ActionListener
    {
        private JRadioButton monthlyRadioButton;
        private JRadioButton loanAmountButton;
        private JFormattedTextField loanAmountField;
        private JFormattedTextField monthlyPaymentField;

        public SelectionListener (JRadioButton monthlyRadioButton,
                                JRadioButton loanAmountButton,
                                JFormattedTextField loanAmountField,
                                JFormattedTextField monthlyPaymentField)
        {
            this.monthlyRadioButton = monthlyRadioButton;
            this.loanAmountButton = loanAmountButton;
            this.loanAmountField = loanAmountField;
            this.monthlyPaymentField = monthlyPaymentField;
        }

        public void actionPerformed(ActionEvent event)
        {
            if(event.getSource() == monthlyRadioButton)
            {
                loanAmountField.setEditable(false);
                monthlyPaymentField.setEditable(true);
            }
            else
            {
                monthlyPaymentField.setEditable(false);
                loanAmountField.setEditable(true);
            }
        }
    }
}

我的问题出现在以下代码片段中:
public void actionPerformed(ActionEvent e) {
    if (selection.getSelection().equals(monthlyRadioButton.getModel())) {
         result  = ((Double) interestRateField.getValue()).floatValue();
         monthlyPaymentField.setValue(new Double(result));
        System.out.println("You selected monthly");
    } else {
        loanAmountField.setValue(new Double(12.22));
        System.out.println("You selected loan");
    }
}

在这里,我正在尝试分配getValue作为结果。我查看了Oracle文档,似乎获得该值的代码只是interestRateField.getValue();,但是当我尝试这样做时,出现了一个错误,说Can't convert object to double,所以我添加了floatValue()并对其进行了强制转换以消除错误。

当我按计算时,它不会在interestRateField中显示来自monthlyPaymentField的输入。

如何使用JFormattedTextField来获取我的值(使用DecimalFormatgetValue中获得),然后将其显示在其他JFormattedTextField中?

最佳答案

略微调整了“气垫船充满鳗鱼”的答案,以使用getValuesetValueJFormattedTextField方法,并跳过手动解析/格式化

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.text.DecimalFormat;

public class FutureValueFrame extends JFrame {
  public static void main( String[] args ) {
    DecimalFormat format = new DecimalFormat( "####.##" );
    //in case you always want to see the 2 fraction digits
    //format.setMinimumFractionDigits( 2 );
    final JFormattedTextField field1 = new JFormattedTextField(
        format );
    final JFormattedTextField field2 = new JFormattedTextField(
        format );
    field1.setColumns( 15 );
    field2.setColumns( 15 );
    JButton btn = new JButton( new AbstractAction( "Multiply by 2" ) {

      @Override
      public void actionPerformed( ActionEvent e ) {
        Number value = ( Number ) field1.getValue();
        if ( value != null ){
          field2.setValue( 2 * value.doubleValue() );
        }
      }
    } );

    JPanel panel = new JPanel();
    panel.add( field1 );
    panel.add( btn );
    panel.add( field2 );
    JOptionPane.showMessageDialog( null, panel );
  }
}

这至少使用了设计时的JFormattedTextField,但仍然具有JFormattedTextField的所有可用性“怪癖”。

the tips4java site上有一个关于improving the JFormattedTextField 的博文,它解决了大部分问题,可能值得一看(尽管我仍然认为可以改进版本,例如,只要输入无效数据以给背景色红色,就可以将背景涂成红色)。用户的视觉提示。)

10-07 12:57