簡體   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