我正在尝试使用背景图像创建一个JFrame,背景图像上方的JLabel居中并朝向底部,右侧和左侧有两个按钮,表示“保持”和“离开”。这已经创建了。问题出现在每个项目的顺序上。我无法在背景图像上看到带有文字和按钮的JLabel,两者都显示出来。这是我的代码;任何意见,将不胜感激。先感谢您。
public class SceneOne {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
JFrame SceneOne = new JFrame();
ImageIcon image = new ImageIcon(
"C:/Users/alan/Downloads/scary_forest_2.jpg");
JLabel imageLabel = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add(imageLabel, BorderLayout.CENTER);
SceneOne.add(panel);
SceneOne.setResizable(true);
imageLabel.setVisible(true);
SceneOne.pack();
JButton Leave=new JButton("Leave");
JButton Stay= new JButton ("Stay");
JPanel Leave1= new JPanel(new FlowLayout());
JPanel Stay1=new JPanel(new FlowLayout());
FlowLayout two = new FlowLayout(FlowLayout.LEFT);
FlowLayout three = new FlowLayout(FlowLayout.RIGHT);
Leave1.setLayout(two);
Stay1.setLayout(three);
Stay1.add(Leave);
Leave1.add(Stay);
Leave1.setOpaque(false);
Stay1.setOpaque(false);
SceneOne.add(Leave1);
SceneOne.add(Stay1);
JLabel label1 = new JLabel("Test");
SceneOne.add(label1);
label1.setText("<html><font color='red'> It was approximately 11:30 pm. The night sky was black not a single star piercing through the darkness"
+ "except the thick and powerful moonlight."
+ "<br>"
+ "You are alone leaving a costume party at a friend's place."
+ "It was rather boring and you decided to leave early."
+ "A stutter is heard and your"
+ "<br>"
+ "car begins to shake"
+ "Your headlights and car lights crack. The engine is left dead silent."
+ "You are left in a total silence"
+ "and baked in merely the moonlight."
+ "<br>"
+ "There is a mere second of silence till a harsh chill ripes through the"
+ "car like a bullet through paper. You are left dumbfounded. What do you do?</font><html>");
label1.setHorizontalAlignment(JLabel.CENTER);
label1.setVerticalAlignment(JLabel.BOTTOM);
label1.setVisible(true);
label1.setOpaque(false);
SceneOne.setComponentZOrder(panel, 0);
SceneOne.setComponentZOrder(label1, 0);
// SceneOne.setComponentZOrder(Leave1,0);
// SceneOne.setComponentZOrder(Stay1,0);
SceneOne.setSize(400,320);
SceneOne.setTitle("The Car");
SceneOne.setVisible(true);
SceneOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SceneOne.setLocation(500, 300);
}
}
答案 0 :(得分:0)
首先遵循Java命名约定。变量名称不应以大写字符开头。我从未见过使用您正在使用的变量名称的教程,教科书或论坛示例。不要自己制定约定!
JFrame的默认布局管理器是BorderLayout。使用frame.add(...)方法时,默认情况下组件将添加到BorderLayout的CENTER
。只有组件可以添加到CENTER中,因此只显示最后一个组件。
如果您希望组件显示在图像的顶部,则需要将组件添加到图像中。基本代码是:
JLabel label = new JLabel( new ImageIcon(...) );
frame.add(label);
label.setLayout(....);
label.add(leaveButton);
label.add(labelWithText);
label.add(stayButton);
我会让你找出你想要的确切布局。