英文:
I am trying to user Swing in Eclipse but I keep getting this error. See below
问题
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblSomeText = new JLabel("Hello, World!");
frame.getContentPane().add(lblSomeText, BorderLayout.CENTER); //错误在这里
}
提示错误: "The Type container is not visible around the frame.getContentPane()"
英文:
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblSomeText = new JLabel("Hello, World!");
frame.getContentPane().add(lblSomeText, BorderLayout.CENTER); //error here
}
It says: "The Type container is not visible around the frame.getContentPane()"
答案1
得分: 1
以下完整的代码对我有效。请检查您的导入并展示您的整个代码,这样我们可以帮助您!
package stackoverflow;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SwingTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
JLabel lblSomeText = new JLabel("Hello, World!");
frame.getContentPane().add(lblSomeText);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640, 480); // 使用 setSize() 替代 setBounds
// frame.pack(); // 或者调用 pack() 替代
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
英文:
The following complete code works for me. Please check your imports and show us your entire code so we can help you!
package stackoverflow;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class SwingTest {
public static void main( String[] args ) {
JFrame frame = new JFrame();
JLabel lblSomeText = new JLabel( "Hello, World!" );
frame.getContentPane().add( lblSomeText );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize( 640, 480 ); // use setSize() instead of setBounds
// frame.pack(); // or call pack() instead
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论