gpt4 book ai didi

java - JPanel 无法使用 GridBagLayout 正确显示

转载 作者:行者123 更新时间:2023-12-01 22:35:20 28 4
gpt4 key购买 nike

import java.awt.*;
import javax.swing.*;

import javax.swing.*;

public class Cashmain extends JFrame{

private GridBagConstraints gbc;
Header jpanel1 = new Header();
Body jpanel2 = new Body();

public Cashmain(){
super("cashcashpinoy");
Toolkit tk = Toolkit.getDefaultToolkit();
int xSize = ((int) tk.getScreenSize().getWidth());
int ySize = ((int) tk.getScreenSize().getHeight());
setSize(xSize,ySize);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();


gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
add(jpanel2, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
add(jpanel1, gbc);

面板无法正确显示。该框架在中心显示 2 个小面板。请帮我!

这就是我的程序应该是这样的:

enter image description here

最佳答案

仅使用 BorderLayout 会更简单,但否则,您的问题是您没有将第二个组件的 weighty 设置为正值。

这是一个小片段,说明了这两个选项并允许您切换到另一个选项。

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class TestLayouts {

protected void initUI(final boolean useBorderLayout) {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton header = new JButton("My Header (Click-me to switch layout current layout is "
+ (useBorderLayout ? "BorderLayout" : "GridBagLayout"));
header.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
TestLayouts.this.initUI(!useBorderLayout);
frame.dispose();
}
});
JLabel someOtherComponent = new JLabel("Some other component");
someOtherComponent.setHorizontalAlignment(JLabel.CENTER);
if (useBorderLayout) {
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(header, BorderLayout.NORTH);
frame.getContentPane().add(someOtherComponent, BorderLayout.CENTER);
} else {
frame.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
frame.getContentPane().add(header, gbc);
gbc.gridy = 1;
gbc.weighty = 1.0;
frame.getContentPane().add(someOtherComponent, gbc);

}
frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestLayouts().initUI(true);
}
});
}

}

关于java - JPanel 无法使用 GridBagLayout 正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26958119/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com