更新 JLabel 文本

Update JLabel text

我正在开发一个简单的 GUI。在按下按钮时,我想 increase/decrease 一个变量并更新相应的 JLabel。

class JFrameSetUp

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


public class JFrameSetUp extends JFrame implements ActionListener {

    private int RecHeight = 0;
    private int RecWidth = 0;

    //Here Buttons

    JButton HeightIncrease = new JButton("+");
    JButton HeightDecrease = new JButton("-");

    JLabel height = new JLabel(Integer.toString(RecHeight));
    JLabel width = new JLabel(Integer.toString(RecWidth));

    GridLayout gridLayout = new GridLayout(2, 4);

    public JFrameSetUp(){

    }

    public void addComponentsToPane(final Container pane){

        //Create GridPanel and set Layout
        JPanel grid = new JPanel();
        grid.setLayout(gridLayout);

        //Create buttondrawPanel and set Layout
        JPanel buttondraw = new JPanel();
        buttondraw.setLayout(new GridLayout(2, 0));

        //Adding Components to GridPanel

        //Adding Layouts to pane

        pane.add(grid, BorderLayout.NORTH);
        pane.add(new JSeparator(), BorderLayout.CENTER);
        pane.add(buttondraw, BorderLayout.SOUTH);

    }

    @Override
    public void actionPerformed(ActionEvent e) {

        //Setting up ActionListener to Buttons

        if (e.getSource() == this.HeightDecrease) {

            RecHeight -= 1;
            height.setText(Integer.toString(RecHeight));

        } else if (e.getSource() == this.HeightIncrease) {

            RecHeight += 1;
            height.setText(Integer.toString(RecHeight));
        }

    }

}

Class 与 MainMethod

import javax.swing.JFrame;


public class Program {

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();

            }
        });
    }



    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrameSetUp frame = new JFrameSetUp();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Set up the content pane.
        frame.addComponentsToPane(frame.getContentPane());
        //Display the window.
        frame.pack();
        frame.setVisible(true);

    }

}

我知道,这是一个新问题。我认为我的代码结构有误。感谢任何帮助。

提前致谢。

更改值调用后

frame.repaint();

很高兴看到你学习 Java!我应该指出一些事情。

首先,你的变量名很好,但不遵循Java naming convention。虽然看起来很小,但它只是一个很好的实践。

当然是你的实际问题;您实现的动作侦听器位于 JFrame 上。 (看看你是如何扩展 JFrame 和实现 ActionListener 的?)这个 ActionListener 应该在按钮上。您可以通过几种方式做到这一点。

方法 1:将其添加到您的代码中

JButton heightButton = new JButton("Increase Height");
heightButton.addActionListener(new ActionListener(){
  @Override
  public void run(){
    //run method here
  }

});

方法 2:创建一个实现 ActionListener

的 class
class ButtonListener implements ActionListener{
  @Override
  public void run(){
    //actionListener code here
  }
}

然后实例化一个这种类型的对象,直接添加到你的代码中。

ActionListner buttonListener = new ButtonListener(); //or ButtonListener buttonListener = new ButtonListener();
JButton heightButton = new JButton("Increase Height");
heightButton.addActionListener(buttonListener);

当然,就像 MadProgrammers 的回答一样,不要忘记将标签等添加到您的 JFrame 或 JPanel 中。祝学习顺利Java!

您永远不会向按钮注册任何 ActionListener...

HeightIncrease.addActionListener(this);
HeightDecrease.addActionListener(this);

您也永远不会将按钮添加到 GUI

buttondraw.add(HeightIncrease);
buttondraw.add(HeightDecrease);

您也永远不会将标签添加到 GUI...

grid.add(height);
grid.add(width);

我重写了代码,因为你的例子打乱了我的思路,希望你不介意...

概念上是一样的,只是效率稍微高一点

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private int recHeight = 0;
        private int recWidth = 0;

        //Here Buttons
        JButton heightIncrease = new JButton("+");
        JButton heightDecrease = new JButton("-");

        JLabel height = new JLabel(Integer.toString(recHeight));
        JLabel width = new JLabel(Integer.toString(recWidth));

        GridLayout gridLayout = new GridLayout(2, 4);

        public TestPane() {
            setLayout(new BorderLayout());
            //Create GridPanel and set Layout
            JPanel grid = new JPanel();
            grid.setLayout(gridLayout);

            grid.add(height);
            grid.add(width);

            //Create buttondrawPanel and set Layout
            JPanel buttondraw = new JPanel();
            buttondraw.setLayout(new GridLayout(2, 0));

            heightIncrease.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    recHeight += 1;
                    height.setText(Integer.toString(recHeight));
                }
            });
            heightDecrease.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    recHeight -= 1;
                    height.setText(Integer.toString(recHeight));
                }
            });

            buttondraw.add(heightIncrease);
            buttondraw.add(heightDecrease);

            //Adding Components to GridPanel
            //Adding Layouts to pane
            add(grid, BorderLayout.NORTH);
            add(new JSeparator(), BorderLayout.CENTER);
            add(buttondraw, BorderLayout.SOUTH);
        }

    }
}

我鼓励您花一些时间查看 How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners 以了解更多详细信息

我敢打赌你的程序什么都不显示,不是吗?那是因为在 addComponentsToPane 方法中,您没有添加任何组件,而是添加了空的 JPanel。在注释 //Adding Components to GridPanel 之后,你应该:

        buttondraw.add(HeightIncrease);
        buttondraw.add(HeightDecrease);
        grid.add(height);
        grid.add(width);

然后,要监听按钮事件,还应该添加:

        HeightIncrease.addActionListener(this);
        HeightDecrease.addActionListener(this);

"this" 是因为您的框架 JFrameSetUp 实现了 ActionListener,因此当单击任一 bootton 时,将调用方法 actionPerformed。 由于 JLabel.setText 方法将重绘自身,因此其组件层次结构也将重绘,因此您无需执行任何其他操作。