In this Java example let us create three buttons on a Swing object. Besides JavaFx, Swing is still widely used by Java developer nowadays to develop Java programs thus it is still views as a very important module that is used to create a user interface for the Java program.
Below is the entire program used to create three buttons on the JFrame windows.
import javax.swing.*; import java.awt.*; public class JFrameLayoutDemo { public static void main(String[] args) { int horizontalcap = 20; int verticalcap = 20; JFrame frame = new JFrame("Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new FlowLayout(FlowLayout.LEADING,horizontalcap,verticalcap)); frame.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); JPanel panel = new JPanel(); panel.add(new JButton("Sort")); panel.add(new JButton("Calculate")); panel.add(new JButton("Display")); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } }
The above program used the FlowLayout object to set the layout of the JPanel object which will contain the three buttons. FlowLayout is not that widely used by Java developers when they creating a JFrame object but it is simply good enough to use as a demo in this example. The three buttons then get added to the JPanel object which will later get added to the JFrame object.