我可以使用 for 循环在 Java 中创建对象吗?

时间:2021-02-23 20:53:08

标签: java loops swing jframe jbutton

我可以在一个循环中初始化多个对象吗?

这是我的代码片段的样子。如您所见,它变得难以一目了然并且占用太多空间。

我希望能够在一个 for 循环中创建按钮,然后在另一个 for 循环中进行修改。

public class MyFrame extends JFrame {
    MyFrame() {

        JButton button1 = new JButton();
        JButton button2 = new JButton();
        JButton button3 = new JButton();
        JButton button4 = new JButton();
        JButton button5 = new JButton();
        JButton button6 = new JButton();
        JButton button7 = new JButton();
        JButton button8 = new JButton();
        JButton button9 = new JButton();
        JButton button0 = new JButton();


        button1.setBounds(60, 60, 50, 50);
        button2.setBounds(120,60,50,50);
        button3.setBounds(180,60,50,50);
        button4.setBounds(60,120,50,50);
        button5.setBounds(120,120,50,50);
        button6.setBounds(180,120,50,50);
        button7.setBounds(60,180,50,50);
        button8.setBounds(120,180,50,50);
        button9.setBounds(180,180,50,50);
        button0.setBounds(120,240,50,50);

    }
}

2 个答案:

答案 0 :(得分:3)

是的,您可以使用 for 循环来创建按钮。

这是我创建的 GUI。

Ten Button GUI

在创建 GUI 时使用绝对定位 (setBounds) 不是一个好主意。您应该使用 Swing layout managers

我使用 GridLayout 来定位按钮。

这是完整的可运行代码。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TenButtonGUI implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new TenButtonGUI());
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Ten Button GUI");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createMainPanel(), BorderLayout.CENTER);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new GridLayout(0, 3, 5, 5));
        panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        for (int i = 0; i < 11; i++) {
            if (i == 9) {
                JLabel label = new JLabel(" ");
                panel.add(label);
            } else {
                JButton button = new JButton();
                button.setPreferredSize(new Dimension(50, 50));
                panel.add(button);
            }
        }

        return panel;
    }

}

答案 1 :(得分:1)

你可以这样做:

List<JButton> buttons = new ArrayList<>();
int[][] bounds = {{60, 60, 50, 50}, {120,60,50,50}}; //add more bound quadruplets

// iterating over the values in the bounds array
Arrays.asList(bounds).forEach(v -> {
    JButton button = new JButton();
    button.setBounds(v[0], v[1], v[2], v[3]);
    buttons.add(button);
});

最后,您会在 buttons 列表中找到您的按钮。

相关问题