我有一个非常具体的布局,我一直试图完成一段时间没有成功。我试图创建的布局只是放置一个固定高度的JPanel,位于另一个面板的垂直中心。水平方向,它应该伸展以适应另一方的界限。
同样,需要的是:
根据几个人要求我发布不起作用的代码:
JPanel MainPanel = new JPanel();
frmPhoneClicker.getContentPane().add(MainPanel);
MainPanel.setLayout(new MigLayout("", "[984px]", "[165px]"));
Panel subPanel = new JPanel();
subPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
MainPanel.add(subPanel, "cell 0 0 1 1,growx,aligny center");
答案 0 :(得分:3)
您肯定需要了解有关Layouts的更多信息GridBagLayout会有所帮助。但是你走了:
// your Panels
JPanel mainPanel = new JPanel();
JPanel subPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout()); // use GridBagLayout with mainPanel
subPanel.setPreferredSize(new Dimension (0,165)); // use a preferred height for the subPanel
GridBagConstraints c = new GridBagConstraints(); // your gridBagLayout Constraints
c.fill = GridBagConstraints.HORIZONTAL; // stretch subPanel horizontal
c.weightx = 1.0; // with 100% of screen
mainPanel.add(subPanel,c); // add sub to mainPanel with the constraints
答案 1 :(得分:2)
一个完整的工作示例,颜色可以遵循您的方案:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class testPanel extends JFrame{
public testPanel() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
this.setSize(screenWidth / 2, screenHeight * 2 / 3);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(true);
this.setAlwaysOnTop(false);
this.setUndecorated(false);
JPanel outerPanel = new JPanel(new GridBagLayout());
outerPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
JPanel innerPanel = new JPanel();
innerPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
innerPanel.setPreferredSize(new Dimension (0,300));
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;//Size
outerPanel.add(innerPanel, c);
this.add(outerPanel);
this.setVisible(true);
}
}
请注意,如果包含的窗口大小低于innerPanel
的大小,则固定高度将不再适用。