Java 用Jbutton清除JLabel

Java 用Jbutton清除JLabel,java,jframe,jbutton,jlabel,Java,Jframe,Jbutton,Jlabel,实际上,我是Java编程的初学者(在eclipse上,没有netbeans),我希望通过单击JButton而不删除此框架顶部的JButton来清除JFrame中出现的JLabel import java.awt.Color; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter;

实际上,我是Java编程的初学者(在eclipse上,没有netbeans),我希望通过单击JButton而不删除此框架顶部的JButton来清除JFrame中出现的JLabel

import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import javax.swing.BoundedRangeModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ButtonTest extends JPanel implements ActionListener {
  private JButton ouvrirButton = new JButton("Ouvrir");
  private JButton retirerButton = new JButton("Retirer");
  private JButton ajouterButton = new JButton("Ajouter");

public ButtonTest() {
  add(ouvrirButton);
  add(retirerButton);
  add(ajouterButton);

ouvrirButton.addActionListener(this);
retirerButton.addActionListener(this);
ajouterButton.addActionListener(this);}

public void actionPerformed(ActionEvent evt) {
 Object source = evt.getSource();
 Color color = getBackground();

// ACTION Button "OUVRIR"
// I WANT TO REMOVE THIS JLABEL TEXT WHEN I CLICK FOR EXEMPLE ON
// OR "RETIRER"

if (source == ouvrirButton)
{ 
    color = Color.yellow;
    JLabel lab1 = new JLabel("Text", JLabel.LEFT);
    setLayout(new FlowLayout()); 
    add(lab1 = new JLabel("INVENTAIRE : "));
    lab1.setBounds(20, 15, 500, 100);
}
else if (source == retirerButton)
        color = Color.red;
else if (source == ajouterButton)
    color = Color.red;
setBackground(color);
repaint();
}

// The main

 public static void main(String[] args) {
  // NOM DE LA FENETRE
  JFrame frame = new JFrame("Programme ");

frame.addWindowListener(new WindowAdapter() {
  public void windowClosing(WindowEvent e) {
    System.exit(0);
  }
});

Container contentPane = frame.getContentPane();
contentPane.add(new ButtonTest());
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
frame.setSize(1300, 700);
frame.setVisible(true);    
}
}
我试过了。setText(“”),但它不起作用。。。请帮帮我

我尝试了.setText(“”),但它不起作用

是的。问题是在ActionListener中创建标签,这样标签引用仅在创建它的代码块中有效

您需要将标签创建为实例变量(就像您为所有按钮所做的那样),并在将按钮添加到面板的同时将标签添加到fame中

然后,您将能够访问ActionListener中的标签并更改文本