首页 > 解决方案 > 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;
}

} output of the program

标签: javaswingjpaneljlabellayout-manager

解决方案


就个人而言,我会使用 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;
    }
}

您可能想花更多时间查看课程:在容器中布置组件


推荐阅读