几周前,我尝试过使用 Swing(第一次),我自己冒险了一段时间,以获得更好的感觉。我似乎遇到了垂直对齐的问题。
情况如下:我在边界布局的西部有一个 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,我明白为什么了。标签不是那么小,我以错误的方式填充背景(白框并不代表实际的标签)。谢谢您的帮助。