JLabel的文字没有变化

时间:2014-01-06 12:51:44

标签: java swing jlabel

编辑:巨大的代码重组,旧问题:http://pastebin.com/Mbg4dYiY

我创建了一个基本程序,旨在使用Swing在窗口中显示天气。我正在使用IntelliJ开发,我已经使用了UI构建器。我试图从Weather Underground服务器获取一些信息,然后使一个名为weatherlabel的JLabel显示此信息。但是,JLabel实际上并没有在窗口中改变;它只是留在'天气会去这里'。我该如何解决这个问题?

这是我的main.java:

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

}

这是我的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);
        }


    }

}

当我运行程序时,会将其打印到日志中:

Hello World!
        "weather":"Scattered Clouds",
        Scattered Clouds
        Scattered Clouds

1 个答案:

答案 0 :(得分:1)

  1. 您似乎对OOP和代码流有一种奇怪的理解
  2. 您必须使用main方法,其中一种方法是尝试调用其他main方法。不要那样做。程序应该只有一个main方法。您永远不会拥有此

    Display.main(new String[]{});
    
  3. 为什么要这个ChangeWeatherLabelText课?只有一种方法,在它自己的类中似乎不需要。如果该方法中的Display对程序的其余部分没有任何作用,则实例化。所以你打电话对标签没有影响。

  4. 而不是3,将该方法放在实际具有标签的类中,只引用方法中的标签字段。
  5. 此外,GetWeather似乎是一个带辅助方法的辅助类。如果他们不返回某些东西,“助手”类方法就没用了。
  6. 恕我直言,你应该重组你的整个节目。有些事情现在可能有用,但你的代码中有很多不好的做法
  7. 如果我要写这个程序,所有代码都在一个文件中。如果你坚持将它们放在单独的文件中,你需要学习如何使用构造函数以及如何将对象传递给它们。这就是你如何操纵其他类中的对象。除非您了解MVC模型,否则此时可能会稍微提前一点。

  8. OP更新代码

    更新

    测试一下,一定要阅读评论,这样你才能看到我做了什么。如果您有任何疑问,请与我联系。

    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);
            }
    
    
        }
    
    }