使用 Jbutton 清除 JLabel

Clear a JLabel with a Jbutton

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

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 中的标签并更改文本。