因此,我正在制作一个游戏,我想在单击 JButton 时更改屏幕上已经存在的图像的图像,但是我尝试的任何方法都不起作用,所以我在这里寻求帮助。
这是我的代码:
package frametest;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class FrameTest extends JFrame implements ActionListener {
JPanel totalGUI, player1, buttons;
JLabel p1a, p1b;
JButton change1, change2;
ImageIcon C2 = new ImageIcon("Pictures\\cards\\C2.png");
ImageIcon SK = new ImageIcon("Pictures\\cards\\SK.png");
ImageIcon HJ = new ImageIcon("Pictures\\cards\\HJ.png");
public JPanel createContentPane(){
JPanel totalGUI = new JPanel();
totalGUI.setBackground(new Color( 52, 186, 119 ));
totalGUI.setLayout(null);
//Speler 1
JPanel player1 = new JPanel();
player1.setLocation(240,431);
player1.setSize(190,110);
player1.setBackground(new Color( 52, 186, 119 ));
totalGUI.add(player1);
JLabel p1a = new JLabel();
p1a.setIcon(C2);
p1a.setLocation(0,0);
player1.add(p1a);
pack();
JLabel p1b = new JLabel();
p1b.setIcon(SK);
p1b.setLocation(0,20);
player1.add(p1b);
pack();
//Knoppen
JPanel buttons = new JPanel();
buttons.setLayout(null);
buttons.setLocation(700,435);
buttons.setSize(200,90);
totalGUI.add(buttons);
JButton change1 = new JButton("Jack of Hearts");
change1.setLocation(0,0);
change1.setSize(200,30);
change1.addActionListener(this);
buttons.add(change1);
JButton change2 = new JButton("King of Spades");
change2.setLocation(0,30);
change2.setSize(200,30);
change2.addActionListener(this);
buttons.add(change2);
totalGUI.setOpaque(true);
return totalGUI;
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == change1) {
p1a.setIcon(HJ);
} else if(e.getSource() == change2 ) {
p1a.setIcon(SK);
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Poker Game");
FrameTest demo = new FrameTest();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000,600);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}}
看来我必须在这篇文章中写更多才能发布它,但我不知道该写什么......