gpt4 book ai didi

java - Swing 和 JPanels,布局管理器

转载 作者:行者123 更新时间:2023-12-03 22:52:19 26 4
gpt4 key购买 nike

我在几周前尝试过(第一次)使用 Swing,然后我自己尝试了一下,以便更好地感受它。我似乎遇到了垂直对齐的问题。

情况是这样的:我在 borderlayout 的西部有一个 boxlayout(Y_AXiS) JPanel。在带 boxlayout 的 JPanel 内部,我有两个我想要垂直对齐的 JPanel(无论框架的尺寸如何,都被推向屏幕顶部)。然而,布局管理器似乎在两个 JPanel 之间放置了一个很大的垂直空间。我在想也许网格布局更适合这个,但我不确定。我曾多次尝试在谷歌上寻找答案并纠正问题,但没有成功。请帮忙!

package com.granet;

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


public class CustomerOrganizer extends JFrame
{
public CustomerOrganizer()
{
JPanel topPanel = new JPanel();
topPanel.setBackground(Color.darkGray);

JLabel customerSlogan = new JLabel("Customer Organizer");

topPanel.add(customerSlogan);



JPanel leftPanel = new JPanel();
leftPanel.setBackground(Color.darkGray);
leftPanel.setBorder(new EmptyBorder(10,100,00,0));


leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));

DrawPanel firstTab = new DrawPanel(Color.white, 350, 50);
DrawPanel secondTab = new DrawPanel(Color.white, 350, 50);

JLabel firstTabText = new JLabel("First Tab");
JLabel secondTabText = new JLabel("Second Tab");

firstTab.setBorder(new EmptyBorder(0,60,60,0));
secondTab.setBorder(new EmptyBorder(0,60,60,0));

firstTab.add(firstTabText);
secondTab.add(secondTabText);


leftPanel.add(firstTab);
leftPanel.add(secondTab);

firstTab.setAlignmentX(Component.LEFT_ALIGNMENT);
secondTab.setAlignmentX(Component.LEFT_ALIGNMENT);

/* DOESN'T WORK, I'm pretty sure this changes the point on the jpanel which used for alignment (top, bottom, left or right)
firstTab.setAlignmentY(Component.TOP_ALIGNMENT);
secondTab.setAlignmentY(Component.TOP_ALIGNMENT);
*/


add(topPanel, BorderLayout.NORTH);
add(leftPanel, BorderLayout.WEST);

pack();

}

public static void main(String[] args)
{
CustomerOrganizer frame = new CustomerOrganizer();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,400);
frame.setVisible(true);

}
}

绘图面板.java

package com.granet;

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

public class DrawPanel extends JPanel
{
Color color;
int width;
int height;

public DrawPanel(Color color, int width, int height)
{
this.color=color;
this.width=width;
this.height=height;
}

public DrawPanel()
{
this.color = Color.darkGray;
this.width=this.getWidth();
this.height=this.getHeight();
}

public void paintComponent(Graphics g)
{
g.setColor(color);
g.fillRect(0, 0, width, height);
}
}

这是我运行时看到的: http://concertforhope.net/citeforme/javabug.png

请注意,底部标签没有被推到顶部标签上。

NVM,我知道为什么了。选项卡并没有那么小,我以错误的方式填充了背景(白框并不代表实际的选项卡)。感谢您的帮助。

最佳答案

这不是错误。 boxlayout 应该在组件之间平均划分整个空间。

您可能想要垂直布局或类似的布局。

我真的建议你得到 Google WindowBuilder (免费)并尝试使用 GUI 中的布局。

在您的特殊情况下,您还可以考虑 JTabbedPane在右边有一个标签位置。

关于java - Swing 和 JPanels,布局管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6316145/

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