简体   繁体   中英

Update JLabel text

I'm working on a simple GUI. On Button press i want to increase/decrease a variable and update the corresponding 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 with 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);

    }

}

I'm aware, that's kind a newbish question. I think I'm wrong with my Code Structure. Any help is appreciated.

Thanks in advance.

You never register any ActionListener s to the buttons...

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

You also never add the buttons to the GUI

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

You also never add the labels to the GUI either...

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

I reworked the code, because your example was messing with my mind, hope you don't mind...

It's conceptually the same idea, just done slightly more efficently

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);
        }

    }
}

I would encourage you to spend some time having a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details

更改值后

frame.repaint();

Good to see you learning Java! A few things I should point out.

Firstly, your variable names are good, but they don't follow the Java naming convention . Even though it seems small, it's just good practice to follow.

Of course, your actual problem; the action listener you've implemented is on the JFrame. (See how you extend JFrame and implement ActionListener?) This ActionListener should be on the button. You'll can do this a few ways.

Method 1: By adding it inline with your code

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

});

Method 2: Create a class which implements ActionListener

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

And then instantiate an object of this type and add it directly to your code.

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

Of course, as in MadProgrammers answer, don't forget to add the labels and such to your JFrame or JPanel. Good luck learning Java!

I bet that your program just shows nothing, isn't it? That's because in addComponentsToPane method, you didn't add any component but empty JPanels. After the comment //Adding Components to GridPanel, you should:

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

Then, to listen to button event, you should also add :

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

"this" is because your frame JFrameSetUp implements ActionListener, so when either bootton is clicked the method actionPerformed is invoked. As JLabel.setText method will repaint itself and consequently its component hierarchi is repainted as well, you haven't to do anything othr.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM