几周前我最近开始使用 Java GUI,但我在对齐方面遇到了困难。基本上,我试图让两个面板具有不同的背景图像(顶部栏和内容),我想一个接一个地对齐它们。问题是,我不能使用BorderLayout.NORTH
and BorderLayout.SOUTH
,因为背景图像失去了原来的大小并且变得非常小。
如何正确对齐它们,而不会丢失原始尺寸?
这是我的代码:
package main;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageTest {
public static void main(String[] args) {
ImageFrame frame = new ImageFrame("topBar.png", "contentImage.png");
frame.setSize(640,480);
frame.setVisible(true);
}
}
class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
class ImageFrame extends JFrame {
public ImageFrame(String topBar, String body) {
setLayout(new BorderLayout());
ImagePanel topPanel = new ImagePanel(topBar);
ImagePanel bodyPanel = new ImagePanel(body);
add(topPanel, BorderLayout.NORTH);
add(bodyPanel, BorderLayout.SOUTH);
pack();
}
}