简体   繁体   English

JLabel的文字没有改变

[英]JLabel's text is not changing

EDIT: Huge code re-organisation, old question here: http://pastebin.com/Mbg4dYiY 编辑:巨大的代码重组,旧问题在这里: http : //pastebin.com/Mbg4dYiY

I have created a basic program that is designed to show the weather in a window using Swing. 我创建了一个基本程序,该程序旨在使用Swing在窗口中显示天气。 I am developing using IntelliJ and I have used the UI builder in that. 我正在使用IntelliJ进行开发,并且在其中使用了UI构建器。 I am attempting to fetch some information from the Weather Underground servers and then make a JLabel called weatherlabel display this information. 我试图从Weather Underground服务器获取一些信息,然后使一个名为weatherlabel的JLabel显示此信息。 However, the JLabel doesn't actually change in the window; 但是,JLabel实际上并未在窗口中更改; it just stays as 'Weather Will Go Here'. 它只是停留在“天气会在这里”。 How do I fix this? 我该如何解决?

Here is my main.java: 这是我的main.java:

public class main {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        Display d = new Display();
        d.getandsetWeather();
    }

}

Here is my Display.java: 这是我的Display.java:

public class Display {

    Display disp = this;

    public JPanel myPanel;
    public JLabel weatherfield;
    private JButton button1;

    public void init() {
        JFrame frame = new JFrame("Display");
        frame.setContentPane(new Display().myPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setMinimumSize(new Dimension(480, 234));
        frame.pack();
        frame.setVisible(true);
    }

    public void getandsetWeather() {
        String editedline = null;
        init();
        try {
            // Construct data
            String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
            data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

            // Send data
            URL url = new URL("http://api.wunderground.com/api/772a9f2cf6a12db3/geolookup/conditions/q/UK/Chester.json");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line;
            while ((line = rd.readLine()) != null) {

                if( line.contains("\"weather\":")) {
                    System.out.println(line);
                    editedline = line.replace("\"weather\":\"", "");
                    editedline = editedline.replace("\",", "");
                    System.out.println(editedline);
                    weatherfield.setText(editedline);
                }


            }
            wr.close();
            rd.close();
            weatherfield.setText(editedline);
            System.out.println(weatherfield.getText());
            weatherfield.repaint();
            weatherfield.revalidate();
        } catch (Exception e) {
            System.out.println("Error!" + e);
        }


    }

}

When I run the program, this is printed to the log: 当我运行程序时,这将打印到日志中:

Hello World!
        "weather":"Scattered Clouds",
        Scattered Clouds
        Scattered Clouds
  1. You seem to have a strange understanding of OOP and code-flow 您似乎对OOP和代码流有一个奇怪的理解
  2. You have to main methods, one of which you are trying to call the other main method. 您必须使用main方法,您要尝试调用其中一个main方法。 Don't do that. 不要那样做 A program should only have one main method. 一个程序应该只有一种main方法。 You should never have to this 永远都不必这样做

     Display.main(new String[]{}); 
  3. Why even have this ChangeWeatherLabelText class? 为什么还要设置ChangeWeatherLabelText类? There is only one method, that doesn't seem to be needed in it's own class. 只有一种方法,在它自己的类中似乎并不需要。 Your instantiation if Display in that method does nothing to the rest of the program. 如果用该方法Display ,则实例化对程序的其余部分没有任何作用。 So you call has no effect on the label. 因此,您的呼叫对标签没有影响。

  4. Instead of 3, put that method in the class that actually has the label and just reference the label field in the method. 将该方法放到实际上具有标签的类中,而不是3,然后在该方法中引用标签字段。
  5. Also, GetWeather just seems like a helper class with a helper method. 另外, GetWeather似乎就像是带有帮助程序方法的帮助程序类。 "Helper" class methods are useless if they don't return something. 如果“帮助程序”类方法不返回任何内容,则它们将无用。
  6. IMHO, you should restructure your entire program. 恕我直言,您应该重组整个程序。 Some things may work now, but there's a lot of bad practice going on in your code 现在有些事情可能会奏效,但是您的代码中存在许多不良做法
  7. If I were to write this program, all the code would be in one file. 如果我要编写此程序,则所有代码都在一个文件中。 If you insist on them being in separate files, you need to learn how to use constructors and how to pass objects to them. 如果您坚持将它们放在单独的文件中,则需要学习如何使用构造函数以及如何将对象传递给它们。 That is how you are going to manipulate objects from other classes. 这就是您要操纵其他类中的对象的方式。 That is unless you understand the MVC model, which may be a little advance at this point for you. 除非您了解MVC模型,否则此刻可能对您有所帮助。

UPDATE with OP update of code 更新的代码OP更新

Test this out and be sure to read the comments so you can see what I did. 测试一下,并确保阅读注释,以便您可以看到我的所作所为。 Let me know if you have any question. 如果您有任何问题,请告诉我。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class main {
    public static void main(String[] args) {
        System.out.println("Hello World!");
        new Display();                        // <-- just instantiate
    }

}

 class Display {

    Display disp = this;

    public JPanel myPanel;               // <--------- Haven't been initialized 
    public JLabel weatherfield;
    private JButton button1;

    public Display() {                   // you need constructor to call init
        init();
    }

    public void init() {
        myPanel = new JPanel(new BorderLayout());    // initialize
        weatherfield = new JLabel(" ");              // initialize
        button1 = new JButton("Button");              // initialize
        myPanel.add(weatherfield, BorderLayout.CENTER);
        myPanel.add(button1, BorderLayout.SOUTH);

        button1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                getandsetWeather();                       // <-------- add listener to call getandsetweather
            }
        });

        JFrame frame = new JFrame("Display");
        frame.setContentPane(myPanel);   //   <--------------------- fix 1
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setMinimumSize(new Dimension(480, 234));
        frame.pack();
        frame.setVisible(true);
    }

    public void getandsetWeather() {
        String editedline = null;
        init();
        try {
            // Construct data
            String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
            data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

            // Send data
            URL url = new URL("http://api.wunderground.com/api/772a9f2cf6a12db3/geolookup/conditions/q/UK/Chester.json");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line;
            while ((line = rd.readLine()) != null) {

                if( line.contains("\"weather\":")) {
                    System.out.println(line);
                    editedline = line.replace("\"weather\":\"", "");
                    editedline = editedline.replace("\",", "");
                    System.out.println(editedline);
                    weatherfield.setText(editedline);
                }


            }
            wr.close();
            rd.close();
            weatherfield.setText(editedline);
            System.out.println(weatherfield.getText());
            weatherfield.repaint();
            weatherfield.revalidate();
        } catch (Exception e) {
            System.out.println("Error!" + e);
        }


    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM