java - 使用 Jbutton 清除 JLabel

标签 java jframe jbutton jlabel

我实际上是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 中创建标签,以便标签引用仅在创建它的代码块中有效。

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

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

关于java - 使用 Jbutton 清除 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41527347/

相关文章:

java - 如何将 MySQL Timestamp 转换为 JFreeChart TimeSeries Graph X 轴值?

java - (Libgdx) 使舞台和 spritebatch 中的一切变暗

java - 如何关闭 Activity 的 JFrame

java - 如何在 Java 中使用 JButton 重新绘制组件?

java - 如何添加鼠标松开事件?

java - 更改需要声明为final的局部变量的值

Java 的 Graphics.drawImage 生成不准确的图像

java - @Secured 如何知道数据库中的用户是什么角色?

java - javax.swing 中的 getContentPane() 的作用是什么?

Java 按钮操作命令