gpt4 book ai didi

java - 如何在java中对齐JPanel

转载 作者:行者123 更新时间:2023-12-01 18:37:28 25 4
gpt4 key购买 nike

我有一个采用框布局的 JPanel,但我不确定如何将 JPanel 与窗口中心对齐(即使调整窗口大小也保持居中)我尝试寻找解决方案,但所有问题似乎都结束了与我正在寻找的东西相比,这很复杂。

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

public class Stacker extends JFrame {
public Stacker() {
super("Stacker");
setSize(430, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create top panel
JPanel commandPane = new JPanel();
BoxLayout vertical = new BoxLayout(commandPane,
BoxLayout.Y_AXIS);
commandPane.setLayout(vertical);

JButton subscribe = new JButton("Subscribe");
JButton unsubscribe = new JButton("Unsubscribe");
JButton refresh = new JButton("Refresh");
JButton save = new JButton("Save");

commandPane.add(subscribe);
commandPane.add(unsubscribe);
commandPane.add(refresh);
commandPane.add(save);

JMenuItem j1 = new JMenuItem("File");
JMenuItem j2 = new JMenuItem("Open");
JMenuItem j3 = new JMenuItem("Close");
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("Feeds");
menu.add(j1);
menu.add(j2);
menu.add(j3);
menubar.add(menu);

setJMenuBar(menubar);



// create bottom panel
/*JPanel textPane = new JPanel();
JTextArea text = new JTextArea(4, 70);
JScrollPane scrollPane = new JScrollPane(text);
// put them together
FlowLayout flow = new FlowLayout();
setLayout(flow);
add(commandPane);
add(scrollPane); */
setJMenuBar(menubar);
add(commandPane);
setVisible(true);
}

public static void main(String[] arguments) {
Stacker st = new Stacker();
}
}

最佳答案

您说您正在使用 BoxLayout,但是带有 BoxLayout 的 JPanel 是您想要居中的 JPanel,还是它包含您想要居中的 JPanel?

如果它包含您想要居中的 JPanel,那么您可以在要居中的 JPanel 的任一侧添加胶水。如果它是您想要居中的 JPanel,那么您可以使用 GridBagLayout 或 BoxLayout 来实现您所说的效果。

谷歌搜索“Java 中心组件”之类的内容会给您带来大量结果。

关于java - 如何在java中对齐JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21310529/

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