如何在 Java Swing 中将 JTable 添加到面板中?
若要将 JTabel 添加到面板中,我们首先创建一个面板 −
JPanel panel = new JPanel();
现在,创建 JTable 并添加具有记录的行和列 −
String[][] rec = { { "1", "Steve", "AUS" }, { "2", "Virat", "IND" }, { "3", "Kane", "NZ" }, { "4", "David", "AUS" }, { "5", "Ben", "ENG" }, { "6", "Eion", "ENG" }, }; String[] header = { "Rank", "Player", "Country" }; JTable table = new JTable(rec, header);
将上面创建的表格添加到面板 −
panel.add(new JScrollPane(table));
以下是将 JTabel 添加到 Java Swing 中的面板的示例 −
示例
package my; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.border.TitledBorder; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP)); String[][] rec = { { "1", "Steve", "AUS" }, { "2", "Virat", "IND" }, { "3", "Kane", "NZ" }, { "4", "David", "AUS" }, { "5", "Ben", "ENG" }, { "6", "Eion", "ENG" }, }; String[] header = { "Rank", "Player", "Country" }; JTable table = new JTable(rec, header); panel.add(new JScrollPane(table)); frame.add(panel); frame.setSize(550, 400); frame.setVisible(true); } }
这将生成以下输出 −
广告