直到结束,JButton才会出现

时间:2013-02-08 13:48:33

标签: java image swing jbutton repaint

当我运行我的程序时,一切都按计划工作,除了我必须更换屏幕上的卡片才会显示,直到它被鼠标悬停。我假设这是因为任何容纳图像的容器都在它上面,但我不知道如何将它移动到背景中,甚至不知道我可以用什么样的容器来添加图像。

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);
}
}

3 个答案:

答案 0 :(得分:4)

不要覆盖paint()方法。而是覆盖主容器的paintComponent()

致电super.paintComponent(g)

不要延伸JFrame,例如JPanel,将所有内容添加到面板,并将面板设置为常规JFrame实例的内容窗格。

答案 1 :(得分:0)

您需要在super.paint(g)函数内调用paint(Graphics),以确保正确显示框架内的Swing组件。

答案 2 :(得分:0)

没有使用您的示例对此进行测试,但我认为您需要在覆盖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);
}