Java gui remove shortcut using JButton

I need help in that you remove the shortcut and create a new one using the button. At the moment, this will add a new shortcut, but will not delete the old one. I can not find the command that will work, northpanel.remove () will destroy the panel and the previous label, but then I can not create any new ones.

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

@SuppressWarnings("serial")
public class test2 extends JFrame implements ActionListener {

 private JTextField textfield;

 private JPanel northPanel = new JPanel();
 private JPanel southPanel = new JPanel();

 public test2() {
  setSize(400, 200);

  BorderLayout layout = new BorderLayout ();
  setLayout(layout);

  JLabel label1 = new JLabel("remove this");
  northPanel.add(label1);

  JLabel label2 = new JLabel("Enter move");
  southPanel.add(label2);
  textfield = new JTextField(10);
  southPanel.add(textfield);
  JButton button = new JButton("Move / remove label");
  button.addActionListener(this);
  southPanel.add(button);

  add(northPanel, BorderLayout.NORTH);
  add(southPanel, BorderLayout.SOUTH);
 }

 @Override
 public void actionPerformed(ActionEvent e) {
  String text = textfield.getText();

  if (text.equals("")) {
   System.out.println("textfield is empty");
  } else {
   System.out.println(text);
  }


 // northPanel.remove();

  JLabel label3 = new JLabel("new label");
  northPanel.add(label3);

  repaint();
  validate();
 }

 public static void main(String[] args) {
  test2 app = new test2();
  app.setVisible(true);
  app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}
+3
source share
4 answers

Why don't you change the label text instead of deleting the old and adding a new one?

private JPanel northPanel = new JPanel();
private JPanel southPanel = new JPanel();
private JLabel label1 = new JLabel("remove this");

// ....


@Override
 public void actionPerformed(ActionEvent e) {
  // ...

  label1.setText("new text");

  // ...
 }
+2
source

Why are you trying to remove and add a shortcut. All you have to do is:

label1.setText("some different text");

However, the general rule for removing / adding components to a visible graphical interface is:

panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint();
+1
source

label1 . label1 . actionPerformed,

 public void actionPerformed(ActionEvent e) {
  String text = textfield.getText();

  if (text.equals("")) {
   System.out.println("textfield is empty");
  } else {
   System.out.println(text);
   label1.setText(text);
  }
0

Removing a tag from a frame. You must also update the frame containing the label. This worked great for me.

frame.getContentPane().remove(label);

For clarification, just do it.

Just enter a name frame, then .getContentPane().remove, then (label).

0
source

Source: https://habr.com/ru/post/1772228/


All Articles