【问题标题】:I need to make a button which text will change depending of an integer我需要制作一个按钮,该按钮的文本将根据整数而改变
【发布时间】:2022-01-18 23:12:42
【问题描述】:

我首先需要按钮的文本为 16。当按钮被点击时,它需要 16 到一半,当它被点击时,它一次又一次地一半,当它到达 1 时,它需要保持为 1。

int n=16;
        JButton button4 = new JButton(String.valueOf(n));
        frame.add(button4);
        button4.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                button4.setText(String.valueOf(n/2));
            }
        });

到目前为止,我尝试了这个,但它只达到了 8,仅此而已。 我添加了框架,我只需要这个按钮就可以了

【问题讨论】:

    标签: java user-interface


    【解决方案1】:

    下面的代码会不断地将 n 分成两半,直到它达到 1,然后保持在那里。

            int n=16;
            JButton button4 = new JButton(String.valueOf(n));
            frame.add(button4);
            button4.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    button4.setText(String.valueOf(n));
                    if( n > 1)
                        n = n / 2;
                }
            });
    

    确保在类头中的方法之外定义 n。

    【讨论】:

    • 它有效,但我需要将 n 声明为 static int n=16;在 static void main 之前,我为什么需要这样做?
    • @Јаневски Ѓоре 当您从内部类中引用变量时,这些变量需要声明为静态的。
    【解决方案2】:

    主要问题是您没有修改n。所以你只需继续将文本设置为16 / 2 = 8

    您可以修改n(例如:n /= 2),或者您可以读取按钮的文本,转换为 int,将其减半,然后将按钮的文本设置为该值。不需要n

    button4.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                JButton b = (JButton)e.getSource();
                int n = Integer.parseInt(b.getText());
                if (n > 1) {
                    b.setText(String.valueOf(n / 2));
                }
            }
            catch (Exception ex) {}
        }
    });
    

    此代码可重复用于任何按钮。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-18
      • 2020-01-12
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 2019-10-05
      • 1970-01-01
      相关资源
      最近更新 更多