如何在 Java 中建立膠合以填充相鄰元件之間的空白?


假設我們有 6 個元件,並且我們需要填充其中一些元件之間的空白 -

JButton button1 = new JButton("CSK");
JButton button2 = new JButton("DC");
JButton button3 = new JButton("MI");
JButton button4 = new JButton("SRH");
JButton button5 = new JButton("RR");
JButton button6 = new JButton("KKR");

如需填充空白並分隔元件,請使用 createGlue() 方法建立膠合 -

Box box = new Box(BoxLayout.X_AXIS);
box.add(button1);
box.add(button2);
box.add(Box.createGlue());
box.add(button3);
box.add(button4);
box.add(Box.createGlue());
box.add(button5);
box.add(button6);

以下是一個填充相鄰元件之間空白的示例 -

示例

package my;
import java.awt.BorderLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
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("Matches");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JButton button1 = new JButton("CSK");
      JButton button2 = new JButton("DC");
      JButton button3 = new JButton("MI");
      JButton button4 = new JButton("SRH");
      JButton button5 = new JButton("RR");
      JButton button6 = new JButton("KKR");
      Box box = new Box(BoxLayout.X_AXIS);
      box.add(button1);
      box.add(button2);
      box.add(Box.createGlue());
      box.add(button3);
      box.add(button4);
      box.add(Box.createGlue());
      box.add(button5);
      box.add(button6);
      JScrollPane jScrollPane = new JScrollPane();
      jScrollPane.setViewportView(box);
      frame.add(jScrollPane, BorderLayout.CENTER);
      frame.setSize(550, 250);
      frame.setVisible(true);
   }
}

輸出


更新時間: 30-Jul-2019

437 次瀏覽

開啟你的 職業生涯

獲得認證,完成課程

開始吧
廣告
© . All rights reserved.