【问题标题】:Accomdations to be made if not extending JFrame?如果不扩展 JFrame 要进行调整?
【发布时间】:2014-01-15 21:04:11
【问题描述】:

我一直在从 YouTube 视频中学习 Java Swing GUI,因为我要到大学下学期末才学习它们,而且我觉得等待太有趣了。然而,虽然视频制作者让它很容易上手,而且我学到了很多东西,但我可以说他可能是自己学的,因为他的一些编码实践与我们在学校学到的有点不同。 (例如,他不关心封装或驼峰式。)这让我担心我所学的一切都将毫无用处。

他在视频中所做的所有项目都在一个类中,使用实现 ActionListener、MouseListener 等的内部类。所以我不知道如何将我从这些视频中学到的东西与无 GUI 的多类项目联系起来我在学校工作过。

我将举一个项目的一般示例:(我只是添加私有,因为这是我习惯的)

public class Something extends JFrame {
   private JPanel topPanel;
   private JPanel bottomPanel;
   private JLabel label;
   private JButton button;

   public Something() {

    Container pane = this.getContentPane(); //need help with this

    topPanel = new JPanel();
    topPanel.setLayout(new GridLayout(1,1));

    label = new JLabel("x");
    topPanel.add(label);
    pane.add(topPanel);

    bottomPanel = new JPanel();
    bottomPanel.setLayout(new GridLayout(1,1));

    button = new JButton("Button");
    bottomPanel.add(button);
    pane.add(bottomPanel);

    Event e = new Event();
    button.addActionListener(e);

  }

  public class Event implements ActionListener {

   }

另外,我在这里阅读了另一个关于为什么扩展 JFrame 是一个坏主意的帖子。如果我必须适应,我会创建一个 JFrame 框架,然后添加(框架)吗?然后确保我将下一层添加到框架中?我必须做哪些住宿?

【问题讨论】:

  • 在学习 GUI 之前,或者在学习 GUI 的同时,还要好好学习接口、设计模式和依赖注入的概念。
  • 如果您正在寻找更多关于 swing 的帮助,您应该查看 Oracle 的 tutorial

标签: java swing user-interface jframe


【解决方案1】:

一般来说,您不应该扩展 JFrame。相反,扩展 JPanel。例如您的代码可能如下所示:

public class Something extends JPanel {
  // very similar code to yours goes here
  // though I'd set a specific LayoutManager
}

现在您拥有了更多的灵活性:您可以将精彩的 GUI 添加到 JFrame、JDialog 或另一个更复杂的 JPanel 中。例如

JDialog dialog = new JDialog();
JPanel reallyComplexPanel = new JPanel(new BorderLayout());
// add in stuff here, e.g buttons at the bottom
Something mySomething = new Something();
reallyComplexPanel .add(mySomething, BorderLayout.NORTH);  // my stuff at the top
dialog.setContentPane(reallyComplexPanel);

【讨论】:

  • contentPane 到底是什么?我使用它,但我不是 100% 定义它是什么。是在 JFrame 下方但在 Panel 上方的级别吗?
猜你喜欢
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 2013-09-12
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多