我正在一個非常簡單的程序上工作。我想要做的是在按下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");
}
}
}
}
如果你正在尋找好的學習材料,我建議斯坦福講座(youtube上的視頻)。這位教授非常擅長解釋Java,並且有很大一部分專門用於圖形學。 – didierc 2013-04-04 08:40:01