【问题标题】:Why must I use getContentPane() instead of "this" when setting a BoxLayout for a JFrame?为什么在为 JFrame 设置 BoxLayout 时必须使用 getContentPane() 而不是“this”?
【发布时间】:2014-06-02 21:51:36
【问题描述】:

在将 JFrame 的布局设置为 BoxLayout 时,为什么我必须使用 getContentPane() 而不是 this 关键字作为 BoxLayout 的参数参数。为了给 JPanel 一个 BoxLayout,我必须使用 this 作为参数。

我认为这是因为 JFrame 具有多个层或部分,它们是玻璃窗格、分层窗格、内容窗格和菜单栏。所以 this 关键字指的是 JFrame,但它不是指我们想要配置布局管理器的内容窗格。这就是我们调用 getContentPane() 的原因。我读到 JFrame 的内容窗格实际上是一个 JPanel。

总结一下:BoxLayout 的目标参数接受 JPanel 但不接受 JFrame,但 JFrame 的内容窗格是 JPanel。

class MyFrame1 extends JFrame {
    public MyFrame1() {    
        // This line does not work, why? 
        setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); 
    }
}

class MyFrame2 extends JFrame {
    public MyFrame2() {    
        // This line works
        setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
    }
}

class MyPanel extends JPanel {
    public MyPanel() {
        // JPanel uses "this" keyword
        setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
    }
}

JPanel 是否像 JFrame 一样有多个窗格?我必须使用 getContentPane() 的实际原因是什么?

当编译器说不能共享 BoxLayout 时,是否意味着不能在组成 JFrame 的多个窗格之间共享 BoxLayout?

【问题讨论】:

  • 编译器真的这么说吗?
  • 是的,每次第一个参数(目标)采用错误参数时都会发生这种情况。
  • 我认为没有发生错误,因为我在 MyFrame1 中有正确的代码(这是一个意外,我已将其更改为包含不正确的代码)。
  • 编译器真的说'BoxLayout不能共享'?
  • “线程“主”java.awt.AWTError 中的异常:无法共享 BoxLayout”

标签: java swing user-interface boxlayout contentpane


【解决方案1】:

JFrameContainer,但不是Container "that needs to be laid out." 相反,getContentPane() 返回的Container 是可以使用BoxLayout 实例的BoxLayout。或者考虑下面使用Box 的变体,“使用BoxLayout 对象作为其布局管理器的轻量级容器。”

Box b = Box.createVerticalBox();
b.add(new JLabel("Test"));
f.setContentPane(b);

经测试:

import java.awt.EventQueue;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JLabel;

/** @see http://stackoverflow.com/a/23159430/230513 */
public class Test {

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Box b = Box.createVerticalBox();
        b.add(new JLabel("Test"));
        f.setContentPane(b);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Test().display();
            }
        });
    }
}

【讨论】:

    猜你喜欢
    • 2011-02-25
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    相关资源
    最近更新 更多