我尝试用列名“ User”和测试数据“ data”创建一个JTable
,但是列名没有被打印。
String [] [] data = {{"hallo","hallo","","","",""},
{"hallo","hallo","","","",""}};
String [] User = {"ID","Benutzername", "Name", "Vorname", "Geburtsdatum", "Wirt"};
tableUsers = new JTable(data,User);
tableUsers.setPreferredScrollableViewportSize(new Dimension(500,50));
tableUsers.setFillsViewportHeight(true);
//add(new JScrollPane(tableUsers));
JTableHeader header = tableUsers.getTableHeader();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(header, BorderLayout.NORTH);
panel.add(tableUsers, BorderLayout.CENTER);
JScrollPane scrollPane = new JScrollPane(tableUsers);
add(scrollPane);
tableUsers.setBounds(29, 245, 580, 136);
contentPane.add(tableUsers);
当我使用时:
JFrame jf = new JFrame();
addComponents(jf.getContentPane());
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
有效。它创建了一个新的框架,但我想将其添加到使用WindowBuilder创建的实际框架中。我该怎么做?
您将表添加到“ JPanel”面板,然后将面板添加到滚动窗格。因此,现在您的滚动窗格包含您的表。现在,您需要将滚动窗格添加到内容窗格。您不应将tableUsers添加到多个项目。
编辑:由于我认为您遇到了单独的问题,我正在添加用于运行和测试的全部代码。
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
public class Test {
/**
* Do this for thread safety
* @param args
*/
public static void main (String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
}
});
}
/**
* create the JFrame
*/
private static void createGUI() {
JFrame jf = new JFrame();
addComponents(jf.getContentPane());
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
}
/**
* add the components
* @param pane
*/
private static void addComponents(Container pane) {
String [] [] data = {{"hallo","hallo","","","",""}, {"hallo","hallo","","","",""}};
String [] User = {"ID","Benutzername", "Name", "Vorname", "Geburtsdatum", "Wirt"};
JTable tableUsers = new JTable(data,User);
tableUsers.setPreferredScrollableViewportSize(new Dimension(500,50));
tableUsers.setFillsViewportHeight(true);
//add(new JScrollPane(tableUsers));
JTableHeader header = tableUsers.getTableHeader();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(header, BorderLayout.NORTH);
panel.add(tableUsers, BorderLayout.CENTER);
JScrollPane scrollPane = new JScrollPane(panel);
pane.add(scrollPane);
tableUsers.setBounds(29, 245, 580, 136);
//pane.add(tableUsers);
}
}
JTable不显示列名-使用JScrollPane
您没有正确使用JTable和JScrollPane。
基本代码应该是:
JTable table = new JTable(...);
JScrollPane scrollPane = new JScrollPane( table );
frame.add(scrollPane);
那没有必要: