I am trying to user Swing in Eclipse but I keep getting this error. See below

huangapple go评论126阅读模式
英文:

I am trying to user Swing in Eclipse but I keep getting this error. See below

问题

  1. private void initialize() {
  2. frame = new JFrame();
  3. frame.setBounds(100, 100, 450, 300);
  4. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  5. JLabel lblSomeText = new JLabel("Hello, World!");
  6. frame.getContentPane().add(lblSomeText, BorderLayout.CENTER); //错误在这里
  7. }

提示错误: "The Type container is not visible around the frame.getContentPane()"

英文:
  1. private void initialize() {
  2. frame = new JFrame();
  3. frame.setBounds(100, 100, 450, 300);
  4. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  5. JLabel lblSomeText = new JLabel("Hello, World!");
  6. frame.getContentPane().add(lblSomeText, BorderLayout.CENTER); //error here
  7. }

It says: "The Type container is not visible around the frame.getContentPane()"

答案1

得分: 1

以下完整的代码对我有效。请检查您的导入并展示您的整个代码,这样我们可以帮助您!

  1. package stackoverflow;
  2. import javax.swing.JFrame;
  3. import javax.swing.JLabel;
  4. public class SwingTest {
  5. public static void main(String[] args) {
  6. JFrame frame = new JFrame();
  7. JLabel lblSomeText = new JLabel("Hello, World!");
  8. frame.getContentPane().add(lblSomeText);
  9. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  10. frame.setSize(640, 480); // 使用 setSize() 替代 setBounds
  11. // frame.pack(); // 或者调用 pack() 替代
  12. frame.setLocationRelativeTo(null);
  13. frame.setVisible(true);
  14. }
  15. }
英文:

The following complete code works for me. Please check your imports and show us your entire code so we can help you!

  1. package stackoverflow;
  2. import javax.swing.JFrame;
  3. import javax.swing.JLabel;
  4. public class SwingTest {
  5. public static void main( String[] args ) {
  6. JFrame frame = new JFrame();
  7. JLabel lblSomeText = new JLabel( "Hello, World!" );
  8. frame.getContentPane().add( lblSomeText );
  9. frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  10. frame.setSize( 640, 480 ); // use setSize() instead of setBounds
  11. // frame.pack(); // or call pack() instead
  12. frame.setLocationRelativeTo( null );
  13. frame.setVisible( true );
  14. }
  15. }

huangapple
  • 本文由 发表于 2020年5月4日 05:00:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/61581550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定