Brian N
Brian N

Reputation: 21

How to call `setText` on multiple JTextfields?

I want to figure out a way to set the text for multiple JTextfields in just a few lines (preferable one line) of code rather than a new line for every textfield.

I am looking for a way to invoke the setText method on multiple JTextfield values. My code works correctly, but I do not want to write out someField.setText("0.00"); for each JTextfield.

Here is code with the repeated calls that I want to shorten:

JButton btnNewButton_1 = new JButton("Clear");
    btnNewButton_1.setBounds(367, 533, 86, 32);
    btnNewButton_1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnNewButton_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            textIncome.setText("0.00");
            textGrossSalary.setText("0.00");
            textGrossSalary.setText("0.00");
            textHousehold.setText("0.00");
            textFood.setText("0.00");
            textChildren.setText("0.00");
            textBills.setText("0.00");
            textIncidentals.setText("0.00");
            textCredit.setText("0.00");
            textHome.setText("0.00");
            textInvestings.setText("0.00");
            textPets.setText("0.00");
            textTransport.setText("0.00");
            textLifestyle.setText("0.00");
            textTax.setText("0.00");
            textDisposable.setText("0.00");
            textHealthFitness.setText("0.00");
            textGiftsDonations.setText("0.00");

        }

    });

Upvotes: 2

Views: 925

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347194

Put them in a List or an array and iterate over them

For example, create an instance field array which contains the fields which you want to set (to the same value)

private JTextField fields[] = new JTextField[]{
        textIncome,
        textGrossSalary,
        textGrossSalary,
        textHousehold,
        textFood,
        textChildren,
        textBills,
        textIncidentals,
        textCredit,
        textHome,
        textInvestings,
        textPets,
        textTransport,
        textLifestyle,
        textTax,
        textDisposable,
        textHealthFitness,
        textGiftsDonations};

Then when the ActionListener is triggered, iterate over it...

btnNewButton_1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        for (JTextField field : fields) {
            field.setText("0.00");
        }
    }
});

Based on btnNewButton_1.setBounds(367, 533, 86, 32);, I'd advise avoiding using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

Upvotes: 4

Related Questions