【问题标题】:Incrementing/Decrementing using JPanel and JButton使用 JPanel 和 JButton 递增/递减
【发布时间】:2022-06-29 01:42:59
【问题描述】:

我已经尝试解决这个问题已经有一段时间了,但我无法弄清楚我在这里做错了什么

代码如下:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PushCounterPanelMath extends JPanel
{
    private int count;
    private JButton inc;
    private JButton dec;
    private JLabel label;

    public PushCounterPanelMath()
    {
        count = 0;
        inc = new JButton("Increment");
        dec = new JButton("Decrement");
        label = new JLabel();
        inc.addActionListener(new ButtonListener());
        dec.addActionListener(new ButtonListener());
        add(inc);
        add(dec);
        add(label);
        setBackground(Color.cyan);
        setPreferredSize(new Dimension(300, 40));
    }

    private class ButtonListener implements ActionListener
    {
        
        public void actionPerformed(ActionEvent event)
        {
            
            count++;
            label.setText("Value: " + count);
            if(event.equals(dec))
                count--;
            label.setText("Value "  + count);
        }
    }
}

我正在尝试使用两个按钮来增加和减少值,但由于某种原因,无论我按“增量”还是“减量”,它只会增加它 我该如何解决这个问题?

【问题讨论】:

    标签: java swing jpanel jbutton


    【解决方案1】:

    event.equals(dec) 永远不会是真的; ActionEvent 永远不等于 JButton。但是你可以使用 event.getSource();

            if(event.getSource().equals(dec))
                count--;
            else count++;
            label.setText("Value "  + count);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      • 2020-12-11
      • 1970-01-01
      相关资源
      最近更新 更多