试图从另一个类获得变量

时间:2016-06-27 02:56:03

标签: java jsoup

我正在尝试让我的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);

}
}

1 个答案:

答案 0 :(得分:0)

您只需将方法public void alertSystemMessage()更改为班级public String alertSystemMessage()中的AlertSystemDaemon,而不是sysout alertText您将其返回为:

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.