我的循环和“BorderLayout”有问题。当我使用驱动程序编译和运行它时,似乎 add.west(etc) 被正在进行的 add.west 覆盖。我只剩下“南”面板中的第 9 个组件,“东”和“西”完全是空的。如果我将“for (int i=0;i<8;i++){”更改为:“for (int i=0;i<2;i++){”我只得到所需 9 中的第二个元素“西”面板。谁能告诉我为什么。原谅我的无知。我是初学者。
谢谢你。乔
这大概是它的样子:
(WEST) (EAST)
btn0, label0, label0 btn4, label4, label4
btn1, label1, label1 btn5, label5, label5
btn2, label2, label2 btn6, label6, label6
btn3, label3, label3 btn7, label7, label7
(SOUTH)
btn8, label8, label8
//代码从这里开始:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.NumberFormat;
public class CoinPanel extends JPanel{
private JButton buttons[] = new JButton[9];
private JLabel multiplySign[] = new JLabel[9];
private JLabel coinCount[] = new JLabel[9];
String [] names= {"1c", "2c", "5c", "10c", "20c", "50c", "€1", "€2", "Reset"};
int [] values= {1, 2, 5, 10, 20, 50, 100, 200, 0};
public CoinPanel(){
for (int i=0; i<8; i++){
buttons[i] = new JButton(names[i]);
buttons[i].addActionListener(new BtnListener());
coinCount[i] = new JLabel("0", JLabel.CENTER);
coinCount[i].setBorder(BorderFactory.createLineBorder(Color.black));
multiplySign[i] = new JLabel ("x", JLabel.CENTER);
//从这里布局的东西:
setLayout (new BorderLayout());
JPanel west= new JPanel();
west.setBackground(Color.BLACK);
JPanel east= new JPanel();
east.setBackground(Color.RED);
JPanel south= new JPanel();
south.setBackground(Color.BLUE);
if(i<4){
west.add (buttons[i]);
west.add (multiplySign[i]);
west.add (coinCount[i]);
}
else if(i<8){
east.add (buttons[i]);
east.add (multiplySign[i]);
east.add (coinCount[i]);
}
else{
multiplySign[i].setText("TOTAL");
south.add (multiplySign[i]);
south.add (coinCount[i]);
south.add (buttons[i]);
}
add(west, BorderLayout.WEST);
add(east, BorderLayout.EAST);
add(south, BorderLayout.SOUTH);
}
setPreferredSize (new Dimension(450,300));
}
//到这里^^^
private class BtnListener implements ActionListener{
public void actionPerformed (ActionEvent event){
String [] text = new String[9];
int [] intArray = new int [9];
double sum =0;
for (int i=0; i<(intArray.length-1); i++){
if(event.getSource() == buttons[i]){
text[i] = coinCount[i].getText();
intArray[i]=Integer.parseInt(text[i]);
intArray[i] = ((intArray[i]) +1);
coinCount[i].setText(intArray[i] + "");
}
if(event.getSource() == buttons[8]){
coinCount[i].setText("0");
}
sum += (Integer.parseInt(coinCount[i].getText())*values[i]);
NumberFormat nf = NumberFormat.getCurrencyInstance();
coinCount[8].setText(nf.format(sum/100)+"");
}
}
}
}
//这是驱动程序:
import javax.swing.*;
public class CoinSorter{
public static void main(String[] args){
JFrame frame = new JFrame ("Coin Counter Example");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
CoinPanel panel = new CoinPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}