现在我已经学习了Java几个星期了,而且在将背景图像应用于JFrame时我真的陷入了困境。我遇到的每个教程都不会像我所做的那样创建框架(我扩展了JFrame),或者如果他们这样做,说明不够清晰,我不能理解。使用Swing在JFrame上设置背景图像
下面的代码来自我自己的一个项目,所以帮助我练习目前为止学到的知识。请你可以建立在下面的代码,并向我解释什么要添加和在哪里,所以我可能有一个图像作为我的框架的背景?
我真的很感激的一件事是,如果你能解释事情是如何工作的,为什么需要和他们实际在做什么 - 我不喜欢盲目复制和粘贴你没有任何线索的想法它是如何工作的。解释越深入越好;即使它听起来光顾。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MiniPad extends JFrame implements ActionListener {
JPanel pan = new JPanel();
ClassLoader ldr = this.getClass().getClassLoader();
ImageIcon closeImg = new ImageIcon(ldr.getResource("\\images\\buttons\\closeBtn.png"));
JTextArea note = new JTextArea("", 6, 21);
JScrollPane notes = new JScrollPane(note);
JButton close = new JButton(closeImg);
public static void main(String[] args) {
MiniPad padgui = new MiniPad();
} //Instance of GUI
public MiniPad() {
super("Notepad");
setSize(265, 191);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(pan);
setVisible(true);
//Specifications
note.setLineWrap(true);
note.setWrapStyleWord(true);
notes.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
close.setBorderPainted(false);
close.setContentAreaFilled(false);
close.setOpaque(false);
//Adding to JPanel 'pan'
pan.add(notes);
pan.add(close);
close.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == close) {
setVisible(false);
}
}
}
你可能想在'pan'上使用'LayoutManager',因为它的默认'LayoutManager'是一个'FlowLayout',它可能不会给你最好的结果。查看http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html&http://docs.oracle.com/javase/tutorial/uiswing/layout/visual。html的一些更多细节 – MadProgrammer 2012-08-07 21:14:53
@AlexanderPower:请看看这个链接[如何添加图像到您的项目](http://stackoverflow.com/a/9866659/1057230)和这个小[示例](http ://stackoverflow.com/a/11372350/1057230),我曾试图解释一下。如果你仍然需要更多东西,请随时询问:-)这里有一个[示例](http://stackoverflow.com/a/11376322/1057230),与你的代码序列相关,你在做什么错误你的代码。 – 2012-08-08 15:08:32