这是一个如此奇怪的问题(对我来说),我什至不知道如何问它。我有一个自定义控件 NewOtherPaidOutsEntry,其中包含两个文本字段、一个保存按钮和一个取消按钮。主窗口包含一个表单,该表单中有一个可选的 OtherPaidOuts 列表。NewOtherPaidOutsEntry 添加在此列表的底部,以便用户可以向列表添加条目。我创建了一个接口 NewOtherPaidOutsListener,其中包含一个方法 newOtherPaidOutsActionEmitted 和一个名为 setNewOtherPaidOutsListener 的 NewOtherPaidOutsEntry 方法。父表单像这样设置这个新条目(EditAction 只是一个枚举,请注意,为了清楚起见,我省略了真正的异常处理):private void setupNewEntry() { this.newEntry = new NewOtherPaidOutsEntry(this.shiftId); this.newEntry.setNewOtherPaidOutsListener((EditAction action) -> { try { handleNewOtherPaidOuts(action); } catch (Exception e) { handleException(e); } });}而 handleNewOtherPaidOuts 是这样的:private void handleNewOtherPaidOuts(EditAction action) { switch (action) { case SAVE: System.out.println("Save NewOtherPaidOuts"); OtherPaidOutsController.addShiftOtherPaidOut(newEntry); newEntry.reset(); layoutPanel(); shiftLeftPane.update(); break; case CANCEL: System.out.println("Cancel NewOtherPaidOuts"); break; }}我放入了 println 语句,并看到它在按钮被点击后立即执行。如果我逐步调试,一切都正常。但是如果我只是运行应用程序,OtherPaidOuts 的列表不会更新,直到我第二次单击新条目的保存按钮。第一次单击时,按钮保持按下状态。addShiftOtherPaidOut(newEntry) 执行数据库插入。newEntry.reset() 只是将两个文本字段设置为空文本。OtherPaidOuts 的列表在 JPanel OtherPaidOutsPane 中,作为 layoutPanel() 方法:protected void layoutPanel() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(createTitlePanel()); add(Box.createVerticalStrut(10)); getOtherPaidOutsEntries(); add(newEntry); add(Box.createVerticalGlue()); }getOtherPaidOutsEntries 方法只是获取此记录的现有条目列表并将它们添加到 OtherPaidOutsPane。然后将 OtherPaidOutsPane 嵌入到另一个 JPanel ShiftLeftPane 中。我想我可以只使用一个对话框来输入一个新条目,但是......我想我会先用这条路线尽力而为。如果我没有提供足够的示例代码,我深表歉意,但项目的这个阶段是如此根深蒂固,很难给出一个可运行的示例。请让我知道我还需要提供什么,我很乐意提供。请理解我是靠自己的座位飞行,所以请对任何解释友好;-)谢谢!
1 回答
鸿蒙传说
TA贡献1865条经验 获得超7个赞
当您将组件动态添加到可见 GUI 时,基本代码是:
panel.add(....);
panel.revalidate();
panel.repaint();
默认情况下,Swing 组件的大小是 (0, 0),因此没有什么可绘制的()。您需要 revalidate() 来调用布局管理器,根据布局管理器的规则为组件指定大小和位置。
我想我可以只使用一个对话框来输入一个新条目,
没有详细阅读您的整个问题,因为很难了解您正在做的事情的背景。
但是,如果您有多个条目,那么您可能应该使用 JTable 来显示数据。然后您可以使用 JDialog 来提示输入数据,然后将数据添加到 JTable。这比尝试添加/删除面板更容易管理。
添加回答
举报
0/150
提交
取消