2012-03-04 61 views
0

我很難嘗試將JButton s添加到我的JFrameJFrame/JButton錯誤消息

我已經創建了兩種方法(現在都在同一個類中)。如果我做showGUI方法靜態的,然後我收到錯誤:

//Listen for actions on buttons. 
next.addActionListener(this); (CANNOT USE THIS IN A STATIC CONTEXT) 
previous.addActionListener(this); (CANNOT USE THIS IN A STATIC CONTEXT) 
classify.addActionListener(this); (CANNOT USE THIS IN A STATIC CONTEXT) 

並添加JButton對象,以我的JFrame的時候,我收到以下錯誤:

add(next); (Cannot make a static reference to the non-static method add(Component) from the type Container) 
add(previous); (Cannot make a static reference to the non-static method add(Component) from the type Container) 
add(classify); (Cannot make a static reference to the non-static method add(Component) from the type Container) 

我如何克服這個問題?我已經包括了我的方法如下,僅供參考:

public void showGUI(BufferedImage img){ 

    next = new JButton("Next Image"); 
    next.setMnemonic(KeyEvent.VK_N); 
    next.setActionCommand("disable"); 

    previous = new JButton("Previous Image"); 
    previous.setMnemonic(KeyEvent.VK_P); 
    previous.setActionCommand("disable"); 

    classify = new JButton("Classify"); 
    classify.setMnemonic(KeyEvent.VK_C); 
    classify.setActionCommand("disable"); 

    //Listen for actions on buttons. 
    next.addActionListener(this); 
    previous.addActionListener(this); 
    classify.addActionListener(this); 

    add(next); 
    add(previous); 
    add(classify); 

    //Display image on the screen. 
    frame.setTitle("TITLE"); 
    RMHC newContentPane = new RMHC(); 
    newContentPane.setOpaque(true); 

    frame.setContentPane(newContentPane); 
    frame.getContentPane().setLayout(new FlowLayout()); 
    frame.getContentPane().add(new JLabel(new ImageIcon(img))); 
    frame.pack(); 
    frame.setVisible(true); 
    frame.isResizable(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

} 
+1

爲了更好的幫助更快,發佈[SSCCE](http://sscce.org/)。 – 2012-03-04 21:45:12

+0

爲什麼當您在之後立即創建新對象時,將nextImg設置爲next? – 2012-03-04 21:48:14

+0

@stas我的代碼現在已經更新。 – MusTheDataGuy 2012-03-04 22:03:41

回答

1

我認爲這個問題是因爲你調用從main方法的方法showGUI是靜態的,所以最好的辦法是在main方法初始化GUI框架(也是在美國東部時間),如:

public class MainApp { 
    public static void main(String... args) { 
     EventQueue.invokeLater(
      new Runnable() { 
       @Override 
       public void run() { 
        JFrame frame= new YourFrame(); 
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        frame.setVisible(true); 
       } 
      } 
     ); 
    } 
} 

class YourFrame() extends JFrame implements ActionListener{ 
    public YourFrame() { 
    } 

    public void showGUI(BufferedImage img){ 
    } 

    private void add(JButtob button) { 
    } 
} 
1

,如果事情是靜態根據code example,你是不是在任何情況下。所以你不能使用「這個」...
請在發佈這樣的東西之前學習java基礎知識。

如果你需要幫助,發佈整個班級,我知道你想做什麼,否則我不能幫你。