如何使捲軸永不顯示在 Java 中?


若要使捲軸永不顯示,請使用 JScrollPane.HORIZONTAL_SCROLLBAR_NEVER 和 JScrollPane.VERTICAL_SCROLLBAR_NEVER。假設你使用一些按鈕元件建立了一個 Box 。現在,建立一個 JScrollPane

JScrollPane scrollPane = new JScrollPane();

將視口檢視設為 Box

scrollPane.setViewportView(box);

現在,將捲軸設為永不顯示

scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);

以下是如何將捲軸設為永不顯示的示例

示例

package my;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JButton button1 = new JButton("One");
      JButton button2 = new JButton("Two");
      JButton button3 = new JButton("Three");
      JButton button4 = new JButton("Four");
      JButton button5 = new JButton("Five");
      JButton button6 = new JButton("Six");
      Box box = Box.createVerticalBox();
      box.setPreferredSize(new Dimension(900,900));
      box.add(button1);
      box.add(button2);
      box.add(button3);
      box.add(button4);
      box.add(button5);
      box.add(button6);
      JScrollPane scrollPane = new JScrollPane();
      scrollPane.setViewportView(box);
      scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
      frame.add(scrollPane, BorderLayout.CENTER);
      frame.setSize(550, 250);
      frame.setVisible(true);
   }
}

這將生成以下輸出。此處,框的首選大小足夠大,能顯示捲軸,但它不會可見,因為我們已停用水平和垂直捲軸並將其設為永不顯示

更新日期: 2019 年 7 月 30 日

70 次瀏覽

啟動你的 職業生涯

完成課程以獲得認證

開始
廣告