帮助尝试增加和减少按钮,增加和减少面板上的数字只是不起作用,我试图获得actionPerformed并且动作监听器不工作可能有人给我指导`
public class IncrDecPanel extends JPanel
{
private int INITIAL_NUMBER = 50;
private JButton Incr, Dec;
private JLabel label;
private JPanel ButtonPanel;
private int number;
public IncrDecPanel()
{
number = INITIAL_NUMBER;
label = new JLabel(String.valueOf(number));
Incr = new JButton("Incr");
Dec = new JButton("Dec");
JButton IncrButton = new JButton("Increment");
IncrButton.addActionListener (new IncrListener());
JButton DecButton = new JButton("Decrement");
DecButton.addActionListener(new DecListener());
ButtonPanel = new JPanel();
ButtonPanel.setPreferredSize(new Dimension(200, 40));
ButtonPanel.setBackground(Color.red);
ButtonPanel.add(Incr);
ButtonPanel.add(Dec);
12
setPreferredSize(new Dimension(200, 80));
setBackground(Color.black);
add(label);
add(ButtonPanel);
}
private class IncrListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
label.setText (Integer.toString (++number));
}
}
private class DecListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
label.setText (Integer.toString (--number));
}
}
}`
答案 0 :(得分:0)
您将ActionListeners
添加到错误的按钮。
您已创建按钮Incr
和Dec
,然后将您的听众添加到IncrButton
和DecButton
,然后再添加Incr
和Dec
你的JPanel。只需在创建后将听众分配到第一个按钮,例如:
Incr = new JButton("Incr");
Dec = new JButton("Dec");
Incr.addActionListener(new IncrListener());
Dec.addActionListener(new DecListener());
希望这会有所帮助。 :)