Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I have a couple of recommendations:</p> <ul> <li>set the GridLayout constants when calling its constructor. e.g., <code>GridLayout gridLayout1 = new GridLayout(0, 3);</code></li> <li>Don't set the bounds of your GUI but let the GUI's layout managers do this for you based on its preferred size.</li> <li>Don't forget to call pack() on the JFrame after adding all components</li> <li>I usually call <code>setLocationRelativeTo(null);</code> after calling <code>pack();</code> and before calling <code>setVisible(true);</code></li> <li>Don't forget to call <code>setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);</code> in your class's (JFrame) constructor.</li> <li>One way to set the button's size is to set the Font of the button to be larger.</li> </ul> <p>e.g.,</p> <pre><code>import java.awt.*; import javax.swing.*; public class TPad extends JPanel { public static final String[][] BTN_TEXTS = { {"1", "2", "3"}, {"4", "5", "6"}, {"7", "8", "9"}, {"*", "0", "#"} }; private static final int GAP = 5; private static final int FONT_POINTS = 36; private static final Font BTN_FONT = new Font(Font.SANS_SERIF, Font.BOLD, FONT_POINTS); public TPad() { int rows = BTN_TEXTS.length; int cols = BTN_TEXTS[0].length; setLayout(new GridLayout(rows, cols, GAP, GAP)); setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP)); for (int row = 0; row &lt; BTN_TEXTS.length; row++) { for (int col = 0; col &lt; BTN_TEXTS[row].length; col++) { JButton btn = new JButton(BTN_TEXTS[row][col]); btn.setFont(BTN_FONT); add(btn); } } } private static void createAndShowUI() { JFrame frame = new JFrame("TPad"); frame.getContentPane().add(new TPad()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload