gpt4 book ai didi

java - 图形类似乎覆盖 JFrame/JPanel

转载 作者:行者123 更新时间:2023-12-01 18:45:53 25 4
gpt4 key购买 nike

我在理解 JPanel、JFrame 和图形类的整个结构以及扩展和重写等方面遇到了一些困难。我似乎一切正常,直到我添加了图形类,然后 JPanel/JFrame 上的按钮等不再显示。我发现这与重写或 super 有关?但我确实需要一些澄清。非常感谢!

为了方便查看,我缩小了代码范围。

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**********
}

最佳答案

Uncomment this and the code won't work anymore

不要重写顶级容器(JFrame、JDialog...)的paint()。自定义绘制是通过重写 JPanel(或 JComponent)的 paintComponent() 方法来完成的。然后将面板添加到框架中。不要忘记调用 super.paintComponent(...)。

阅读 Custom Painting 上的 Swing 教程教程以获取更多信息和示例。

关于java - 图形类似乎覆盖 JFrame/JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17823152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com