使用Java在JFrame中的JLabel中插入html表

时间:2016-09-11 13:28:10

标签: java swing

我是java的新学习者并获得了一项对我来说非常艰难的任务。在这个任务中,我必须使用JFrame和JLabel创建一个表。在JLabel中,我想使用HTML "<table></table>"创建此表。为此,我使用while循环输入带有值的各种<tr><td>,并将其插入JLabel。但是,我不知道如何做到这一点。

以下是我写的代码:

import javax.swing.*;


public class Multiplikationstabell {
    public static void main(String[] args) {
        // TODO code application logic here
        Tabell t1 = new Tabell();
        t1.elements();
    }

}

class Tabell extends JFrame {
    private JLabel label;

    public Tabell() {
        setTitle("Muliplikations tabell");

        this.label = new JLabel(elements());
        add(label);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
     public void elements() {
        System.out.println("<html><body><table border = '1'>");
        int rowNumber = 1;

        while (rowNumber <= 10) {
            int rowFields = 1;
            int multiplier = 1;
            int value = 1;
            value = value * rowNumber;
            System.out.println("<tr>");
            while (rowFields <= 10) {
                System.out.print("<td>" + value * multiplier + "</td>");
                multiplier++;
                rowFields++;
            }
            System.out.println("</tr>");
            rowNumber++;
        }
        System.out.println("</table></body></html>");
    }
}

1 个答案:

答案 0 :(得分:-1)

我们需要使用HTML内容设置JLabel的文字。

Multiplikationstabell

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Multiplikationstabell {

    public static void main(String[] args) {
        // TODO code application logic here
        Tabell t1 = new Tabell();
        String htmlConent = t1.elements();
        t1.label.setText(htmlConent);
    }
}

Tabell

class Tabell extends JFrame {

   public JLabel label;

    public Tabell() {
        setTitle("Muliplikations tabell");
        this.label = new JLabel();
        add(label);
        setVisible(true);
        setSize(400, 400);
        // setLayout(new FlowLayout());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    public String elements() {
        String htmlContent = "<html><body><table border = '1'>";
        int rowNumber = 1;
        while (rowNumber <= 10) {
            int rowFields = 1;
            int multiplier = 1;
            int value = 1;
            value = value * rowNumber;
            htmlContent += "<tr>";
            while (rowFields <= 10) {
                htmlContent += "<td>" + value * multiplier + "</td>";
                multiplier++;
                rowFields++;
            }
            htmlContent += "</tr>";
            rowNumber++;
        }
        htmlContent += "</table></body></html>";
        return htmlContent;
    }
}