我想将JPanel放在JScrollpane中,我编写了这段代码,但是没有用
所以我需要你的帮助

    centerPanel_scroll = new JScrollPane();
    centerPanel_scroll.setBounds(261, 71, 750, 698);
    center_panel = new JPanel();
    center_panel.setLayout(null);
    center_panel.setBackground(Color.cyan);
    centerPanel_scroll.setViewportView(center_panel);
    main_panel.add(centerPanel_scroll);

最佳答案

您的center_panel在JScrollPane中。视口不考虑大小/边界,而是首选大小,因此,如果需要,请通过setPreferredSize(...)设置首选大小,或者甚至更好,使组件扩展getPreferredSize()

我不知道您要通过261、71处的setBounds位置实现什么目标。该位置在视口中,因此毫无意义。

同样,您可能会弄乱使用null布局,而JScrollPanes可能会对null布局造成很多麻烦。只需不设置边界/大小或使用空布局,您就会发现生活变得容易得多。

例如。,

centerPanel_scroll = new JScrollPane();
// centerPanel_scroll.setBounds(261, 71, 750, 698);
center_panel.setPreferredSize(new Dimension(750, 698));
center_panel = new JPanel();
// center_panel.setLayout(null);
center_panel.setPreferredSize(new Dimension(900, 800));
center_panel.setBackground(Color.cyan);
centerPanel_scroll.setViewportView(center_panel);
main_panel.add(centerPanel_scroll);


例如。,

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.*;

public class ScrollEg extends JPanel {
    public ScrollEg() {
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewportView(new InnerPanel());

        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(650, 500);
    }

    private static class InnerPanel extends JPanel {
        private static final int PREF_W = 1000;
        private static final Color COLOR_1 = Color.RED;
        private static final Color COLOR_2 = Color.BLUE;

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(PREF_W, PREF_W);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.setPaint(new GradientPaint(0, 0, COLOR_1, 100, 100, COLOR_2, true));
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.fillOval(0, 0, PREF_W, PREF_W);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ScrollEg mainPanel = new ScrollEg();
            JFrame frame = new JFrame("ScrollEg");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}

09-04 12:51