2011-11-20 40 views
1

對於那些有Java經驗的人來說,這可能是一個非常簡單的問題。這是我的代碼,至今我寫的錯誤以及我收到的錯誤。我相信我之前完成過類似的代碼,沒有任何錯誤。我很確定我錯過了一些愚蠢的東西,但我無法弄清楚或在網上找到任何東西。 感謝:Java JPanel.add(...)無法正常工作..?

import javax.swing.*; 
import java.awt.*; 

public class MyFrame extends JFrame { 

    JPanel mainPanel = new JPanel(); 
    JButton editButton = new JButton("Edit"); 
    JPanel.add(editButton); 
} 
Syntax error on token(s), misplaced construct(s) - for the underlined '.' 
on the last line 
Syntax error on token "editButton", VariableDeclaratorId expected after this 
token - for the underlined parameter within the brackets on the last line. 

真的很感激,快速響應,如果對不起這很簡單。 馬特

回答

4

你試圖使用它,彷彿它是一個靜態方法 - 你希望編輯按鈕添加到面板?你需要調用它mainPanel

mainPanel.add(editButton); 

但是,你不能這樣做,在一個類聲明 - 像這樣的語句要在方法或構造函數。所以,你可能想:

import javax.swing.*; 
import java.awt.*; 

public class MyFrame extends JFrame {  
    JPanel mainPanel = new JPanel(); 
    JButton editButton = new JButton("Edit"); 

    public MyFrame() { 
     mainPanel.add(editButton); 
    } 
} 

或者可能把所有初始化到構造,並且也使最終的變量和私營:

import javax.swing.*; 
import java.awt.*; 

public class MyFrame extends JFrame {  
    private final JPanel mainPanel; 
    private final JButton editButton; 

    public MyFrame() { 
     mainPanel = new JPanel(); 
     editButton = new JButton("Edit"); 
     mainPanel.add(editButton); 
    } 
} 
+0

謝謝,我知道這是愚蠢的,這是因爲我試圖趕緊代碼,我甚至輸入我的問題,因爲衝。我的意思是把mainPanel.add()也沒有工作,但你已經回答了。謝謝。 –

2

如下使用它。

mainPanel.add(editButton); 

你必須把它通過它的對象,而不是與它與它的類名關聯,因爲它不是一個靜態方法