I have a Swing window which contains a button a text box and a JLabel named as flag. According to the input after I click the button, the label should change from flag to some value.

How to achieve this in the same window?

0

2 Answers

Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:

jLabel.setText("new Value"); 

A simple demo code will be:

 JFrame frame = new JFrame("Demo"); frame.setLayout(new BorderLayout()); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setSize(250,100); final JLabel label = new JLabel("flag"); JButton button = new JButton("Change flag"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { label.setText("new value"); } }); frame.add(label, BorderLayout.NORTH); frame.add(button, BorderLayout.CENTER); frame.setVisible(true); 
import java.awt.*; import javax.swing.*; import javax.swing.border.*; import java.awt.event.*; public class Test extends JFrame implements ActionListener { private JLabel label; private JTextField field; public Test() { super("The title"); setDefaultCloseOperation(EXIT_ON_CLOSE); setPreferredSize(new Dimension(400, 90)); ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) ); setLayout(new FlowLayout()); JButton btn = new JButton("Change"); btn.setActionCommand("myButton"); btn.addActionListener(this); label = new JLabel("flag"); field = new JTextField(5); add(field); add(btn); add(label); pack(); setLocationRelativeTo(null); setVisible(true); setResizable(false); } public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("myButton")) { label.setText(field.getText()); } } public static void main(String[] args) { new Test(); } } 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy