【发布时间】:2019-05-09 16:16:32
【问题描述】:
我在对齐 JLabel 播放按钮时遇到问题。我不知道面板中的其他元素是否会导致问题,但我没有尝试解决此问题。标签显示在屏幕底部(水平居中,因为 setAlignmentX),没有任何东西可以将其向上移动。我所有的组件都位于一条垂直线上,所以我需要使用 BoxLayout。但是,我不明白为什么突然标签的位置离其他元素如此之远,而其他元素看起来完全没问题。
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Vector;
public class Frame {
private final int WIDTH = 1024;
private final int HEIGHT = 768;
private JFrame frame;
private JPanel panel;
private JLabel human;
private JTextArea text;
public Frame()
{
this.frame = new JFrame();
this.panel = new JPanel();
this.human = ImageSize(200, 200, "res/human.png");
this.text = new JTextArea("You have lost in the forest. Now you have to find " +
"your way back.");
//frame setup
frame.setTitle("Shady Path");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.pack();
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
frame.getContentPane().setBackground(Color.BLACK);
frame.setResizable(false);
//main text setup
Font font = new Font(Font.MONOSPACED, Font.PLAIN, 20);
text.setEditable(false);
text.setForeground(Color.WHITE);
text.setFont(font);
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setMargin(new Insets(0, 300, 0, 300));
text.setOpaque(false);
//button setup
JButton button = new JButton();
JLabel playButton = new JLabel("Play");
playButton.setFont(font);
playButton.setForeground(Color.WHITE);
playButton.add(button);
//panel setup and adding elements
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setOpaque(false);
panel.add(Box.createVerticalStrut(50));
panel.add(human);
human.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(Box.createVerticalStrut(30));
panel.add(text);
text.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.add(Box.createVerticalStrut(30));
panel.add(playButton);
playButton.setAlignmentX(Component.CENTER_ALIGNMENT);
playButton.setAlignmentY(Component.CENTER_ALIGNMENT);
frame.add(panel);
frame.setVisible(true);
}
private JLabel ImageSize(int x, int y, String fileName) //Method for image resizing
{
BufferedImage baseImg = null;
try {
baseImg = ImageIO.read(new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
Image resizedImg = baseImg.getScaledInstance(x, y, Image.SCALE_SMOOTH);
ImageIcon IconImg = new ImageIcon(resizedImg);
JLabel imageLabel = new JLabel(IconImg);
return imageLabel;
}
【问题讨论】:
-
欢迎来到 Stackoverflow!请将您的代码设为MCVE,以便我们自己运行代码。没有太多遗漏,只有一个方法、类声明、一些导入和一个 main 方法。并且可能添加问题的屏幕截图。
-
我会使用 GridBagLayout,但这就是我
-
我刚开始学习,所以我还不知道哪种布局最好用。如果没有人能解决这个问题,我会改变布局
标签: java swing jpanel jlabel layout-manager