2013-12-21 45 views
2

我想用i.add(jp, BorderLayout.EAST);设置我的JPanel的位置,但它不起作用。任何想法为什么?我在这里先向您的帮助表示感谢。JPanel使用边框布局不工作的定位

/* INSTANCE DECLARATIONS */ 
private JTextField tf;//text field instance variable 
private JLabel jl2;//label instance variable 


/***************** 
* WINDOW METHOD * 
* ***************/ 
public void window() { 

    LoadImageApp i = new LoadImageApp();//calling image class 

    JFrame gameFrame = new JFrame();//declaration 
    JPanel jp = new JPanel(); 
    JLabel jl = new JLabel("Enter a Letter:");//prompt with label 

    tf = new JTextField(1);//length of text field by character 
    jl2 = new JLabel("Letters Used: "); 

    jp.add(jl);//add label to panel 
    jp.add(tf);//add text field to panel 
    jp.add(jl2);//add letters used 

    gameFrame.add(i); //adds background image to window 
    i.add(jp, BorderLayout.EAST); // adds panel containing label to background image panel 

    gameFrame.setTitle("Hangman");//title of frame window 
    gameFrame.setSize(850, 600);//sets size of frame 
    gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit when 'x' button pressed 
    gameFrame.setIconImage(new ImageIcon("Hangman-Game-grey.png").getImage());//set the frame icon to an image loaded from a file 
    gameFrame.setLocationRelativeTo(null);//window centered 
    gameFrame.setResizable(false);//user can not resize window 
    gameFrame.setVisible(true);//display frame 


}//end window method 

回答

5

i,你LoadImageApp例如,使用什么样的布局管理器?我打赌这不是BorderLayout。我敢打赌,LoadImageApp类延伸JPanel,如果是这样,如果你从来没有明确地设置它的布局,那么默认情况下它使用FlowLayout,并且当你发现,FlowLayout不尊重BorderLayout.EAST int常量。

的解决方案是可能很简单:让使用BorderLayout

setLayout(new BorderLayout()); 

编辑
幽州的评论:

当我设置的边界布局我到东部,我的背景图像也转移到右边,有没有办法解决这个问题?

不,你错过了这一点。您需要将LoadImageApp的布局设置为BorderLayout。你不应该添加我BorderLayout.EAST。这从未被推荐给你。

public class LoadImageApp extends JPanel { 

    // in the constructor 
    public LoadImageApp() { 
    setLayout(new BorderLayout()); 
    } 

    // .... etc.... 
} 

的LoadImageApp实例(我会说出loadImageApp,不i),应补充BorderLayout.CENTER,你做之前。请阅读布局管理器教程,您可以找到here

+0

当我将我的边界布局设置为EAST时,我的背景图像也向右移动,是否有办法解决这个问题? – Anon

+0

@Anon:请参阅编辑。 –