Используйте JRadioButtons для установки двух текстовых полей - PullRequest
1 голос
/ 15 февраля 2011

Очень новый для Java здесь. Как использовать JRadioButton для установки двух разных текстовых полей? Три кнопки:
1,7 на 5,35%
2. 15 при 5,5%
3,30 при 5,75%

Вариант 1 устанавливает для поля 1 значение 7 и для поля 2 значение 5,35
Вариант 2 устанавливает поля от 1 до 15 и от поля 2 до 5,5
Вариант 3 устанавливает для field1 значение 30 и field2 значение 5,75

.

Какой самый быстрый и простой способ написать этот код? Кажется, достаточно просто, но у меня чертовски много времени с JRadioButtons.

Спасибо.

РЕДАКТИРОВАТЬ: Вот код. Похоже, я почти на месте, но я все еще не могу получить переключатели, чтобы поместить данные в поля. Говорит, что мне нужно изменить тип на int, но если я сделаю это, это больше не поле для ввода ...

//import all needed functionality
import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.*;
public class ScrofaniWk3Alt extends JApplet{

/**
 * 
 */
private static final long serialVersionUID = 1L;

/**
 * @param args
 */
    // Declare variables and put code application logic here

    String userInput = null;
    JLabel loanAmountLabel = new JLabel("Loan Amount: ");
    JTextField loanAmount = new JTextField();
    double[] ratesList = {0.0535, 0.055, 0.0575};
    JLabel rateLabel=new JLabel("Interest Rate: ");
    JTextField rate=new JTextField();
    String[] yearsList = {"7","15","30"};
    JLabel yearsLabel=new JLabel("Years of Payment: ");
    JTextField years=new JTextField();
    JRadioButton sevenButton = new JRadioButton("7");
    JRadioButton fifteenButton = new JRadioButton("15");
    JRadioButton thirtyButton = new JRadioButton("30");
    JLabel payLabel=new JLabel("Monthly Payment: ");
    JLabel payment=new JLabel();
    JButton calculate=new JButton("Calculate");
    JButton clear=new JButton("Clear");
    JButton quit=new JButton("Quit");
    JTextArea payments=new JTextArea();
    JScrollPane schedulePane=new JScrollPane(payments);
    Container mortCalc = getContentPane();


    public void init() {
//Configure the radio buttons to input data into fields
    sevenButton.setActionCommand("Radio1");
    fifteenButton.setActionCommand("Radio2");
    thirtyButton.setActionCommand("Radio3");

    ButtonGroup chooseYears = new ButtonGroup();
    chooseYears.add(sevenButton);
    chooseYears.add(fifteenButton);
    chooseYears.add(thirtyButton);
    }

    public void actionPerformed(ActionEvent e) {
    if ("Radio1".equals(e.getActionCommand())) {
        years = 7;
        rate = 5.35;   
    }
    if ("Radio2".equals(e.getActionCommand())) {
        years = 15;
        rate = 5.5;   
    }
    if ("Radio3".equals(e.getActionCommand())) {
        years = 30;
        rate = 5.75;   
    } 


    calculate.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {    
                // Perform the calculation

                double yearsCalc=Integer.parseInt(years.getText())*12;
                double rateCalc=Double.parseDouble(rate.getText())/12;
                double principalCalc=Double.parseDouble(loanAmount.getText());
                double monthlyPayment=principalCalc*Math.pow(1+rateCalc,yearsCalc)*rateCalc/(Math.pow(1+rateCalc,yearsCalc)-1);

                DecimalFormat df = new DecimalFormat("$###,###.##");
                payment.setText(df.format(monthlyPayment));

                // Perform extra calculations to show the loan amount after each subsequent payoff
                double principal=principalCalc;
                int month;
                StringBuffer buffer=new StringBuffer();
                buffer.append("Month\tAmount\tInterest\tBalance\n");
                for (int f=0; f<yearsCalc; f++) {
                month=f+1;
                double interest=principal*rateCalc;
                double balance=principal+interest-monthlyPayment;
                buffer.append(month+"\t"); buffer.append(new String(df.format(principal))+"\t");
                buffer.append(new String(df.format(interest))+"\t"); buffer.append(new String(df.format(balance))+"\n");
                principal=balance;
                }
                payments.setText(buffer.toString());
                } catch(Exception ex) {
                System.out.println(ex);
            }
        }
    });
    clear.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            loanAmount.setText(""); payment.setText(""); payments.setText("");
        }
    });
    quit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(1);
        }
    });     
    //Config GUI
    JPanel panelMort=new JPanel();
    panelMort.setLayout(new GridLayout(5,2));
    panelMort.add(loanAmountLabel);
    panelMort.add(loanAmount);  
    panelMort.add(new Label());
    panelMort.add(sevenButton);
    panelMort.add(fifteenButton);
    panelMort.add(thirtyButton);
    panelMort.add(yearsLabel);
    panelMort.add(years);
    panelMort.add(rateLabel);
    panelMort.add(rate);
    panelMort.add(payLabel);
    panelMort.add(payment);

    JPanel buttons=new JPanel();
    buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
    buttons.add(calculate); buttons.add(clear); buttons.add(quit);

    JPanel panelMort2=new JPanel();
    panelMort2.setLayout(new BoxLayout(panelMort2, BoxLayout.Y_AXIS));
    panelMort2.add(panelMort); panelMort2.add(buttons);

    mortCalc.add(BorderLayout.NORTH, panelMort2);
    mortCalc.add(BorderLayout.CENTER, schedulePane);
}
public static void main(String[] args) {
    JApplet applet = new ScrofaniWk3Alt();
    JFrame frameMort = new JFrame("ScrofaniWk3Alt");
    frameMort.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frameMort.getContentPane().add(applet);
    frameMort.setSize(500,1000);

    frameMort.setResizable(true);
    frameMort.setVisible(true);

    applet.init();
    applet.start();

}
}

Ответы [ 2 ]

0 голосов
/ 15 февраля 2011
// put these where you define your buttons
radio1.setActionCommand("RADIO1");
radio2.setActionCommand("RADIO2");
radio3.setActionCommand("RADIO3");



// add this to your actionPerformed method
public void actionPerformed(ActionEvent e) {
    if ("RADIO1".equals(e.getActionCommand())) {
        field1 = 7;
        field2 = 5.35;   
    }
    if ("RADIO2".equals(e.getActionCommand())) {
        field1 = 15;
        field2 = 5.5;   
    }
    if ("RADIO3".equals(e.getActionCommand())) {
        field1 = 30;
        field2 = 5.75;   
    }    
} 
0 голосов
/ 15 февраля 2011

Прочтите раздел из учебника по Swing на Как использовать радиокнопки .По сути, вы добавляете ActionListener к каждой кнопке, а затем устанавливаете значение в текстовых полях.

Если вам нужна дополнительная помощь, опубликуйте SSCCE , который показывает, что вы пытались после прочтения учебника.

...