Java AWT GridLayout create calculator
import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Main { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("GridLayout frame"); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 4)); //from w w w .j a v a2 s . c o m addButtons(buttonPanel, "7", "8", "9", "0", "4", "5", "6", "C", "1", "2", "3", "=", "+", "-", "*", "/" ); JTextField resultBox = new JTextField("*** Layout Only ***"); resultBox.setEditable(false); // Prevent user editing frame.getContentPane().add(buttonPanel, BorderLayout.CENTER); frame.getContentPane().add(resultBox, BorderLayout.NORTH); frame.pack(); frame.setVisible(true); } private static void addButtons(Container contentPane, String... strings) { for (String label : strings) { contentPane.add(new JButton(label)); } } }
import java.awt.GridLayout; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Main extends JFrame { private static final String[] names = { "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+" };//from w w w . j a v a2s .co m public Main() { JPanel container = new JPanel(); JPanel topGrid = new JPanel(new GridLayout(1, 1)); JPanel bottomGrid = new JPanel(new GridLayout(4, 4, 3, 3)); container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS)); topGrid.add(new JTextField(10)); // add buttons for (int i = 0; i < names.length; i++) { bottomGrid.add(new JButton(names[i])); } container.add(topGrid); container.add(bottomGrid); add(container); } public static void main(String[] args) { Main gui = new Main(); gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gui.setSize(250, 250); gui.setVisible(true); } }