I wrote about Java Swing and its components in my previous post. Now, it's time to move on to the next steps which is learning how to make use of those components and create an application. Of 'course, I didn't talk about all the components that come in the package. But we will encounter some new ones in a few. I personally think that you learn the most when you have a concrete example or project that is useful and applicable to the real world. Therefore, I decided to write a program called A Simple Calculator. This will be a long post. So, I'll try my best to highlight the most important notes. I also want to extend this project to a few posts. So, in this post, I'll talk about the layout of a swing application. The following is a screen shot of my simple calculator.
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