【问题标题】:JLabel's text is not changingJLabel 的文字没有变化
【发布时间】:2014-01-06 12:51:43
【问题描述】:

编辑:巨大的代码重组,老问题在这里: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

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖SSCCE
  • 您可能需要重新验证或重新绘制布局。像这样:d.weatherfield.revalidate();或 d.weatherfield.repaint(); repaint() 应该足够了。
  • @LeoPflug,重绘没有任何区别;不过谢谢。
  • @AndrewThompson,下次会做!

标签: java swing jlabel


【解决方案1】:
  1. 你对OOP和代码流的理解好像有点奇怪
  2. 您必须使用main 方法,其中一个您正试图调用另一个main 方法。不要那样做。一个程序应该只有一个main 方法。你应该永远不得不这样做

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

  4. 而不是 3,将该方法放在实际具有标签的类中,并仅引用方法中的标签字段。
  5. 另外,GetWeather 看起来就像一个带有辅助方法的辅助类。 “Helper”类方法如果不返回任何东西就毫无用处。
  6. 恕我直言,您应该重组整个程序。有些事情现在可能有效,但您的代码中有很多不好的做法
  7. 如果我要编写这个程序,所有代码都将在一个文件中。如果您坚持将它们放在单独的文件中,则需要学习如何使用构造函数以及如何将对象传递给它们。这就是你将如何操作来自其他类的对象。除非您了解 MVC 模型,否则这对您来说可能有点进步。

UPDATE OP 更新代码

对此进行测试,并确保阅读 cmets,以便您了解我所做的。如果您有任何问题,请告诉我。

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


    }

}

【讨论】:

  • 认为我的代码很糟糕!我现在要做一些重组。
  • 整个 4 类的事情开始了,因为我对静态空隙的工作原理有一个非常糟糕的想法,如果你想知道的话
  • 查看我的 UPDATE 我修复了一些问题并添加了您应该查看的 cmets。运行程序。它对我有用。
  • 你可以去掉getandsetWeather()中的init()。我现在注意到了。我认为这就是为什么单击按钮时程序会闪烁的原因
  • 是的,我确定你有超过 1 个 ;-)
猜你喜欢
  • 2013-03-30
  • 2019-01-24
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
  • 2012-08-08
  • 2021-09-28
  • 1970-01-01
相关资源
最近更新 更多