Code:import java.awt.GridLayout; import java.awt.Container; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JButton; public class GridLayoutFrame extends JFrame implements ActionListener { private JButton buttons[]; private final String names[] = { "one" , "two" , "three" , "four" , "five" , "six"}; private boolean toggle = true; private Container container; private GridLayout gridLayout1; private GridLayout gridLayout2; public GridLayoutFrame() { super("GridLayout Demo"); gridLayout1 = new GridLayout(2 , 3 , 5 , 5); gridLayout2 = new GridLayout(3 , 2 ); container = getContentPane(); setLayout(gridLayout1); buttons = new JButton[names.length]; for(int count = 0 ; count < names.length ; count++) { buttons[count] = new JButton(names[count]); buttons[count].addActionListener(this); add(buttons[count]); } } public void actionPerformed(ActionEvent event) { if(toggle) { container.setLayout(gridLayout2); } else { container.setLayout(gridLayout1); } toggle = !toggle; container.validate(); } }
(1) the usage of container = getContentPane();
(2) the "this" at buttons[count].addActionListener(this) is refer to ..?
You give the instruction to add an actionlistener. Now you must tell it where the actionlistener is. By using "this" here you tell Java it can find the actionlistener in the class you're currently in. So here you tell Java it can find the actionlistener in"GridLayoutFrame". Java can find the actionperformed method itself from there.
You don't add graphical stuff directly on JFrame in Java. You use root panes.
Check out these:
How to Use Root Panes (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)
Using Top-Level Containers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)
actually the "this" will ask java to find an appropriate "stuff" to match with the current condition ..?
this is a reference to the class/object you're using it in.
__________________________________________
I study Information Systems at Karlstad University when I'm not on CodeCall
so in this case , the "this" im passing is the reference to an object of interface ( ActionListener ) ... ??
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks