getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS)); //or getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); JButton btn1 = new JButton("Button 1"); btn1.setAlignmentX(Component.CENTER_ALIGNMENT); getContentPane().add(btn1); JButton btn2 = new JButton("Button 2"); btn2.setAlignmentX(Component.CENTER_ALIGNMENT); getContentPane().add(btn2);
package com.java.myapp; import java.awt.Component; import java.awt.EventQueue; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.BoxLayout; public class MyForm extends JFrame { /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { MyForm frame = new MyForm(); frame.setVisible(true); } }); } /** * Create the frame. */ public MyForm() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS)); JButton btn1 = new JButton("Button 1"); btn1.setAlignmentX(Component.CENTER_ALIGNMENT); getContentPane().add(btn1); JButton btn2 = new JButton("Button 2"); btn2.setAlignmentX(Component.CENTER_ALIGNMENT); getContentPane().add(btn2); JButton btn3 = new JButton("Button 3"); btn3.setAlignmentX(Component.CENTER_ALIGNMENT); getContentPane().add(btn3); JButton btn4 = new JButton("Button 4"); btn4.setAlignmentX(Component.CENTER_ALIGNMENT); getContentPane().add(btn4); } }
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท