Repaint()方法不会重新绘制所需内容

时间:2014-12-07 19:05:04

标签: java random paintcomponent repaint

这就是我的任务。

我必须生成4张随机卡。之后,当按下“刷新”按钮时,卡片应该再次随机化。我已经像这样实现了repaint()方法,但它并没有改变卡片的显示方式。

public class FourCards extends JFrame {

        JLabel slot1 = new JLabel(getImage());
        JLabel slot2 = new JLabel(getImage());
        JLabel slot3 = new JLabel(getImage());
        JLabel slot4 = new JLabel(getImage());

    public FourCards() {

        JPanel CardsPanel = new JPanel(new GridLayout(1,4,5,5));
        add(CardsPanel);

        CardsPanel.add(slot1);
        CardsPanel.add(slot2);
        CardsPanel.add(slot3);
        CardsPanel.add(slot4);

        JButton jbtRefresh = new JButton("Refresh");

        JPanel ButtonPanel = new JPanel();
        this.add(ButtonPanel, BorderLayout.SOUTH);
        ButtonPanel.add(jbtRefresh);

        jbtRefresh.addActionListener(new ButtonListener());

        }

    public ImageIcon getImage() {

        ImageIcon temp = new ImageIcon("C:/resized/" + (int)(Math.random() * 52) + ".png");
        return temp;

    }

    public void update() {

        slot1 = new JLabel(getImage());
        slot2 = new JLabel(getImage());
        slot3 = new JLabel(getImage());
        slot4 = new JLabel(getImage());

    }

    public static void main(String[] args) {

        FourCards frame = new FourCards();
            frame.setTitle("Random 4 cards");
            frame.setSize(600,280);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);

    }

    class ButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            update(); // get new images
            repaint();

        }

    }

}

3 个答案:

答案 0 :(得分:2)

当你这样做时

slot1 = new JLabel(getImage());
slot2 = new JLabel(getImage());
slot3 = new JLabel(getImage());
slot4 = new JLabel(getImage());

你没有改变GUI。您正在更新slotX变量的值。您还应该替换GUI树中的实际组件。

尝试将CardsPanel作为成员变量,并执行

CardsPanel.removeAll();
CardsPanel.add(new JLabel(getImage()));
CardsPanel.add(new JLabel(getImage()));
CardsPanel.add(new JLabel(getImage()));
CardsPanel.add(new JLabel(getImage()));

答案 1 :(得分:1)

update()方法中,您正在创建新的JLabel对象,并且这些对象未添加到面板中,因此不会显示它们。要更改图像,请在所有setIcon(...)上使用JLabel方法,而不是创建新对象。

答案 2 :(得分:1)

update()方法上,您正在创建新的JLabel,但不会将其添加到面板中,并保持面板上的旧版本不变。您必须更改现有的JLabel,并且无需创建新的public void update() { slot1.setIcon(getImage()); slot2.setIcon(getImage()); slot3.setIcon(getImage()); slot4.setIcon(getImage()); } 。像这样:

{{1}}