我正在構建一個使用JFrame的程序。我最終想要的結果是實現一個ActionListener,當用戶單擊一個按鈕時它將刪除標籤。例如:當用戶點擊JButton時,5個標籤中的一個從框架中移除。當他們再次點擊該按鈕時,其餘的4個標籤中的一個被刪除...等等,直到剩下0個標籤。從技術上講,我有程序按要求工作,但是,我試圖看看是否有方法通過循環實現ActionListener事件,而不是爲每個單獨的標籤列出if語句。非常感謝!JFrame - ActionListener
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//calls for public class to inherit features of JFrame within Java
public class NoPurchaseReason extends JFrame implements ActionListener {
private int removeText = 0;
JButton btn = new JButton("Select");
JLabel lbl = new JLabel("Found better price");
JLabel lbl1 = new JLabel("Not as shown on website");
JLabel lbl2 = new JLabel("Wrong product");
JLabel lbl3 = new JLabel("Damaged upon delivery");
JLabel lbl4 = new JLabel("None of the above");
public static void main(String[] args) {
JFrame f = new NoPurchaseReason("Please tell us why you wish to return your purchase.");
f.setBounds(300, 100, 500, 500);
f.setVisible(true);
f.setBackground(Color.blue);
}
public NoPurchaseReason(String title) {
super(title);
setLayout(null);
lbl.setBounds(40, 40, 600, 40);
btn.setBounds(320, 10, 80, 20);
lbl.setBounds(100, 40, 100, 20);
lbl1.setBounds(100, 70, 100, 20);
lbl2.setBounds(100, 100, 150, 20);
lbl3.setBounds(100, 130, 100, 20);
lbl4.setBounds(100, 160, 100, 20);
add(btn);
add(lbl);
add(lbl);
add(lbl1);
add(lbl2);
add(lbl3);
add(lbl4);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
removeText++;
if (removeText == 1) {
lbl.setVisible(false);
lbl1.setBounds(100, 40, 100, 20);
lbl2.setBounds(100, 70, 100, 20);
lbl3.setBounds(100, 100, 150, 20);
lbl4.setBounds(100, 130, 100, 20);
}
if (removeText == 2) {
lbl1.setVisible(false);
lbl2.setBounds(100, 40, 100, 20);
lbl3.setBounds(100, 70, 150, 20);
lbl4.setBounds(100, 100, 100, 20);
}
if (removeText == 3) {
lbl2.setVisible(false);
lbl3.setBounds(100, 40, 150, 20);
lbl4.setBounds(100, 70, 100, 20);
}
if (removeText == 4) {
lbl3.setVisible(false);
lbl4.setBounds(100, 40, 100, 20);
}
if (removeText == 5) {
lbl4.setVisible(false);
}
}
}
非常感謝你們的例子!這比我的代碼更加簡潔。我似乎遇到的唯一麻煩是當我嘗試實現您提供的第一個示例時,我繼續得到以下錯誤:標記「setLayout」上的語法錯誤,=在此標記後預期----不確定爲什麼這是怎麼回事? – user2825293
這些示例需要直接粘貼到方法內部,而不是類(我在主要方法中很快寫入它們)。只有聲明可以存在於方法之外,在這種情況下,錯誤發生在'setLayout'上,因爲它不是一個聲明,而是一個方法調用,因此它必須進入某種方法。我在編寫代碼時並沒有真正將你的代碼作爲基礎,所以這不是「面向對象」的全部 - 對此感到遺憾。爲了說明我在說什麼,我在第一個示例中添加了額外的代碼。 – sgbj
非常完美!出於某種原因,我以爲我將setLayout放在我的方法中,但顯然我不是。我非常感謝你的幫助。 :) – user2825293