我已经学习 Java 几个星期了,在将背景图像应用于 JFrame 时,我真的陷入了困境。我遇到的每个教程都没有按照我的方式创建 Frames(我扩展了 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);
}
}
}