
It's a simple calculator : it has a couple of JButtons and one JTextField. (You can use JLabel in the place of JTextField). What is not obvious here is that I used GridLayout and BorderLayout for the layout of the buttons.
By default, JPanel comes with a FlowLayout(It will be discussed in later posts). You can change default layout of a JPanel when you create a new JPanel by specifying in the constructors or you can explicitly call setLayout() method of JPanel. For this program, I used a mixture of BorderLayout and GridLayout. I used two GridLayouts because I wanted all numbers on the left side and all the signs on the right side.

So, we have the mainPanel which is holding all the different panels with different layouts. The mainPanel's layout is BorderLayout as I want to put the text field and the buttons on top of each other. And there's another buttonsPanel which holds two smaller panels : numbersPanel & signsPanel. The reason is that that two different button panels are different in terms of number and arrangement. buttonsPanel has also a BorderLayout because BorderLayout allows the two panels to be placed on left and right sides. And each smaller button panel has GridLayout which is self-explanatory.
You need to add the following 3 lines of code in the end to put everything on the panel.
buttonsPanel.add(numberPanel, BorderLayout.WEST);
buttonsPanel.add(signsPanel, BorderLayout.EAST);
mainPanel.add(buttonsPanel, BorderLayout.CENTER);
You will see that I created JButton and add an actionListener to it. I'll talk about it in my next post.
No comments:
Post a Comment