gpt4 book ai didi

java - 如何从 JPanel 类访问 JFrame 组件?

转载 作者:行者123 更新时间:2023-12-01 22:29:44 24 4
gpt4 key购买 nike

我正在处理 GUI 作业,遇到了一个无法解决的问题。我有一个带有多个 JPanel 的 JFrame,其中一个 JPanel 包含一个带有多个 JPanel 的 CardLayout。由于我们有更多的人致力于该项目,因此我们决定为 CardLayout 内的每个面板创建一个单独的类(扩展 JPanel)。

问题是从 JPanel 类访问 JFrame 的组件。

举个例子,我在 JFrame 中的某个位置有一个 JLabel 用作状态栏,并且我想在按下 SaleMain 面板上的按钮时更改状态栏的文本(扩展 JPanel 的 SaleMain 类) ,包含在 CardLayout 中)。

另一个例子,在另一个面板 EditCustomer (也是一个 JPanel 类,包含在 CardLayout 中)中,我想要一个带有操作监听器的按钮,该按钮会将当前面板(包含该按钮的面板)更改为不同的面板CardLayout 中的面板。

希望我说得尽可能清楚,提前感谢你们帮助我:)

最佳答案

model / view / controller pattern (MVC) 对于创建 GUI 很有用。通过将模型与 View 分离,您可以一次专注于 GUI 的一部分。

您为 GUI 创建一个模型,其中包含要在 GUI 上显示的信息。

I have a JLabel somewhere in the JFrame that serves as a status bar and I want to change the text of the status bar when a button is pressed on the SaleMain panel

将文本放入模型中,并在按钮的操作监听器中将文本放入状态栏中。

I'd like to have a button with an action listener that will change the current panel (the one containing the button) to a different panel from the CardLayout.

那就这样做吧。 Action 监听器是一个可以改变 View 的 Controller 。

看看我的文章,Dice Game ,了解 Java Swing 应用程序如何实现 MVC 模式和 JPanel 切换。

关于java - 如何从 JPanel 类访问 JFrame 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28072952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com