有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在GUI中生成一列字符串

我刚开始学习Java,我想做一个基本的gui,显示7的表格

这是我的代码:

import javax.swing.*;
import java.awt.*;

public class test {
    private JFrame f;
    private JPanel p;
    private JLabel lab;
    private JLabel lab1;
    private JLabel lab2;

    public test() {
        gui();
    }

    public void gui() {
    {
        f = new JFrame ("table of 7");
        f.setVisible(true);
        f.setSize(200,400);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        p = new JPanel();
        p.setBackground(Color.YELLOW);

        lab = new JLabel("1 x 7 = 7" );
        lab1 = new JLabel("2 x 7 = 21");
        lab2 = new JLabel("3 x 7 = 28");

        p.add(lab); p.add(lab1); p.add(lab2); 
        f.add(p);
    }
}

public static void main(String[] args) {
        new test();
}
}

问题是,我想在一个整洁的列中显示表,我尝试了在单个字符串中显示/n,但这不起作用


共 (1) 个答案

  1. # 1 楼答案

    the problem is I want to display the table in a neat column

    你需要使用等距字体

    也许是这样的:

    label.setFont( new Font("monospaced", Font.PLAIN, 12) );
    

    您需要为所有标签执行此操作

    或者,显示数据的一种更简单的方法是使用JTextArea,然后您可以执行以下操作:

    JTextArea textArea - new JTextArea(10, 20);
    textArea.setFont(...);
    textArea.append("1 x 7 =  7");
    textArea.append("\n2 x 7 = 14");