如何通过for循环更改标签文本?

时间:2017-03-10 00:34:01

标签: java swing for-loop

我有这个代码创建一个带有九个按钮和一个标签的面板,当点击一个按钮时,标签会发生变化,以便点击该女巫编号。

我想要做的是弄清楚如何用for循环替换actionPerformed中的if函数,以便它做同样的事情?

这是我的代码:

package zadatak;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class forPetlja {

    private JFrame mojOkvir;
    private JPanel p1, p2;
    private JLabel txtLabela;

    public forPetlja() {
        pripremiGUI();
    }

    private void pripremiGUI() {
        //okvir
        mojOkvir = new JFrame("Primena 2 panela");
        mojOkvir.setSize(400, 250);
        mojOkvir.setLocationRelativeTo(null);
        mojOkvir.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //paneli
        p1 = new JPanel();
        p1.setBorder(BorderFactory.createTitledBorder("JButton"));
        p1.setLayout(new GridLayout(3, 3));

        p2 = new JPanel();
        p2.setBorder(BorderFactory.createTitledBorder("JLabel i Panel p1"));
        p2.setLayout(new BorderLayout());

        //labela
        txtLabela = new JLabel("Prikazi koje je dugme kliknuto.");
    }

    private void prikaziGUI() {
        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() instanceof JButton) {
                    txtLabela.setText("Kliknut je broj " + e.getActionCommand());
                }
            }
        };

        JButton[] niz = new JButton[9];

        for (int i = 0; i < niz.length; i++) {
            niz[i] = new JButton(String.valueOf(i));
            niz[i].addActionListener(listener);

            p1.add(niz[i]);
        }

        p2.add(txtLabela, BorderLayout.WEST);
        p2.add(p1, BorderLayout.EAST);
        mojOkvir.add(p2);
        mojOkvir.setVisible(true);
    }

    public static void main(String[] args) {
        forPetlja objekatPrikaziGUI = new forPetlja();
        objekatPrikaziGUI.prikaziGUI();

    }
}

0 个答案:

没有答案