java - Cannot align jlabel in a jpanel
问题描述
I have problems aligning the JLabel playButton. I don't know if the other elements in the panel cause the issue, but nothing that I tried fixed this. The label is showing at the bottom of the screen (centered horizontally, because of the setAlignmentX) and nothing can move it up. All of my components are positioned in a vertical line, so I need to use BoxLayout. However, I cannot understand why all of a sudden the label is positioned so far away from the other elements, which appear completely fine.
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;
}
解决方案
就个人而言,我会使用 a GridBagLayout
,它更复杂,但更灵活......
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Frame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Frame frame = new 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);
// That's pointless
//frame.setLayout(new BorderLayout());
// That's pointless
//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 GridBagLayout());
panel.setOpaque(false);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.weightx = 1.0;
gbc.insets = new Insets(50, 0, 0, 0);
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(human, gbc);
gbc.insets = new Insets(30, 0, 0, 0);
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(text, gbc);
gbc.fill = GridBagConstraints.NONE;
panel.add(playButton, gbc);
frame.add(panel);
frame.setVisible(true);
}
private JLabel ImageSize(int x, int y, String fileName) //Method for image resizing
{
BufferedImage baseImg = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = baseImg.createGraphics();
g2d.setColor(Color.RED);
g2d.fillRect(0, 0, x, y);
g2d.dispose();
// 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(new ImageIcon(baseImg));
return imageLabel;
}
}
您可能想花更多时间查看课程:在容器中布置组件
推荐阅读
- azure - Azure 逻辑应用 - 从 http 请求接收文件
- bash - 如何将复杂的文件 glob 传递给子 shell?
- javascript - 如何在网页上找到这个元素?
- regex - 如何从 1 匹配到 12。给定 Version/13.1.2
- google-cloud-platform - 从 Java 中的 pub sub 流式传输时使用 PubSub-NullPointerException 进行 Spark Streaming
- python-3.x - 无法创建多个类的对象
- google-apps-script - exec节点调用gaction令牌时如何将其传递给gactions(无运算符)
- php - 如何为路由中的多个参数实现“defaults()” - Laravel
- java - Mac 10.15 上的 ElasticSearch 错误“/System/Volumes/Data/usr/local/var/lib/elasticsearch/nodes/0”“写入”
- java - Wildfly 14 中带有 Infinispan 的本地缓存