图像不会改变,我将如何刷新面板呢?

时间:2017-01-01 19:20:57

标签: java swing jpanel jlabel imageicon

当某个事件发生时,我希望图像改变但不会发生。
这是代码:

game.add(bbol);
if (flashed == 1) {
   bbol.setIcon(bboH);
} else {
}

我是否需要刷新game面板?

修改

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.Border;

public class BeeBee extends JFrame implements ActionListener, MouseListener {
    private static final long serialVersionUID = 1L;
    private JFrame frame = new JFrame("BB8 Says");
    private JPanel game;
    private JPanel menu;
    ImageIcon bbegif = new ImageIcon("tumblr_o0c57n9gfv1tha1vgo1_r3_250.gif");
    public static final int WIDTH = 800, HEIGHT = 800;
    public int flashed = 0, glowTime, dark, ticks, indexPattern;
    public boolean creatingPattern = true;  
    public ArrayList<Integer> pattern;
    public Random random;
    private boolean gameOver;
    public int counter;
    public int temp;
    public int score;
    //these are the images, replace them if you like
    public ImageIcon bbb = new ImageIcon("bbb.gif");
    public JLabel bbbl = new JLabel(bbb);
    public ImageIcon bbbH = new ImageIcon("bbbH.gif");
    public ImageIcon bbg = new ImageIcon("bbg.gif");
    public JLabel bbgl = new JLabel(bbg);
    public ImageIcon bbgH = new ImageIcon("bbgH.gif");
    public ImageIcon bbgr = new ImageIcon("bbgr.gif");
    public JLabel bbgrl = new JLabel(bbgr);
    public ImageIcon bbgrH = new ImageIcon("bbgrH.gif");
    public ImageIcon bbo = new ImageIcon("bbor.gif");
    public JLabel bbol = new JLabel(bbo);
    public  ImageIcon bboH = new ImageIcon("bborH.gif");
    public  ImageIcon unhap = new ImageIcon("unhap.gif");
    public  JLabel unhapl = new JLabel(unhap);
    //these are the images, replace them if you like
    public BeeBee()
    {
        mainmenu();
    }
    public void start()
    {

    random = new Random();
    pattern = new ArrayList<Integer>();
    indexPattern = 0;
    dark = 2;
    flashed = 0;
    ticks = 0;
}
public void actionPerformed(ActionEvent e) 
{
    ticks++;

    if (ticks % 20 == 0)
    {
        flashed = 0;

        if (dark >= 0)
        {
            dark--;
        }}

    if (creatingPattern)
    {
        if (dark <= 0)
        {
            if (indexPattern >= pattern.size())
            {
                flashed = random.nextInt(40) % 4 + 1;
                pattern.add(flashed);
                indexPattern = 0;
                creatingPattern = false;
            }
            else
            {
                flashed = pattern.get(indexPattern);
                indexPattern++;
            }

            dark = 2;
        }}
    else if (indexPattern == pattern.size())
    {
        creatingPattern = true;
        indexPattern = 0;
        dark = 2;
    }}
public void mainmenu()
{
    Timer timer = new Timer(20, this);
    start();
    timer.start();
    frame.setSize(WIDTH +7, HEIGHT +30);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    menu = new JPanel();
    game = new JPanel();
    menu.setBackground(Color.yellow);
    game.setBackground(Color.yellow);
    JButton button = new JButton("Start");
    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            frame.setContentPane(game);
            frame.invalidate();
            frame.validate();
        };
    });

    menu.add(button);
    gamme();
    frame.add(menu);
    frame.setVisible(true);     
}

public void gamme()
{
    Border border = BorderFactory.createLineBorder(Color.black, 5);
    bbol.setBorder(border);
    bbgl.setBorder(border);
    bbgrl.setBorder(border);
    bbbl.setBorder(border);
    game.setLayout(new GridLayout(2,2));
    game.add(bbol);
    game.add(bbgl);
    game.add(bbgrl);
    game.add(bbbl);

}
public static void main(String[]args)
{
    new BeeBee();
}
@Override
public void mousePressed(MouseEvent e) 
{
    int x = e.getX(), y = e.getY();

    if (!creatingPattern && !gameOver)
    {
        if (x>0 && x<WIDTH/2 && y>0 && y<HEIGHT/2)
        {
            flashed = 1;
            ticks = 1;
            bbol.setIcon(bboH);
        }
        else if (x>WIDTH/2 && x<WIDTH && y>0 && y<HEIGHT/2)
        {
            flashed = 2;
            ticks = 1;
            bbgl.setIcon(bbgH);
        }
        else if (x>0 && x<WIDTH/2 && y>HEIGHT/2 && y<HEIGHT)
        {
            flashed = 3;
            ticks = 1;
            bbgrl.setIcon(bbgrH);
        }
        else if (x>WIDTH/2 && x<WIDTH && y>HEIGHT/2 && y<HEIGHT)
        {
            flashed = 4;
            ticks = 1;
            bbbl.setIcon(bbbH);
        }
        if (flashed != 0)
        {
            if (pattern.get(indexPattern)==flashed)
            {
                indexPattern++;
            }
            else
            {
                gameOver = true;
            }
        }
        else
        {
            start();
            gameOver = true;
        }}
    else if (gameOver)
    {
        start();
        gameOver = false;
    }
    if (flashed == 1) {
        bbol.setIcon(bboH);
    } else 
    {
        bbol.setIcon(bbo);
    }
 if (flashed == 2) {
        bbgl.setIcon(bbgH);
    } else 
    {
        bbgl.setIcon(bbg);
    }
 if (flashed == 3) {
        bbgrl.setIcon(bbgrH);
    } else 
    {
        bbgrl.setIcon(bbgr);
    }
 if (flashed == 4) {
        bbbl.setIcon(bbbH);
    } else 
    {
        bbbl.setIcon(bbb);
    }
    game.repaint();  
}
@Override
public void mouseClicked(MouseEvent e) 
{}
@Override
public void mouseEntered(MouseEvent e) 
{}
@Override
public void mouseExited(MouseEvent e) 
{}
@Override
public void mouseReleased(MouseEvent e) 
{}

}

