我正在写一个带有占位符资产的角色创建者迷你游戏。它应该是具有六个按钮的GUI,其中三个按钮可以改变简笔画的头发,衣服和鞋子,另外三个按钮可以将其删除。
我尝试将setVisible(true)添加为headBUTTON_ActionPerformed()的最后一行,但它没有改变。图片的位置很好,因为它们出现了,但不是立即显示。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
public class GUI extends JFrame {
private Avatar pc = new Avatar();
private JLabel flavortext = new JLabel();
private JButton headBUTTON = new JButton();
private JLabel base = new JLabel();
BufferedImage baseImage;
public GUI(){
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
int frameWidth = 755;
int frameHeight = 618;
setSize(frameWidth, frameHeight);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (d.width - getSize().width) / 2;
int y = (d.height - getSize().height) / 2;
setLocation(x, y);
setTitle("CREATOR");
//setResizable(false);
try {
setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("assets/bg.png")))));
} catch (IOException e) {
e.printStackTrace();
}
headBUTTON.setBounds(24, 160, 113, 41);
headBUTTON.setText("change Head");
headBUTTON.setMargin(new Insets(2, 2, 2, 2));
headBUTTON.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
headBUTTON_ActionPerformed(evt);
}
});
add(headBUTTON);
try {
baseImage = ImageIO.read(new File("assets/base.png"));
base.setIcon(new ImageIcon(baseImage));
} catch(Exception e) {
e.printStackTrace();
}
base.setBounds(210, 128, 371, 449);
add(base);
setVisible(true);
} // end of public GUI
public static void main(String[] args) {
new GUI();
}
public void headBUTTON_ActionPerformed(ActionEvent evt) {
pc.changeHead();
JLabel headd = new JLabel();
headd.setIcon(new ImageIcon(pc.getHead()));
headd.setBounds(210, 128, 371, 449);
add(headd);
setVisible(true);
}
}
This is the Avatar class:
public class Avatar{
private String gender;
private BufferedImage head;
private BufferedImage body;
private BufferedImage bottom;
public int countH, countBot, countBod;
Avatar(){
countH = 1;
countBod = 1;
countBot = 1;
}
public BufferedImage getHead(){
return head;
}
public BufferedImage getBody(){
return body;
}
public BufferedImage getBottom(){
return bottom;
}
public void changeHead(){
try {
if (countH > 2) {
countH = 1;
}
head = ImageIO.read(new File("assets/hair"+countH+".png"));
countH++;
} catch(Exception e) {
}
}
public void changeBody(){
try {
if (countBod > 2) {
countBod = 1;
}
body = ImageIO.read(new File("assets/body"+countBod+".png"));
countBod++;
} catch(Exception e) {
}
}
public void changeBottom(){
try {
if (countBot > 2) {
countBot = 1;
}
bottom = ImageIO.read(new File("assets/bottom"+countBot+".png"));
countBot++;
} catch(Exception e) {
}
}
}
基本图像和背景图像正确显示,但是单击按钮时,我必须调整窗口大小以使“头发”出现。目前,我只尝试使“ Head”按钮起作用。