簡體   English   中英

如何在Java GUI中創建類似表的結構

[英]How to Create a Table-like Structure in Java GUI

我想創建一個類似表格的結構,以便可以輕松顯示信息。 我希望它看起來像這樣:

這是我要創建的表結構。

什么是實現這一目標的最佳布局管理器? 我當前正在使用GridBagLayout,但是我無法使Title跨越整個頂部行,而讓ColumnTitle1和ColumnTitle2分別跨越第二行。 有人可以提供一些代碼來提供幫助。

我認為GridBagLayout是實現此設計的最佳方法。 這是一個完整的示例,看起來像這樣:

在此處輸入圖片說明

JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();

gc.gridx=0;
gc.gridy=0;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.weightx = 1.0;
gc.gridwidth = 2;
JLabel title = new JLabel("TITLE");
title.setBackground(Color.RED);
title.setOpaque(true);
title.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(title, gc);

gc.gridx=0;
gc.gridy=1;
gc.weightx = 0.5;
gc.gridwidth = 1;        
JLabel col1 = new JLabel("COLUMN 1 TITLE");
col1.setBackground(Color.YELLOW);
col1.setOpaque(true);
col1.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(col1, gc);

gc.gridx=1;
gc.gridy=1;        
JLabel col2 = new JLabel("COLUMN 2 TITLE");
col2.setBackground(Color.GREEN);
col2.setOpaque(true);
col2.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(col2, gc);

gc.fill = GridBagConstraints.BOTH;
gc.gridx=0;
gc.gridy=2;
gc.weighty = 1.0;
gc.gridwidth = 1;        
JLabel info1 = new JLabel("Info 1 Text");
info1.setBackground(Color.CYAN);
info1.setOpaque(true);
info1.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(info1, gc);

gc.gridx=1;
gc.gridy=2;
JLabel info2 = new JLabel("Info 2 Text");
info2.setBackground(Color.MAGENTA);
info2.setOpaque(true);
info2.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(info2, gc);

frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM