2014-11-15 38 views
0

我的JPanel包含:放的JButton上的JLabel的顶部内的JPanel

JButton,并 的JLabel与图片在它

我想放在一个JLabel在北部中心位置顶部的按钮设置。目前它的设置彼此相邻,我不知道如何叠加JLabel。

我在这里尝试了很多解决方案,但它似乎并没有按照我想要的方式工作。谢谢!

JLabel picLabel = new JLabel(); // background of the label 
picLabel.setIcon(new ImageIcon(CoursesGUI.class.getResource("/images/graph_paper.jpg"))); 
Button en_course_btn = new JButton("English Course"); 
coursePanel.add(en_course_btn); 
coursePanel.add(picLabel); 

更新:Button放置在JLabel的顶部,但不在里面。

+1

'#的JButton setIcon'? – MadProgrammer

+1

另外,永远不要在代码中引用'src'目录,它不会在运行时存在,而是使用'Class @ getResoruce'并将它传递给'/ images/graph_paper.jpg'的路径。 – MadProgrammer

+0

为什么要这么做? ?这看起来像[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 – Radiodef

回答

3

您应该为您的标签设置布局,并添加里面的按钮:

JPanel setupPanel = new JPanel(); 
JPanel titlePanel = new JPanel(); 
JPanel contentPanel = new JPanel(); 
JPanel coursePanel = new JPanel(); 

JLabel picLabel = new JLabel(); // background of the label 
picLabel.setLayout(new FlowLayout(FlowLayout.CENTER)); 

picLabel.setIcon(new ImageIcon(CoursesGUI.class.getResource("/images/graph_paper.jpg"))); 

// picLabel.setLayout(new BorderLayout()); // sets layout inside the label 
JButton en_course_btn = new JButton("English Course"); 

contentPanel.setBackground(Color.GREEN); 
titlePanel.setBackground(Color.YELLOW); 

// picLabel.setPreferredSize(new Dimension(500, 470)); // dimensions of inner containers 
contentPanel.setPreferredSize(new Dimension(1280, 670)); 
titlePanel.setPreferredSize(new Dimension(1280, 50)); 

picLabel.add(en_course_btn); 
//coursePanel.add(en_course_btn); 
coursePanel.add(picLabel); 

contentPanel.add(coursePanel); // add coursePanel containing buttons and background 
setupPanel.add(titlePanel, BorderLayout.NORTH); 
setupPanel.add(contentPanel); 
getContentPane().add(setupPanel); 
+0

@ProgLearner尝试使用FlowLayout构造函数和FlowLayout.CENTER参数(请参阅我的更新回答)。 –

+0

@Natuto Biju模式,我已经上传了我的整个代码,希望它可以帮助。更新后的问题是一样的:我不能将JButton放在JLabel的顶部。 – ProgLearner

+0

@ProgLearner你应该评论linePanel.add(en_course_btn);并添加行picLabel.add(en_course_btn); (请参阅更新的代码) –