[英]JButton does not appear until moused over
当我运行程序时,所有事情都按计划进行,除了需要将按钮更改为屏幕上的按钮外,直到将鼠标悬停在该按钮上为止。 我认为这是因为任何保存图像的容器都在它上面,但是我不知道如何将其移到背景中,甚至不知道我可以使用哪种容器来添加图像。
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.util.Random;
import java.awt.event.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class oneplayer extends JFrame {
BufferedImage image1, image2, image3, image4;
Random gen = new Random();
public void redo() {
int p1, p2, p3, p4;
p1 = gen.nextInt(13) + 1;
p2 = gen.nextInt(13) + 14;
p3 = gen.nextInt(13) + 27;
p4 = gen.nextInt(13) + 40;
try {
File input1 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p1 + ".png");
File input2 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p2 + ".png");
File input3 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p3 + ".png");
File input4 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p4 + ".png");
image1 = ImageIO.read(input1);
image2 = ImageIO.read(input2);
image3 = ImageIO.read(input3);
image4 = ImageIO.read(input4);
} catch (IOException ie) {
System.out.println("Error:"+ie.getMessage());
}
repaint();
}
public oneplayer() {
JPanel buttonPanel = new JPanel();
setLayout(new BorderLayout());
JButton refresh = new JButton("Refresh");
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
redo();
}
});
add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.add(refresh, BorderLayout.CENTER);
redo();
}
public void paint(Graphics g) {
g.drawImage(image1, 20, 55, null);
g.drawImage(image2, 96, 55, null);
g.drawImage(image3, 172, 55, null);
g.drawImage(image4, 248, 55, null);
}
public static void main(String args[]) {
oneplayer frame = new oneplayer();
frame.setTitle("Random Cards");
frame.setSize(350, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
不要重写paint()
方法。 而是重写主容器的paintComponent()
。
调用super.paintComponent(g)
不要扩展JFrame
而是扩展例如JPanel
,将所有内容添加到面板中,并将该面板设置为普通JFrame
实例的内容窗格。
您需要在paint(Graphics)
函数中调用super.paint(g)
以确保正确显示框架内的Swing组件。
尚未使用示例对此进行测试,但是我认为您需要在覆盖Frame上的绘制时调用父类的绘制,以便显示Frame的组件。 像这样:
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image1, 20, 55, null);
g.drawImage(image2, 96, 55, null);
g.drawImage(image3, 172, 55, null);
g.drawImage(image4, 248, 55, null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.