繁体   English   中英

如何在Java中将文本输出到窗口

[英]How to output text into a window in java

我正在寻找一种创建窗口(使用Jpanel或其他工具),从网站中获取一定数量的文本(此部分正在工作)并将其显示在文本字段中的方法。 我知道这似乎很简单,但是我是新来的。 谢谢! 到目前为止,我从Jsoup网站获得了以下示例:

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class closings {

public static void main(String[] args) throws IOException {

    Document document = Jsoup.connect("http://www.wjla.com/weather/virginia-school-closings-delays/").get();
    Elements tags = document.select("#closingsList");

    for (Element tag : tags) {
        System.out.println(tag.text());
    }
}}

假设您的jsoup正常工作,并且您的每个循环都打印出所需的标签...。我编写了一些代码,使用Java swing将数组列表的内容打印到TextArea。 我与您所做的唯一不同是使用字符串而不是元素(因为我没有下载jsoup库。

class stackExchangeHelp

package stackExchangeHelp;

import java.util.ArrayList;

public class stackExchangeHelp
{
    public static void main(String[] args)
    {
        //this should be a list of elements (not strings)
        ArrayList<String> listToSend = new ArrayList<String>();

        //use your for each loop to add elements to the list
        listToSend.add("First element");
        listToSend.add("Second Element");
        listToSend.add("Third Element");

            DisplayGuiHelp gui = new DisplayGuiHelp(listToSend);
    }
}

类DisplayGuiHelp

package stackExchangeHelp;

import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextPane;

public class DisplayGuiHelp
{
    public DisplayGuiHelp(ArrayList<String> list) //constructor of the DisplayGuiHelp object that has the list passed to it on creation
    {
        final JFrame theFrame = new JFrame();
        theFrame.setTitle("Stack exchange help");
        theFrame.setSize(500, 500);
        theFrame.setLocation(550, 400);

        JPanel mainPanel = new JPanel();

        JTextArea theText = new JTextArea(5,25); //create the text area

        for(String text : list)
        {
            theText.append(text + "\n"); //append the contents of the array list to the text area

        }
        mainPanel.add(theText); //add the text area to the panel

        theFrame.getContentPane().add(mainPanel); //add the panel to the frame
        theFrame.pack();
        theFrame.setVisible(true);

    }
}

如果您有任何疑问或希望我进一步扩展,请告诉我。

您可以创建一个JLabel

步骤1:将此行添加到您的代码中:

import javax.swing.*;

步骤2:添加此代码:

JFrame f = new JFrame();
JPanel p = new JPanel();
JLabel l = new JLabel(tag.text());

p.add(l);
f.add(p);
f.setVisible(true);

你们都准备好了! 享受您的代码!

暂无
暂无

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

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