如何在阵列中制作Jpanel?

时间:2018-05-06 12:41:25

标签: java jpanel

我不太喜欢编写代码的方式,我知道编写的方式很糟糕,所以有没有办法以更简单的方式编写代码?也许通过制作一个数组并循环通过?

private JPanel pnl1; 
private JPanel pnl2; 
private JPanel pnl3; 
private JPanel pnl4; 
private JPanel pnl5; 

public void createGUI() {
    setSize(WIDTH, HEIGHT);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());
    //Panel related code will go here
    pnl1 = createPanel(Color.blue);
    pnl2 = createPanel(Color.black);
    pnl3 = createPanel(Color.cyan);
    pnl4 = createPanel(Color.green);
    pnl5 = createPanel(Color.darkGray);
    this.getContentPane().add(pnl1, BorderLayout.EAST);
    this.getContentPane().add(pnl2, BorderLayout.WEST);
    this.getContentPane().add(pnl3, BorderLayout.SOUTH);
    this.getContentPane().add(pnl4, BorderLayout.CENTER);
    this.getContentPane().add(pnl5, BorderLayout.NORTH);

    repaint();
    this.setVisible(true);
}

private JPanel createPanel(Color c) {
    //Create a JPanel object and store it in a local var
    //set the background colour to that passed in c
    //Return the JPanel object
    JPanel jp = new JPanel();
    jp.setBackground(c);
    return jp;
}

谢谢

2 个答案:

答案 0 :(得分:0)

当然可以使用数组和循环重写代码。

createGUI()方法中,您可以执行以下操作:

Color[] colors = {
        Color.blue, Color.black, Color.cyan, Color.green, Color.darkGray
};
Object[] constraints = {
        BorderLayout.EAST, BorderLayout.WEST, BorderLayout.SOUTH, BorderLayout.CENTER, BorderLayout.NORTH
};
for (int i = 0; i < 5; i++) {
    JPanel panel = createPanel(colors[i]);
    this.getContentPane().add(panel, constraints[i]);
}

但正如其他人已经评论过的那样:根据你的目标, 这可能是也可能不是改善代码的最佳选择。

答案 1 :(得分:0)

如何使用 import java.util.ArrayList;

public void createGUI() {
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        //Panel related code will go here

        ArrayList<JPanel> array = new ArrayList<JPanel>();
        for(int i=1; i<=5; i++){
            array.add(new JPanel());

            switch(i){
                case 1: this.getContentPane().add(array.get(i).setBackground(Color.blue), BorderLayout.EAST);
                break;
                case 2: this.getContentPane().add(array.get(i).setBackground(Color.black), BorderLayout.WEST);
                break;
                case 3: this.getContentPane().add(array.get(i).setBackground(Color.cyan), BorderLayout.SOUTH);
                break;
                case 4: this.getContentPane().add(array.get(i).setBackground(Color.green), BorderLayout.CENTER);
                break;
                case 5: this.getContentPane().add(array.get(i).setBackground(Color.darkGray), BorderLayout.NORTH);
                break;
            }
        }

        repaint();
        this.setVisible(true);
    }