我有这个
buttons[0].setBounds(12, 161, 96, 25); // Numerical 0
buttons[1].setBounds(12, 50, 42, 25); // Numerical 1
buttons[2].setBounds(66, 50, 42, 25); // Numerical 2
buttons[3].setBounds(120, 50, 42, 25); // Numerical 3
buttons[4].setBounds(12, 87, 42, 25); // Numerical 4
buttons[5].setBounds(66, 87, 42, 25); // Numerical 5
buttons[6].setBounds(120, 87, 42, 25); // Numerical 6
buttons[7].setBounds(12, 124, 42, 25); // Numerical 7
buttons[8].setBounds(66, 124, 42, 25); // Numerical 8
buttons[9].setBounds(120, 124, 42, 25); // Numerical 9
buttons[10].setBounds(174, 124, 50, 62);// Equals button (=)
buttons[11].setBounds(174, 50, 110, 25);// DEL Button (DEL)
buttons[12].setBounds(120, 161, 42, 25);// DOT Button (.)
buttons[13].setBounds(174, 87, 50, 25); // MINUS Button(-)
buttons[14].setBounds(234, 87, 50, 25); // PLUS Button (+)
buttons[15].setBounds(236, 124, 50, 25);// PUTA Button (*)
buttons[16].setBounds(236, 161, 50, 25);// DJEL Button (/)
我想优化它。这就是我如何管理使用数组添加项目以及为其他东西添加for循环。
JButton [] buttons = new JButton [17];
String [] btnCommands = {"0","1","2","3","4","5","6","7","8","9","=","DEL",".","-","+","*","/"};
for (int i = 0;i < btnCommands.length;i++) {
buttons[i] = new JButton(btnCommands[i]);
}
我如何为setBounds做一个4维数组?
int [][][][] bounds = {{{{}}}};
如何初始化和使用它?
答案 0 :(得分:1)
我会使用JButton.setBounds(Rectangle)
方法,而是使用Rectangles
数组。
String[] btnCommands = {"0","1","2","3","4","5","6","7","8","9","=","DEL",".","-","+","*","/"};
Rectangle[] bounds = {
new Rectangle(12, 161, 96, 25), // Numerical 0
new Rectangle(12, 50, 42, 25), // Numerical 1
new Rectangle(66, 50, 42, 25), // Numerical 2
new Rectangle(120, 50, 42, 25), // Numerical 3
new Rectangle(12, 87, 42, 25), // Numerical 4
new Rectangle(66, 87, 42, 25), // Numerical 5
new Rectangle(120, 87, 42, 25), // Numerical 6
new Rectangle(12, 124, 42, 25), // Numerical 7
new Rectangle(66, 124, 42, 25), // Numerical 8
new Rectangle(120, 124, 42, 25), // Numerical 9
new Rectangle(174, 124, 50, 62),// Equals button (=)
new Rectangle(174, 50, 110, 25),// DEL Button (DEL)
new Rectangle(120, 161, 42, 25),// DOT Button (.)
new Rectangle(174, 87, 50, 25), // MINUS Button(-)
new Rectangle(234, 87, 50, 25), // PLUS Button (+)
new Rectangle(236, 124, 50, 25),// PUTA Button (*)
new Rectangle(236, 161, 50, 25),// DJEL Button (/)
};
JButton[] buttons = new JButton[17];
for (int i = 0;i < btnCommands.length;i++) {
JButton b = new JButton(btnCommands[i]);
b.setBounds(bounds[i]);
buttons[i] = b;
}
答案 1 :(得分:0)
我认为你不需要4维阵列。您可能需要一个二维数组,我们第二个维度中有4个条目,每个绑定一个。
所以你会:
int [][] bounds = {{12, 161, 96, 25}, {12, 50, 42, 25}, ... }
你会像以下一样使用它:
buttons[0].setBounds(bounds[0][0], bounds[0][1], bounds[0][2], bounds[0][3]);
在循环中,只需将第一个维度替换为i
,并保持对其他维度的访问权限。