2016-10-07 59 views
0

嘿傢伙我真的很感謝任何幫助,但我最近編寫了這個簡單的軟件,遇到了一個奇怪的問題。我試圖使用ActionListener,但我有些搞砸了。自從我這樣做以來已經有一段時間了。對不起,如果這只是一個粗心的錯誤。JButton和ActionListener問題

代碼:

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class startScreen implements ActionListener { 
    JFrame mainFrame; 
    JPanel mainPanel; 
    JButton gotIt; 

    private final String gotItText = "Got It!"; 

    public static void main(String[] args) { 
     startScreen a = new startScreen(); 

     a.screenSetup(); 
    } 

    private void screenSetup() { 
     mainFrame = new JFrame(); 
     mainPanel = new JPanel(); 
     gotIt = new JButton(); 

     mainFrame.add(mainPanel); 
     mainPanel.add(gotIt); 

     gotIt.setText(gotItText); 

     mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     mainFrame.setVisible(true); 
     mainFrame.pack(); 
    } 

    @Override 
    public void actionPerformed(ActionEvent arg0) { 
     JButton buttonPressed = (JButton) arg0.getSource(); 
     if (buttonPressed==gotIt) { 
      System.out.println("gotIt has been pressed!"); 
     } 

    } 

} 
+0

究竟是什麼問題?你可能只是忘了添加ActionListener到JButton ... – TNT

回答