JLabels 在我的滚动面板中的坐标不正确

问题描述

我正在试验可滚动 JPanel,但在放置 JLabel 时发现了一个问题。在下面的代码中,我尝试在我的面板中使用 x 和 y 坐标在另一个标签下放置 2 个标签。我不知道为什么它们要紧挨着放置,而且总是在面板的中央。

我的代码

public class ScrollTest extends JFrame {
    //GUI Items
    private static final int SCREEN_WIDTH = 750,SCREEN_HEIGHT = 600;
    private JPanel panel;
    private JLabel title,description;

    public Scrolltest(){
        panel = new JPanel();
        panel.setBackground(Color.WHITE);
        panel.setopaque(true);

        //JLabels
        title = new JLabel("Title");
        title.setFont(new Font("TimesRoman",Font.BOLD,30));
        title.setBounds(40,50,500,40);
        panel.add(title);

        description = new JLabel("Description:");
        description.setFont(new Font("TimesRoman",20));
        description.setBounds(40,90,40);
        panel.add(description);

        add(new JScrollPane(panel));
        setSize(SCREEN_WIDTH,SCREEN_HEIGHT);
        setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
}

解决方法

由于您只显示两个 JLabel,我认为单列 GridLayout 是合适的。另请注意,您不必编写扩展 JFrame 的类。一开始,所有Swing 示例代码都这样做了,但这不是必需的。而且您不必在类的构造函数中构建 GUI。

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;

public class ScrollTest {
    private static final int SCREEN_WIDTH = 750,SCREEN_HEIGHT = 600;

    private void showGui() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new GridLayout(0,1));
        JLabel title = new JLabel("Title",SwingConstants.CENTER);
        title.setFont(new Font("TimesRoman",Font.BOLD,30));
        panel.add(title);
        JLabel description = new JLabel("Description:");
        description.setFont(new Font("TimesRoman",20));
        panel.add(description);
        frame.add(new JScrollPane(panel));
        frame.setSize(SCREEN_WIDTH,SCREEN_HEIGHT);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new ScrollTest().showGui());
    }
}

这是它的样子。

screen capture of running app

因为您将 JFrame 的大小设置为大尺寸,所以看不到滚动条。有关 JScrollPane constructor,请参阅 javadoc