public JFrame myUI = new JFrame();
public Container pane = myUI.getContentPane() ;
private JTabbedPane tabbedPane = new JTabbedPane();
private void makeTabbedPane(){
JPanel tabs = new JPanel();
String tabsName = "tags";
Object columnNames[] = { "id", "name"};
Object rowData[][] = {
{ "1", "Jean"},
{ "2", "Annie"}
};
DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
JTable tagsTable = new JTable(model);
tagsTable.setRowHeight(24);
JTableHeader header = tagsTable.getTableHeader();
header.setFont(new Font("", Font.BOLD,20));
JScrollPane jsp = new JScrollPane(tagsTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tabs.setLayout(new BorderLayout());
tabs.add(header, BorderLayout.NORTH);
tabs.add(jsp, BorderLayout.CENTER);
tabs.add(new JButton("OK"), BorderLayout.SOUTH);
tabbedPane.addTab(tabsName, tabs);
}
myUI.add(tabbedPane);
}
创建JScrollPane并将其添加到BorderLayout.CENTER后,无法单击JButton“OK”!
(该按钮看起来已启用,但是当您无法点击它时)
如果我不创建JScrollPane,只需将JTable添加到JPanel选项卡,JButton“OK”将是可点击的。
为什么这样以及如何解决它?
答案 0 :(得分:3)
问题与您将表格标题添加到面板有关。无法真正解释原因。必须深入研究。但是当您向滚动窗格添加表时,它会隐式添加表头。所以只需摆脱
//tabs.add(header, BorderLayout.NORTH);
这是一个供其他人测试的MCVE。也许其他人有解释: - )
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
public class TestTable {
public JFrame myUI = new JFrame();
private JTabbedPane tabbedPane = new JTabbedPane();
public TestTable() {
makeTabbedPane();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestTable();
}
});
}
private void makeTabbedPane() {
JPanel tabs = new JPanel();
String tabsName = "tags";
Object columnNames[] = {"id", "name"};
Object rowData[][] = {
{"1", "Jean"},
{"2", "Annie"}
};
DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
JTable tagsTable = new JTable(model);
tagsTable.setRowHeight(24);
JTableHeader header = tagsTable.getTableHeader();
header.setFont(new Font("", Font.BOLD, 20));
JScrollPane jsp = new JScrollPane(tagsTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
tabs.setLayout(new BorderLayout());
//tabs.add(header, BorderLayout.NORTH);
tabs.add(jsp, BorderLayout.CENTER);
tabs.add(new JButton("OK"), BorderLayout.SOUTH);
tabbedPane.addTab(tabsName, tabs);
myUI.add(tabbedPane);
myUI.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
myUI.pack();
myUI.setLocationRelativeTo(null);
myUI.setVisible(true);
}
}