2017-01-07 41 views
2

我實際上是Java編程的初學者(在eclipse和沒有netbeans的情況下),並且想通過單擊JButton來清除JLabel在JFrame中的存在,而不刪​​除此框架頂部的JButton 。用Jbutton清除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(「」),但它不工作...請幫助我!

回答

2

我試圖.setText( 「」),但它不工作...

是它。問題是您在ActionListener中創建標籤,以便標籤引用僅在創建它的代碼塊中有效。

您需要創建標籤作爲實例變量(您爲所有按鈕所做的操作),並在將按鈕添加到面板的同時將標籤添加到名譽中。

然後,您將能夠訪問ActionListener中的標籤並更改文本。

+0

OMG它的工作!非常感謝你,你是一個天才!留言Merci。 – Siya

相關問題