我正在开发一个非常简单的程序。我想要做的是在按下 firstButton 时添加一个新圆圈(在确保我的事件正常工作后,程序当前是这样的)。
我知道我在paintComponent
某个地方需要一种方法,并且可能需要使用repaint
但不确定如何放入这些方法。
帮助将不胜感激,谢谢:
public class aGameForBella extends JPanel {
private int count1 = 0, count2 = 0, count3 = 0;
JButton firstButton, secondButton, thirdButton;
JLabel firstLabel, secondLabel, thirdLabel;
JPanel optionPanel;
//constructor method
public aGameForBella() {
//create components
optionPanel = new JPanel();
firstButton = new JButton("Button option number one");
firstLabel = new JLabel("You pushed the first button: " + count1
+ " times");
secondButton = new JButton("Button option number two");
secondLabel = new JLabel("You pushed the second button: " + count2
+ " times");
thirdButton = new JButton("Button option number three");
thirdLabel = new JLabel("You pushed the third button: " + count3
+ " times");
//add listeners
firstButton.addActionListener(new ButtonListener());
secondButton.addActionListener(new ButtonListener());
thirdButton.addActionListener(new ButtonListener());
//add panels
add(optionPanel);
//add components to panels
optionPanel.add(firstButton);
optionPanel.add(firstLabel);
optionPanel.add(secondButton);
optionPanel.add(secondLabel);
optionPanel.add(thirdButton);
optionPanel.add(thirdLabel);
//set size of things
optionPanel.setPreferredSize(new Dimension(200, 200));
setPreferredSize(new Dimension(250, 500));
setBackground(Color.cyan);
}
//inner class
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == firstButton) {
count1++;
firstLabel.setText("You pushed the first button: " + count1
+ " times");
} else if (event.getSource() == secondButton) {
count2++;
secondLabel.setText("And you pushed the second button: "
+ count2 + " times");
} else if (event.getSource() == thirdButton) {
count3++;
thirdLabel.setText("And the last button: " + count3 + " times");
}
}
}
}