2016-06-27 27 views
1

我試圖讓我的main班級從另一個班級獲得alertText的內容,該班級使用Jsoup來抄襲網站。報廢工作正常,我只是無法得到alertText變量不錯。我試圖讓AlertSystemDaemon班的主班級負責填寫JLabel jLabelAlertSystem的內容。 我嘗試過使用jLabelAlertSystem.setText(String.valueOf(alertText));試圖從另一個班級獲得變數

但是這將會像以前一樣在alertText上出錯。

主類:

public static void main(String[] args) { 


    MainPanel mainPanel = new MainPanel(); 
    mainPanel.initialize(); 
    mainPanel.frame.setVisible(true); 
    systemTray(); 
} 


private void initialize() { 

    SplashScreen splash = new SplashScreen(3000); 
    splash.showSplash(); 

    AlertSystemDaemon alertsystemdaemonobject = new AlertSystemDaemon(); 
     try { 
      alertsystemdaemonobject.alertSystemMessage(); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 


    frame = new JFrame(); 
    frame.setTitle(Label.MAIN_PANEL); 
    frame.setBounds(100, 100, 1140, 768);// 
    frame.setLocationRelativeTo(null); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().setLayout(null); 


    JLabel jLabelAlertSystem = new JLabel(alertText, SwingConstants.RIGHT); 
    jLabelAlertSystem.setBounds(750, 0, 360, 20); 
    jLabelAlertSystem.setFont(new Font("Calibri", Font.BOLD, 15)); 
    jLabelAlertSystem.setForeground (Color.red); 
    jLabelAlertSystem.setText(String.valueOf(alertText)); 
    frame.getContentPane().add(jLabelAlertSystem); 

其他類:

import java.io.IOException; 
import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document; 


public class AlertSystemDaemon { 

public void alertSystemMessage() throws IOException { 
//MainPanel mainpanel = new MainPanel(); 
String url = "http://example.com/alertpage"; 
    Document document = Jsoup.connect(url).get(); 

    String alertText = document.select("p").first().text();   
// jLabelAlertSystem.setText(String.valueOf(alertText)); 
     System.out.println(alertText); 

} 
} 

回答

0

你只需要改變你的方法public void alertSystemMessage()public String alertSystemMessage()在類AlertSystemDaemon和替代sysoutalertText返回它像這個:

public String alertSystemMessage() throws IOException { 
    String url = "http://example.com/alertpage"; 
    Document document = Jsoup.connect(url).get(); 
    String alertText = document.select("p").first().text();   
    return alertText; 
} 

然後你把它叫做方法,創建一個字符串變量來保存它的價值,像這樣:

AlertSystemDaemon alertsystemdaemonobject = new AlertSystemDaemon(); 
String someNameYouWant = null; 
try { 
    someNameYouWant = alertsystemdaemonobject.alertSystemMessage(); 
} catch (IOException e1) { 
    e1.printStackTrace(); 
} 
//use someNameYouWant at your will. 
+0

太謝謝你了! – javajoejuan

相關問題