2014-09-02 114 views
0

我試圖做一個網頁瀏覽器,這裏是我的代碼不能從主類調用方法?

CODE:

import java.awt.*; 
import javax.swing.*; 
import java.util.*; 
import java.awt.event.*; 
import java.applet.*; 

public class browserPannel extends JFrame{ 

    public static void main(String[] arg) 
    { 
     JFrame browser = new JFrame("A Nun In A Weelchair"); 
     browser.setSize(1000,700); 
     browser.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     browser.setLocationRelativeTo(null); 
     browser.pack(); 
     browser.setVisible(true); 

     JPanel header = new JPanel(); 
     header.setBackground(Color.lightGray); 
     header.setVisible(true); 

     final JEditorPane htmlc = new JEditorPane(); 
     htmlc.setBackground(Color.red); 
     htmlc.setEditable(true); 
     htmlc.setContentType("text/html"); 
     htmlc.setVisible(true); 

     final JTextField url = new JTextField(20); 

     url.setSize(890,30); 
     url.setVisible(true); 

     url.addActionListener(
      new ActionListener() 
      { 
       public void actionPerformed(ActionEvent event) 
       { 
        loadHtml(htmlc, url, event.getActionCommand()); 
        System.out.println("action performed"); 
       } 
      } 
      ); 

     JButton send = new JButton("Send"); 
     send.setSize(75,30); 
     send.setVisible(true); 


     header.add(url, BorderLayout.SOUTH); 
     header.add(send); 
     browser.getContentPane().add(header, BorderLayout.NORTH); 
     browser.getContentPane().add(new JScrollPane(htmlc)); 
    } 

    private void loadHtml(JEditorPane htmlc, JTextField url, String link) 
    { 
     try{ 
      htmlc.setPage(link); 
      url.setText(link); 
     }catch(Exception e){ 
      System.out.println("ops sorry could not fined Virgine Mobile"); 
      e.printStackTrace(); 
     } 
    } 

} 

,這裏是我的錯誤信息:

browserPannel.java:38: error: non-static method loadHtml(JEditorPane,JTextField, 
String) cannot be referenced from a static context 
             loadHtml(htmlc, url, event.getActionComm 
and()); 
             ^
1 error 

,你可以告訴它越來越錯誤從我的代碼的buttom方法中定義的loadHtml,現在如果我刪除loadHtml,然後它顯示println(「行動執行」),但只有當我引用loadHtml它說,它非靜態方法不能在stti中執行c方法。

+1

你是否打算從靜態上下文中搜索關於引用非靜態方法的其他問題?這個問題已經被問過很多次了! – 2014-09-02 04:00:11

回答

0

正確。你需要你的browserPannel類的實例來調用該方法,

browserPannel bp = new browserPannel(); 
bp.loadHtml(htmlc, url, event.getActionCommand()); 

,或者你可以讓

private void loadHtml(JEditorPane htmlc, JTextField url, String link) 

static,像

private static void loadHtml(JEditorPane htmlc, JTextField url, String link) 

編輯

而且, Java駱駝案例約定不適用我你的班級BrowserPanel(我建議你遵循這個約定)。

0

當你調用從main方法的「loadHtml」你會做任何的下面: -

1)使用對象browserPannel類的調用loadHtml或

2)你需要該loadHtml方法是靜態的

記得規則static and within the same class can be directly called from main method

喝彩!