我实际上是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(“”)但它不起作用......请帮助我!
答案 0 :(得分:2)
我试过.setText(“”)但它不起作用......
是的。问题是您在ActionListener中创建标签,以便标签引用仅在创建它的代码块中有效。
您需要将标签创建为实例变量(对所有按钮的方式),并在将按钮添加到面板的同时将标签添加到名望中。
然后,您将能够访问ActionListener中的标签并更改文本。