如何为Java的JTable添加可用侧边滚动条?已尝试方法无效
JTable侧边滚动条不显示的问题修复
你的代码里有几个关键问题导致滚动条无法正常工作,修复方案如下:
核心问题分析
- 重复添加JTable:你既把JTable放到了JScrollPane里,又直接把JTable添加到了frame的内容面板,组件层次混乱导致滚动条失去作用
- 使用
null布局:frame3.getContentPane().setLayout(null)禁用了Swing的布局管理器,滚动条的自适应逻辑依赖布局管理器才能正常运行 - 手动设置JTable的
setBounds:这会干扰JScrollPane对表格视图的管理,导致滚动条无法触发
修复后的代码
修改create_frame3方法:
public void create_frame3() { frame3 = new JFrame("SGD"); frame3.setBounds(100, 100, 450, 300); // 替换null布局为BorderLayout,让布局管理器自动处理组件位置 frame3.getContentPane().setLayout(new BorderLayout()); frame3.setBackground(Color.white); frame3.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG); // 新建顶部面板放置按钮和余额标签 JPanel topPanel = new JPanel(); topPanel.setLayout(null); // 暂时保留null布局适配原有按钮位置,也可替换为FlowLayout等更规范的布局 home2 = new JButton("Home2"); home2.setBounds(20,20,100,50); inst = new JButton("insert"); inst.setBounds(60,60,100,50); balSGD = new JLabel("Bal:"+calculateBal(arrlistW, arrlistD)); balSGD.setBounds(50,100,100,50); topPanel.add(home2); topPanel.add(inst); topPanel.add(balSGD); finance_app obj=new finance_app(); home2.addActionListener(obj); inst.addActionListener(obj); // 创建表格与滚动面板 SGDtb = new JTable(); SGDtb.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); SGDtb.setPreferredScrollableViewportSize(new Dimension(420,63)); SGDtb.setFillsViewportHeight(true); JScrollPane SGDjs = new JScrollPane(SGDtb); // 将顶部面板和滚动面板添加到frame对应区域 frame3.getContentPane().add(topPanel, BorderLayout.NORTH); frame3.getContentPane().add(SGDjs, BorderLayout.CENTER); frame3.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG); frame3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 填充表格数据 addRowtoSGDJTable(); frame3.setVisible(true); }
addRowtoSGDJTable方法保持不变:
// 为表格添加行数据的方法 public void addRowtoSGDJTable() { DefaultTableModel model = (DefaultTableModel) SGDtb.getModel(); Object[]columnsName = new Object[4]; columnsName[0] = "TransactionID"; columnsName[1] = "AccountID"; columnsName[2] = "Amount"; columnsName[3] = "Description"; model.setColumnIdentifiers(columnsName); Object[] Data = new Object[4]; for(int x=0;x<transaction.size();x++) { Data[0] = transaction.get(x).getTransactionID(); Data[1] = transaction.get(x).getAccountID(); Data[2] = transaction.get(x).getTransactions(); Data[3] = transaction.get(x).getDescription(); model.addRow(Data); } }
额外说明
- 尽量避免使用
null布局,Swing的布局管理器能自动适配窗口尺寸变化,保证滚动条等组件的正常功能 - 确保JTable仅被包裹在JScrollPane中再添加到容器,不要重复将JTable直接添加到其他容器
内容的提问来源于stack exchange,提问作者Artem Ershov
相关产品推荐
相关产品推荐

