【问题标题】:How can I set the insets of a JFrame?如何设置 JFrame 的插图?
【发布时间】:2012-12-16 13:12:41
【问题描述】:

有没有办法设置JFrame 的插入? 我试过了

frame.getContentPane().getInsets().set(10, 10, 10, 10);

frame.getInsets().set(10, 10, 10, 10);

但它们似乎都不起作用。

【问题讨论】:

  • 如果内容窗格使用JPanel,只需panel.setBorder(new EmptyBorder(10,10,10,10));
  • @AndrewThompson 如果 OP 询问设置框架上的插图,为什么不直接覆盖 getInsets()
  • @Dan 1) Is “Don't do it” a valid answer? 2) Composition over inheritance 3) 我们很少能使用单一布局来制作应用程序,因此不妨创建一个主面板作为内容面板。 4) 但除了这三个令人信服的原因之外,我想不是。

标签: java swing jframe insets


【解决方案1】:

您可以创建一个主 JPanel 并将其他所有内容插入其中。

然后你可以使用BorderFactory创建EmptyBorderLineBorder

看到这个答案: https://stackoverflow.com/a/17925693/8953378

【讨论】:

    【解决方案2】:

    由于这个问题没有明确的答案,但您可以像basiljames 所说的here 那样做。正确的做法是扩展JFrame,然后覆盖getInsets() 方法。

    例如

    import javax.swing.JFrame;
    import java.awt.Insets;
    
    public class JFrameInsets extends JFrame {
        @Override
        public Insets getInsets() {
            return new Insets(10, 10, 10, 10);
        }
    
        private JFrameInsets()  {
            super("Insets of 10");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
            setMinimumSize(getSize());
            setVisible(true);
        }
    
        public static void main(String[] args) {
            new JFrameInsets();
        }
    }
    

    【讨论】:

    • 这不是一个好方法,因为在调整大小的情况下插入会被破坏
    【解决方案3】:
    JPanel contentPanel = new JPanel();
    
    Border padding = BorderFactory.createEmptyBorder(10, 10, 10, 10);
    
    contentPanel.setBorder(padding);
    
    yourFrame.setContentPane(contentPanel);
    

    所以基本上,contentPanel 是框架的主要容器。

    【讨论】:

    • 我没有使用getContentPane方法,我创建了一个JPanel名称contentPanel来访问setBorder方法。
    【解决方案4】:

    覆盖JFrameInsets 不会解决您的实际问题。 要回答您的问题,您不能设置 JFrame 的插图。您应该扩展 JFrame 并覆盖 getInsets 方法以提供您需要的插图。

    【讨论】:

      【解决方案5】:

      你必须创建一个 LayOutConstraint 的对象并设置它的 Insets。 就像下面的例子一样,我使用了 GridBagLayout() 并使用了 GridBagConstraint() 对象。

          GridBagConstraints c = new GridBagConstraints();
          JPanel panel = new JPanel(new GridBagLayout());
          c.insets = new Insets(5, 5, 5, 5); // top, left, bottom, right
          c.anchor = GridBagConstraints.LINE_END;
      
          // Row 1
          c.gridx = 0;
          c.gridy = 0;
          c.anchor = GridBagConstraints.LINE_START;
          panel.add(isAlgoEnabledLabel, c);
      

      【讨论】:

        猜你喜欢
        • 2013-03-17
        • 2020-05-06
        • 1970-01-01
        • 1970-01-01
        • 2015-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多