Hallo
Was ist denn auf Using Top-Level Containers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components) gemeint mit:
Aber wie schaut die zweite Variante aus?
Was ist denn auf Using Top-Level Containers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components) gemeint mit:
Die erste Variante habe ich verstanden:The getContentPane method returns a Container object, not a JComponent object. This means that if you want to take advantage of the content pane's JComponent features, you need to either typecast the return value or create your own component to be the content pane. Our examples generally take the second approach, since it's a little cleaner.
Java:
import java.awt.Container;
import javax.swing.*;
public class X {
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
JComponent pane = (JComponent)(frame.getContentPane()); // Variante 1: casten
pane.add(label);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}