简体   繁体   English

仅在必要时显示滚动条

[英]Displaying a scroll bar only when necessary

I'd like to do something like the following: 我想做类似以下的事情:

    public class MyCustomDialog extends JDialog 
    {

       public MyCustomDialog()
       {
          if (getClientVertScreenSize() < 800)
          {
            // Set the vertical size as 600, and give them a scroll pane to navigate to the bottom of the gui.
          }
          else
          {
             setSize(600, 800); // No need to add a scroll pane.
          }
       }

    }

The trouble is I don't know how to check the clients' screen size, so I don't know how to write the method my constructor relies on. 问题是我不知道如何检查客户端的屏幕大小,所以我不知道如何编写我的构造函数依赖的方法。

请参见Toolkit.getDefaultToolkit()。getScreenSize()

What you could do is just put your component in a JScrollPane and set the horizontal and vertical scroll bar policies to [VERTICAL|HORIZONTAL]_SCROLLBAR_AS_NEEDED . 你可以做的只是将你的组件放在JScrollPane ,并将水平垂直滚动条策略设置为[VERTICAL|HORIZONTAL]_SCROLLBAR_AS_NEEDED This way, the scroll bar will only appear when the JScrollPane 's size is smaller than your component's preferred size. 这样,滚动条仅在JScrollPane的大小小于组件的首选大小时出现。

The class java.awt.Toolkit has an instance method named getScreenSize() , which returns an object of type java.awt.Dimension . java.awt.Toolkit有一个名为getScreenSize()的实例方法,它返回一个java.awt.Dimension类型的对象。 A Dimension is an immutable object (it cannot be changed) with two public, final fields: width and height . Dimension是一个不可变对象(无法更改),包含两个公共的最终字段: widthheight You can obtain an instance of java.awt.Toolkit and perform your 您可以获取java.awt.Toolkit的实例并执行您的

You should use the following code: 您应该使用以下代码:

import java.awt.Dimension;
import java.awt.Toolkit;

public class MyCustomDialog extends javax.swing.JDialog {
    public MyCustomDialog() {

        super(); // Invoke any JDialog initialization code.

        Toolkit t = Toolkit.getDefaultToolkit();
        if (t.getScreenSize().height < 600) {
            setSize(getWidth(), 600);
            // Add your scrollpane, etc.
        } else {
            setSize(600, 800); // No need to add a scroll pane.
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM