当我从网站打印出原始文本时,它只会在JLabel
中放置一行文本,但在控制台中,它们将在各自的行中执行多行。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class closinggui extends JFrame {
private JPanel contentPane;
JLabel label;
JButton button;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
closinggui frame = new closinggui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void code() throws IOException
{
Document document = Jsoup.connect("http://www.nbcwashington.com/weather/school-closings/").get();
Elements tags = document.select("p");
for (Element tag : tags) {
System.out.println(tag.text());
label.setText(tag.text());
}
}
public closinggui() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 449, 524);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
label = new JLabel("");
label.setBounds(10, 45, 414, 440);
contentPane.add(label);
button = new JButton("get closings");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
code();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
button.setBounds(164, 11, 89, 23);
contentPane.add(button);
}
}
作为样本,它应打印出多个学校关闭,如下所示:
Washington Yu Ying Public Charter School Closed
Whitman-Walker Health Open at 10am
Woodyard Road Nursery Open at 10am
但是在标签上,它显示的是1行,即使是关闭它也只是在与其他HTML标签相同的HTML标签中。那我该怎么做缩进呢?
答案 0 :(得分:2)
JLabel label = new JLabel("<html><span>this is <br> your text</span></html>");
或尝试
setText()
用html
<br>
在它。
<br>
会正确破坏线条。
答案 1 :(得分:2)
尝试使用html标签:
String txt = "<html>";
for (Element tag : tags) {
txt += tag.text() + "<br/>";
}
txt += "</html>";
label.setText(txt);