I am trying to test a new program with 2 interfaces "ActionListener" and "ControllerEventListener". What I expect from the program during the execution would be that when I run the program, a GUI appears with a button on it. After I click on the button, the there would be a chain of sound appearing along with the random animation on the GUI. However, there is also an unwanted button popping up at the left corner of the GUI. Why does that button appear and why is it in the left corner? Thanks in advance.
So... the default LayoutManager for a JFrame's content pane is BorderLayout. But then you change the content pane to be a JPanel, whose default LayoutManager is FlowLayout.
(I believe that's correct; I've always explicitly set the LayoutManager I want so I've never had to rely on the above statement.)
And you're adding components to that content pane as if its LayoutManager were a BorderLayout. But suppose my understanding is correct. Then you're using a FlowLayout as if it were a BorderLayout and things are likely to go awry. And since things are going awry, in particular since your JFrame isn't being laid out as you think it should, that suggests I could well be right.
Paul is indeed right. The content pane defaults to BorderLayout whereas the JPanel defaults to FlowLayout.
Solution: Define your panel to have BorderLayout either via an explicit call or inside a constructor
Can someone explains to me what is the difference between BorderLayout and FlowLayout. I've just recently started learning how to work with Swing and still have a lot of things that I don't understand. How should I fix my code then?
You should be able to find out all you need to know about layouts (except how to simplify grid bag constraints) in the Java™ Tutorials. Flow is like line wrapping in a text editor when you alter its width. Border has up to five areas which contain other components and they all can change size but don't change their relative positions.
Thanks for your response. I am still trying to improve my skill and to be able to understand all the issues explained in the java doc is still somewhat challenging to me. I'll make sure that I'll get the hang of it.
The analogy I like to give is this: when you want to learn how to juggle flaming chainsaws, there are three steps:
1. Learn to juggle.
2. Learn to juggle chainsaws.
3. Learn to juggle flaming chainsaws.
Skipping earlier steps in the process can be hazardous. But Swing isn't really like that, you really have to learn a whole lot of things all at once so you don't have unexpected consequences. Working your way through the tutorials is definitely recommended. Although admittedly having a JButton show up in the wrong place is less serious than having a flaming chainsaw show up in the wrong place!