gpt4 book ai didi

java - 使用 JFrame 和对齐

转载 作者:行者123 更新时间:2023-12-01 10:04:03 25 4
gpt4 key购买 nike

当天早些时候我问了另一个 JFrame 问题,并能够解决我的问题,但现在我遇到了另一个障碍。我需要我的 UI 看起来像图中所示,但我不知道如何使用 LayoutManager 让它们彼此堆叠。如果两者都使用 BorderLayout South,则只有最近添加的一个可见。有什么建议吗?

它应该是这样的: enter image description here

这是我的代码:

JFrame frame = new JFrame();
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
JPanel textPanel = new JPanel();

textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.X_AXIS));

JTextField textField = new JTextField();
textField.setMaximumSize((new Dimension(10000,25)));

textPanel.add(new JLabel("Filename:"));
textPanel.add(textField);
textPanel.add(new JButton("Load"));

frame.add(textPanel);

buttonPanel.add(new JButton("Play"));
buttonPanel.add(new JButton("Stop"));


frame.add(buttonPanel, BorderLayout.SOUTH);

frame.setSize(500, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

最佳答案

利用另一个容器将 textPanebuttonPane 放入

Compound Panels

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

public TestPane() {
setLayout(new BorderLayout());

JPanel textPane = new JPanel(new GridBagLayout());
JTextField textField = new JTextField(20);

textPane.add(new JLabel("Filename:"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
textPane.add(textField, gbc);
textPane.add(new JButton("Load"));

JPanel buttonPane = new JPanel();
buttonPane.add(new JButton("Play"));
buttonPane.add(new JButton("Stop"));

JPanel southPane = new JPanel(new GridLayout(2, 0));
southPane.add(textPane);
southPane.add(buttonPane);

add(new JLabel("I'm in the center"));
add(southPane, BorderLayout.SOUTH);
}

}

}

关于java - 使用 JFrame 和对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36587230/

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