Reputation: 94
Is it possible to define multiple JPanels for your program in a single file (class)? The way it's usually done is you define a JPanel as the top class in a file, then you define a listener class as a nested class inside the top class. But, what if you want to define several panels (along with their listener classes) inside the same file, instead of creating multiple files. Sorry, I'm new to Java and the fact that everything needs to be put inside a class is a little confusing to me.
Upvotes: 0
Views: 62
Reputation: 347314
Yes, you can use inner classes, for example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
add(new JLabel("Bananas are green"));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
See Inner Class Example for more details
Upvotes: 1