我在理解 JPanel、JFrame 和图形类的整个结构以及扩展和覆盖等方面遇到了一些麻烦。我似乎一切正常,直到我添加了图形类,然后我的 JPanel/JFrame 上的按钮等不再出现。我发现它与覆盖或超级有关?但我真的需要澄清一下。非常感谢!
为了便于查看,我稍微缩小了代码范围。
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
public class windowBuild extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private int energy = 4;
private JButton btnClaw = new JButton("Claw");
private Image bg;
private boolean loaded = false;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
windowBuild frame = new windowBuild();
frame.setVisible(true);
}
});
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String which = e.getActionCommand();
if (which.equals("Claw")) {
energy = energy - 1;
System.out
.println("Player one's dragon clawed the opponent. Dragon's energy is now at: "
+ energy);
}
}
}
public void loadImage() {
bg = new ImageIcon("C:\\res\\dragonDuelBackground.jpeg").getImage();
loaded = true;
repaint();
}
public windowBuild() {
ButtonHandler bh;
System.out.println("Starting frame...");
bh = new ButtonHandler();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new TitledBorder(null, "Dragon Duel",
TitledBorder.CENTER, TitledBorder.TOP, null, Color.CYAN));
setContentPane(contentPane);
contentPane.setLayout(null);
btnClaw.setBounds(273, 511, 109, 39);
contentPane.add(btnClaw);
btnClaw.addActionListener(bh);
}
//********************************************************************
// public void paint(Graphics g) {
// if (loaded) {
// g.drawImage(bg, 400, 400, null);
// }
// }
//***************Uncomment this and the code won't work anymore**********
}