有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java两个停靠组件,其中第二个组件填充剩余空间

我正在做一个棋盘游戏,我希望棋盘是一个正方形,向西停靠,尺寸为frameHeight x frameHeight,我希望侧面板停靠在东部,以填充剩余的

本质上:
西-帧高x帧高
东-剩余宽度x框架高度

 _________________
|          |      |
|          |      |
|  WEST    | EAST |
|          |      |
|          |      |
|__________|______|

使用MigLayout目前我说的是大(西)的高度应该是100%,但我不确定如何说宽度应该等于父高度的100%,并用小(东)填充剩余的宽度

有没有人能想出一个好办法


共 (3) 个答案

  1. # 1 楼答案

    您可以重写getPreferredSize()方法,根据面板的父级大小计算面板的大小。请记住,此时您完全忽略了面板中任何内容的大小。如果您仍然关心这个问题,我建议扩展JScrollPane而不是JPanel

    import java.awt.*;
    import javax.swing.*;
    
    public class TempProject extends JPanel{
    
        enum Type{
            SQUARE,
            FILL
        };
    
        Type mytype;
    
        public TempProject(Type type){
            mytype = type;
            if(mytype == Type.SQUARE){
                setBackground(Color.orange);
            } else if(mytype == Type.FILL){
                setBackground(Color.blue);
            }
        }
    
        @Override
        public Dimension getPreferredSize(){
            Dimension result = getParent().getSize();
            if(mytype == Type.SQUARE){
                //Calculate square size
                result.width = result.height;
    
            } else if(mytype == Type.FILL){
                //Calculate fill size
                int tempWidth = result.width - result.height;
                if(tempWidth > 0){  // Ensure width stays greater than 0
                    result.width = tempWidth;
                } else{
                    result.width = 0;
                }
            }
            return result;
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        JFrame f = new JFrame("Java Game");
                        f.setSize(700, 500);
                        f.setVisible(true);
                        f.setBackground(Color.GRAY);
    
                        Box contentPanel = Box.createHorizontalBox();
                        contentPanel.add(new TempProject(Type.SQUARE));
                        contentPanel.add(new TempProject(Type.FILL));
                        f.setContentPane(contentPanel);
    
                        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
    
        }
    
    }
    
  2. # 2 楼答案

    1. 如果DockingPanel可以覆盖JFrame的一部分(具有显示和隐藏的功能),则使用

      • GlassPane(注意所有的JComponents必须是lightweight,否则GlassPane就落后了)

      • JLayer(基于Java6JXLayer

    2. 最合适的方法是使用JSplitPane

  3. # 3 楼答案

    MiGLayout不允许对大小约束使用引用,但可以使用pos约束:

    add(panel, "id large, pos 0 0 container.h container.h");
    

    这将添加panel似乎停靠在左边缘,覆盖整个高度,宽度等于其高度

    然后,您可以用以下内容填充剩余的空间:

    add(otherPanel, "pos large.x2 0 container.w container.h");