Skip to content
Advertisement

How to change (add or subtract) the value of a JLabel?

I wish to add 100 EUR to a JLabel (500 EUR) with a JButton (***). Since I cannot add nor subtract an int value from a String, I don’t know what to do.

JButton button;

MyFrame(){
    button = new JButton();
    button.setBounds(200, 400, 250, 100);
    button.addActionListener(e -> );
    button.setText("***");

    JLabel amount = new JLabel("500 EUR");
    amount.setBounds(35, 315, 500, 100);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setSize(1200, 850);
    frame.add(button);
    frame.add(amount);
    frame.setLayout(null);
    frame.setVisible(true);
}

GUI

Advertisement

Answer

How to change (add or subtract) the value of a JLabel?
… Since I cannot add nor subtract an int value from a String, I don’t know what to do.

This is thinking about the problem in a slightly wrong way. The number of Euros should be held separately as an int value. When an action is performed, increment the value and set it to the string with a suffix of " EUR".

Here is a complete (ready to run) example:

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

public class EuroCounter {

    private JComponent ui = null;
    int euros = 1000;
    String suffix = " EUR";
    JLabel amount = new JLabel(euros + suffix, JLabel.CENTER);

    EuroCounter() {
        initUI();
    }

    public final void initUI() {
        if (ui != null) {
            return;
        }

        ui = new JPanel(new BorderLayout(4, 4));
        ui.setBorder(new EmptyBorder(4, 4, 4, 4));

        JButton button;

        button = new JButton("+");
        button.setMargin(new Insets(20, 40, 20, 40));
        ActionListener incrementListener = (ActionEvent e) -> {
            amount.setText((euros+=100) + suffix);
        };
        button.addActionListener(incrementListener);
        JPanel leftAlign = new JPanel(new FlowLayout(FlowLayout.LEADING));
        leftAlign.add(button);
        ui.add(leftAlign, BorderLayout.PAGE_START);

        amount.setBorder(new EmptyBorder(30, 150, 30, 150));
        amount.setFont(amount.getFont().deriveFont(50f));
        ui.add(amount, BorderLayout.CENTER);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            EuroCounter o = new EuroCounter();
            
            JFrame f = new JFrame(o.getClass().getSimpleName());
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setLocationByPlatform(true);
            
            f.setContentPane(o.getUI());
            f.pack();
            f.setMinimumSize(f.getSize());
            
            f.setVisible(true);
        };
        SwingUtilities.invokeLater(r);
    }
}
Advertisement