【问题标题】:Controlling another class from a different class控制来自不同班级的另一个班级
【发布时间】:2011-12-16 07:00:21
【问题描述】:

我在 Swing 方面遇到了一些问题。我有一个JFrame,叫做FrameMain。里面是一个JPanel,叫做panelChoices

FrameMain 被调用/创建时,它用多个PanelEntries 对象填充panelChoices 对象,这是一个JPanel,其中包含多个JButtons(它是一个不同的我写的课)。

我想要做的是,当我单击 PanelEntries 对象内的一个按钮时,我想销毁/删除 FrameMain,以及它的其余组件(包括包含JButton)。

我尝试过使用super,但它返回的JPanelPanelEntries 对象)包含JButton,而不是FrameMain 将它们组合在一起。我怎样才能做到这一点?

编辑:似乎我不够清楚,所以这里有一些我工作中的更多信息。我现在没有实际代码,因为我在另一台机器上,但我希望这有助于详细说明我的问题。

public class FrameMain() {
    private JFrame frameMain;
    private JPanel panelChoices;

    public FrameMain(args) {
        createGUI();
        loadData();
    }

    private void createGUI() {
        JFrame frameMain = new JFrame();
        JPanel panelChoices = new JPanel(new GridLayout(1,1));
        frameMain.add(panel);
        // removed formatting and other design codes since they are not important.
        pack();
    }

    private void loadData() {
        boolean available;
        for (int i = 1; i <= 10; i++) {
            // do some if/else and give value to boolean available
            PanelEntries panel = new PanelEntries(i, available);
            frameMain.add(panel);
            // more code here to handle data.
        }
    }
}

public class PanelEntries() extends JPanel {

    public PanelEntries(int num, boolean avb) {
        JButton button = new JButton("Button Number " + num);
        button.setEnabled(avb);
        add(button);
        // add action listener to created button so that it calls 'nextScreen()' when clicked.
        // more code
        pack();
    }

    private void nextScreen() {
        // destroy/dispose MainFrame here.
        // See Notes.
        AnotherFrame anotherFrame = new AnotherFrame();
    }
}

注意事项

  1. 所有类都在它们自己的.java 文件中。
  2. 我需要知道如何从 PanelEntries 对象内的按钮中释放 FrameMain,而不仅仅是释放 JFrame。

【问题讨论】:

  • 请提供您的代码摘录。我认为这比一堵文字墙更容易理解
  • 听起来您正试图“退出”应用程序。这是正确的吗?
  • superJPanel 返回什么?它是否返回FrameMainsuper.dothis()JPanel 中运行 dothis()。然后super.dothat() in Jpanel 应该给你你需要的东西。
  • @fyr:我已经编辑了这个问题。我希望现在很清楚。
  • @JacoVanNiekerk 不,我只需要从PanelEntries 对象中处理FrameMain 对象。

标签: java swing panels


【解决方案1】:

根据给定的信息,

  1. 如果你想退出应用程序,使用System.exit(0); 没什么大不了的:)

  2. 如果您要处理框架,jframe.dispose();

  3. 如果您想删除一个组件/所有组件,您可以使用.remove(Component) / .removeAll()

如果这没有帮助,请用更多信息重新编写您的问题。

【讨论】:

    猜你喜欢
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 2016-06-06
    相关资源
    最近更新 更多