Reputation: 1511
I've been learning Java Swing GUI from YouTube videos, as I don't learn them till around the end of next semester in university, and I find it too interesting to wait. However, although the video maker has made it pretty easy to follow, and I've learned a lot, I can tell that he probably learned it himself as some of his coding practices are a bit different than how we learned in school. (For example, he doesn't care about encapsulation or camel-case.) This makes me worry that everything I'm learning will be useless.
All of the projects he does in his videos are all within one class using inner classes implementing ActionListener, MouseListener, etc. So I don't know how to connect what I learned from these videos with the GUI-less multiple classes projects I worked on during school.
I'll give a general example of how the projects are: (I just add the private because that's what I'm used to)
public class Something extends JFrame {
private JPanel topPanel;
private JPanel bottomPanel;
private JLabel label;
private JButton button;
public Something() {
Container pane = this.getContentPane(); //need help with this
topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1,1));
label = new JLabel("x");
topPanel.add(label);
pane.add(topPanel);
bottomPanel = new JPanel();
bottomPanel.setLayout(new GridLayout(1,1));
button = new JButton("Button");
bottomPanel.add(button);
pane.add(bottomPanel);
Event e = new Event();
button.addActionListener(e);
}
public class Event implements ActionListener {
}
Also, I read another thread on here on why extending JFrame is a bad idea. If I had to accommodate, would I just create a JFrame frame, then do add(frame)? And then just make sure I add the next layer to the frame? What accommodations would I have to do?
Upvotes: 1
Views: 97
Reputation: 15729
In general, you should not extend JFrame. Instead, extend JPanel. e.g. your code might look like:
public class Something extends JPanel {
// very similar code to yours goes here
// though I'd set a specific LayoutManager
}
Now you have a lot more flexibility: you can add your wonderful GUI into a JFrame, a JDialog, or into yet another even more complex JPanel. e.g.
JDialog dialog = new JDialog();
JPanel reallyComplexPanel = new JPanel(new BorderLayout());
// add in stuff here, e.g buttons at the bottom
Something mySomething = new Something();
reallyComplexPanel .add(mySomething, BorderLayout.NORTH); // my stuff at the top
dialog.setContentPane(reallyComplexPanel);
Upvotes: 1