[英]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.