如何在 Java 中创建 Glue 来填充相邻组件之间的空间?
java 8object oriented programmingprogramming
假设我们有 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() 方法创建一个 Glue −
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); } }