你好,我正在開發一個自定義時鐘應用程序。GUI類中的Java圖像
我的GUI工程發現我的功能很好,但我現在有3天的問題。我無法讓我的GUI在不隱藏我的組件的情況下在後臺顯示圖像。
,這裏是我的GUI類
public void makeFrame() {
contentPane.setLayout(new BorderLayout());
contentPane.add(panel1, BorderLayout.NORTH);
contentPane.add(panel2, BorderLayout.CENTER);
contentPane.add(panel3, BorderLayout.SOUTH);
contentPane.add(panel4, BorderLayout.WEST);
contentPane.add(panel5, BorderLayout.EAST);
panel1.add(label1);
panel2.setLayout(new GridLayout(3,4));
panel2.add(time);
panel2.add(label2);
panel2.add(stopwatch);
panel3.setLayout(new FlowLayout());
panel4.setLayout(new FlowLayout());
panel5.add(alarm);
panel5.add(change);
panel5.setLayout(new FlowLayout());
label1.setFont(new Font("Arial", Font.PLAIN, 90));
label1.setForeground(Color.BLUE);
label2.setFont(new Font("Arial", Font.PLAIN, 70));
label2.setForeground(Color.RED);
time.setEditable(true);
time.setText("Sample Time: n/ 13:45:23 ");
time.setFont(new Font("Arial", Font.PLAIN, 60));
stopwatch.setFont(new Font("Arial", Font.PLAIN, 45));
stopwatch.setSize(20,20);
stopwatch.setText("00 : 00 : 00");
stopwatch.setEditable(false);
stopwatch.add(rounds);
frame = new JFrame("Clock");
frame.setLayout(null);
frame.setSize(600,900);
paint();
frame.setContentPane(contentPane);
makeMenu();
comboBox();
stopWatch();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.validate();
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
和paint()方法
public void paint() {
BufferedImage img = null;
try {
//load the image
img = ImageIO.read(new File("C:/Users/User/workspace/Alarm Clock/src/Clock/clock.jpg"));
ImageIcon image = new ImageIcon(img);
JLabel label = new JLabel(image);
frame.setContentPane(label);
} catch (IOException e) {
}
}
要替換它包含有該標籤的其他組件的內容窗格。嘗試使用內容窗格的卡片佈局,並將標籤設置在最低級別或覆蓋框架的paint()方法並在其中添加圖像:http://stackoverflow.com/questions/1466240/how-to-set-an -image-as-a-background-for-frame-in-swing-gui-of-java – Thomas
永遠不要讓一個異常塊爲空。 (這與你的問題無關,但可能與未來的問題有關。) – Risadinha
@Thomas,「嘗試使用卡片佈局」 - CardLayout一次只能顯示一個組件,這是行不通的。另外,您提供的鏈接中的「接受」答案是不完整的,因爲它沒有提及您需要在添加到內容窗格的面板上使用'setOaque(false)',以便可以看到背景圖像。 – camickr