-1

Having an issue with some bits of my code.

label1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            label1.setText(-Here i want the button to open up a new "update window, and it will update the label to the text i'll provide in a seperate window);
        }
    });

Is there any way to do it without without an additional form? Just wanted to add that i have several labels, and i'm not sure on how to start with it.

1 Answers1

2

One approach is to return a result from your update dialog which you can then use to update the text in label1. Here's an example which updates the label text based on the result return from a JOptionPane

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

public class Test {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setMinimumSize(new Dimension(200, 85));
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new FlowLayout());

                JLabel label = new JLabel("Original Text");
                frame.add(label);

                JButton button = new JButton("Click Me");
                frame.add(button);

                // to demonstrate, a JOptionPane will be used, but this could be replaced with a custom dialog or other control
                button.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int result = JOptionPane.showConfirmDialog(frame, "Should I update the label?", "Test", JOptionPane.OK_CANCEL_OPTION );
                        // if the user selected 'Ok' then updated the label text
                        if(result == JOptionPane.OK_OPTION) {
                            label.setText("Updated text");
                        }
                    }
                });
                frame.setVisible(true);

            }
        });
    }
}

Another approach would be to use an Observer and Observable which would listen for updates and change the label text accordingly. For more on the Observer, take a look at this question: When should we use Observer and Observable

Community
  • 1
  • 1
Jason Braucht
  • 2,358
  • 19
  • 31