1 个答案:

答案 0 :(得分:3)

setIcon(...)应足以更改JLabel中的图像。我怀疑你是如何添加JLabel的。如果您在程序运行期间添加组件,则必须在容器上调用revalidate()repaint(),即接受新JLabel的JPanel。通常最好在程序启动时添加JLabel,而不必担心这些问题。甲

此外,什么事件会触发此更改?您的问题和代码不足以让我们确定。我脑海中的某些事情令我担心你还没有编写事件监听器,因为我们没有看到上面的任何代码表明上面的代码存在于监听器中。请澄清。

如果仍然卡住,请创建并发布有效的minimal example program

你还没有发布有效的mcve,所以我们仍然需要猜测(请阅读链接),

但是在您的MouseListener中,您正在更改闪烁字段的状态,但您没有调用任何会更改图像的代码。我怀疑您发布的关键代码:

if (flashed == 1) 
{
     bbol.setIcon(bboH);
} else {
}

出现在GUI创建代码中。如果是这样,则只调用一次,并且仅使用闪烁的原始值。如果您更改闪烁字段的值,则不会神奇地重新调用此代码,而是您必须自己调用。换句话说,此代码应该在MouseListener中。

同样,如果您需要更多帮助,请发布此处发布的有效mcve代码作为代码格式的文本,我们可以实际编译并运行。

此外,如果你想要一个闪烁的图标,那么你将需要创建并使用一个Swing Timer,一个每隔xxx毫秒交换图标的Swing Timer。

例如:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.image.BufferedImage;

import javax.swing.*;

@SuppressWarnings("serial")
public class BlinkingIcon extends JPanel {
    private static final int IMG_WIDTH = 200;
    private static final int GAP = 8;
    private static final int TIMER_DELAY = 100;

    // index into icons array
    private int iconIndex = 0;

    // array of image icons
    private Icon[] icons = new Icon[2];

    // JLabel that displays the icons
    private JLabel mainLabel = new JLabel();

    // Swing Timer that when started swaps the icons 
    private Timer flashingTimer = new Timer(TIMER_DELAY, new TimerListener());

    public BlinkingIcon() {
        // fill icons array with icons
        icons[0] = createIcon(Color.WHITE);
        icons[1] = createIcon(Color.RED);

        // add the first icon to the JLabel
        mainLabel.setIcon(icons[iconIndex]);

        // add the JLabel to the main JPanel, the GUI
        add(mainLabel);

        // add a MouseListener to the JLabel
        // one that turns the flashing timer on and off
        mainLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (flashingTimer.isRunning()) {
                    flashingTimer.stop();
                } else {
                    flashingTimer.start();
                }
            }
        });
    }

    // for this example, I will create a simple icon that's little more than
    // a color circle, but any icons would work
    private Icon createIcon(Color white) {
        BufferedImage img = new BufferedImage(IMG_WIDTH, IMG_WIDTH, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = img.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(white);
        g2.fillOval(GAP, GAP, IMG_WIDTH - 2 * GAP, IMG_WIDTH - 2 * GAP);
        g2.setStroke(new BasicStroke((float) GAP));
        g2.setColor(Color.BLACK);
        g2.drawOval(GAP, GAP, IMG_WIDTH - 2 * GAP, IMG_WIDTH - 2 * GAP);
        g2.dispose();
        Icon icon = new ImageIcon(img);        
        return icon;
    }

    // ActionListener for our flashingTimer
    private class TimerListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // add one to the iconIndex, the index to the icons array
            iconIndex++;
            iconIndex %= icons.length; // set to 0 if it reaches length of array
            mainLabel.setIcon(icons[iconIndex]); // swap the icon!            
        }
    }

    private static void createAndShowGui() {
        BlinkingIcon mainPanel = new BlinkingIcon();

        JFrame frame = new JFrame("Blinking Icon");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

关于您发布的代码,您有MouseListener代码但是将其添加到没有组件,并且只有将它们附加到某些内容时才能使用侦听器,例如

game.addMouseListener(this);