gpt4 book ai didi

java - 如何使用 GridBagLayout 将组件放在右下角?

转载 作者:搜寻专家 更新时间:2023-10-31 08:20:51 24 4
gpt4 key购买 nike

我需要在 JPanel 中显示单个组件,并且我想始终将该组件保持在右下角。我试着用 GridBagLayout 来做:

val infoArea = new TextArea {
text = "Hello!"
border = Swing.EmptyBorder(30)
background = Color.RED
editable = false
}
val p = new JPanel
p.setLayout(new GridBagLayout)
val c = new GridBagConstraints
c.gridx = 0
c.gridy = 0
c.anchor = GridBagConstraints.LAST_LINE_END
p.add(infoArea.peer,c)
val f = new JFrame
f.setContentPane(p)
f.setVisible(true)

但由于某种原因文本区域位于中心:

enter image description here

我在这里做错了什么?

最佳答案

例如:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.*;

public class LayoutDemo {
private static void createAndShowGui() {
JLabel label = new JLabel("Hello");
label.setOpaque(true);
label.setBackground(Color.red);

JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(label, BorderLayout.LINE_END);

JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
mainPanel.setPreferredSize(new Dimension(400, 400));


JFrame frame = new JFrame("LayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

enter image description here

关于java - 如何使用 GridBagLayout 将组件放在右下角?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7905731/

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