How to achieve the following output in Java like windows Calculator,
Example,
First Row = Text Field
Second Row = 5 buttons
Third Row = 5 Buttons
and the remaining Data in Center of border layout,
How to put first , second, third row in North of Border Layout together ? here is my code ,
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class GridLayoutFrame extends JFrame
{
private JButton[] buttons; // Array of Buttons 1 to 10
private JButton[] topButton; // 10 buttons that has to be placed under Text field 5 button in each row
private JPanel Bottom; // A panel to show everything under first three Row
private JPanel Top; // Top Panel that contains Text Field and 2nd and third Row
private JTextField Input = new JTextField();
private static final String[] names =
{"7", "8", "9", "4", "5", "6","1","2","3"};
private static final String[] topButtons =
{"MC","MR","MS","M+","M-","<-","CE","C","+-","Root"};
// no-argument constructor
public GridLayoutFrame()
{
super ("Calculator");
Bottom = new JPanel();
Top = new JPanel();
Top.setLayout(new GridLayout(3,1,5,5)); // Three Rows (first row must only show a text field
Bottom.setLayout(new GridLayout(5,5,10,10));
topButton = new JButton[topButtons.length];
buttons = new JButton[ names.length ];
Input.setSize(500,500);
Input.setEditable(false);
Input.setBackground(Color.WHITE);
Input.setPreferredSize(new Dimension(300, 30));
for ( int count = 0; count < topButtons.length; count++ )
{
topButton[ count ] = new JButton( topButtons[count]);
Top.add( topButton[ count ] ); // add button to panel
}
for ( int count = 0; count < names.length; count++ )
{
buttons[ count ] = new JButton( names[count]);
Bottom.add( buttons[ count ] ); // add button to panel
}
add(Top,BorderLayout.NORTH);
//add(Bottom,BorderLayout.CENTER);
}
} // end class GridLayoutFrame
The problem with the code is , the Text field is appearing in the same line where the top buttons are appearing.
please help
It is best to use gridbaglayout for the requirements you have as it is very flexible.
You can take a look at http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html
I have modified your program to use GridBagLayout for the top panel. I think it does what you expect for the top panel.