【问题标题】:How to set JPanel fixed size such that the JScrollPane (scrolling) appears?如何设置 JPanel 固定大小以使 JScrollPane(滚动)出现?
【发布时间】:2014-09-19 00:13:18
【问题描述】:

我正在编写一些代码。 JFrame 包含具有特定尺寸的 JPanel。这是我的代码:

import javax.swing.*; 
import java.awt.*; 

public class ScrollPane extends JFrame { 

    public ScrollPane() {
        super("Title");
        setLayout(new BorderLayout());
        setSize(320,240);

        JScrollPane scroller = new JScrollPane(new DrawingPane()); 
        scroller.setPreferredSize(new Dimension(320,240)); 

        add(scroller); 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    } 

    private class DrawingPane extends JPanel {
        public DrawingPane(){
            super();
            setSize(640,480);
            setMinimumSize(new Dimension(320,240));
        }

    }

    public static void main(String[] args) {
        new ScrollPane();
    } 
}

即使为JPanel 设置了最小尺寸,滚动也不会出现。

【问题讨论】:

  • private class DrawingPane extends JPanel { .. setSize(640,480); 我会将DrawingPane 替换为BufferedImage 中显示的JLabel..
  • +1 用于解决方法
  • 覆盖 getPreferredSize() @camickr (IMO 应该是公认的答案)指出之后,调用frame.pack() 而不是frame.setSize()pack() 方法将考虑所有内部组件的首选大小,然后相应地调整框架的大小

标签: java swing jpanel jscrollpane preferredsize


【解决方案1】:

您还需要为绘图面板设置首选尺寸:

private class DrawingPane extends JPanel {
        public DrawingPane(){
            super();
            setPreferredSize(new Dimension(640,480));
            setMinimumSize(new Dimension(320,240));
        }

    }

【讨论】:

  • -1 您不应该使用 setPreferredSize() 方法。相反,您应该覆盖 getPreferredSize() 方法。不要走捷径!!!
  • @camickr 有多种做事方式。您可能是对的,但这并不会使我的回答无效。
  • 对于那些不想把头埋在沙子里的人,请参阅Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Swing?(是的。)
  • @Sanjeev, there are multiple ways of doing things. - 是的,但问题是初学者总是会走捷径,因为他们认为这更容易,而不是理解这个决定的全部含义。
  • @camickr 明白了你的意思.. 请建议我删除这个答案吗?
【解决方案2】:

所有组件都负责确定首选大小,以便布局管理器可以正常工作。在进行自定义绘制时,您需要覆盖自定义组件的 getPreferredSize() 以返回组件的 Dimension。

阅读 Custom Painting 上的 Swing 教程部分,了解更多信息和工作示例。

【讨论】:

    猜你喜欢
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 2016-07-05
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    相关资源
    最近更新 更多