在自定义 JPanel 和 JTable 布局之间进行选择



我正在尝试设置一个水平显示行和文本的 JPanel。它将需要一个文本文件,并且我正在尝试在给定文件大小的情况下同时显示行和文本。使用JTable布局还是在JPanel上制作自己的布局更合适(对编码相对较新)?

下面是一个非常基本的示例,介绍如何使用 JTextPane 在 JFrame 中显示文本文件中的某些文本。 如果你想做更多的事情,那么像布局管理器这样的东西就会发挥作用,但对于简单的文本显示,这应该是合适的:

public class SO{
public static void main(String[] args) throws IOException{
    JFrame frame = new JFrame();
    JTextPane pane = new JTextPane();
    frame.add(pane);
    BufferedReader br = new BufferedReader(new FileReader("D:\Users\user2777005\Desktop\test.txt"));
    String everything = "";
    try {
        StringBuilder sbuild = new StringBuilder();
        String line = br.readLine();
            while (line != null) {
                sbuild.append(line);
                sbuild.append('n');
                line = br.readLine();
            }
            everything = sbuild.toString();
    } catch (FileNotFoundException e) {
                e.printStackTrace();
    } finally {
        br.close();
    }
    pane.setFont(new Font("Segoe Print", Font.BOLD, 12));
    pane.setText(everything);
    frame.setLocationRelativeTo(null);
    frame.pack();
    frame.setVisible(true);
}
}       

如图所示,JTexPane还允许更改字体。

祝你好运!

最新更新