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

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

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 );
   }

}

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:

确定