如何将 GUI 项目始终设置为最前面?



我用Java制作了一个简单的GUI界面游戏。这是一款RPG游戏,在界面的某个地方,它有一个进度条,这是生命条,在里面,它有其他GUI项目,一个文本,这是角色生命的价值。

起初它工作得很好,但我在一个攻击按钮上添加了一个ActionerListener,它的作用是减少生命条和生命值(在文本上(,就像对游戏的真正攻击一样。但是当我这样做时,我会出现一个错误。

有时生命条停留在生命值的前面,有时它不是,就像完全随机的。所以我的问题是:有没有办法将 Gui 项目始终设置在前面?在这种情况下,生命的价值。

Obs:我有一个抽象类(CharactersInterface(,我在其中声明所有的东西和兽人的敌人。

public class wizardInterface extends CharactersInterface{
//interface
public wizardInterface() {
//your name
you = new JLabel(wizard.name);
you.setBounds(85, 20, 160, 30);
panel.add(you);
//hit points
yhitpoints = new JLabel(wizard.hp + "/25");
yhitpoints.setBounds(95, 51, 50, 15);
panel.add(yhitpoints);
//life bar
ylife.setValue(wizard.hp*4);
ylife.setBounds(50, 50, 125, 18);
ylife.setForeground(Color.GREEN);
panel.add(ylife);
//your image
image1 = new ImageIcon(getClass().getResource("wizard.png"));
img1 = new JLabel(image1);
img1.setBounds(50, 80, 128, 128);
panel.add(img1);
//text
text = new JTextArea("Choose your spell!");
text.setFont(new Font("Serif", Font.PLAIN, 16));
text.setBackground(null);
text.setBounds(185, 300, 160, 45);
panel.add(text);
//thunder button
Icon thunder = new ImageIcon(getClass().getResource("thunder.png"));
attack1 = new JButton("Thunder", thunder);
attack1.setBounds(20, 350, 230, 140);
panel.add(attack1);
//fire button
Icon fire = new ImageIcon(getClass().getResource("fire.png"));
attack2 = new JButton("Fire", fire);
attack2.setBounds(280, 350, 230, 140);
panel.add(attack2);
//background image
backgroundImage = new ImageIcon(getClass().getResource("background1.png"));
background = new JLabel(backgroundImage);
background.setBounds(0, -20, 535, 300);
panel.add(background);
//do something when press the button
thehandler handler = new thehandler();
attack1.addActionListener(handler);
attack2.addActionListener(handler);
}
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent event) {
if(event.getSource()==attack1){
orc.hp -=  1 + dice.nextInt(10) +  wizard.intelligence; // 1d10 +2;
}else if(event.getSource()==attack2){
orc.hp -= 3 + dice.nextInt(8) + wizard.intelligence; // 1d8 +4
}
//here is where I reduce the life of the enemy
elife.setValue(orc.hp*2);
ehitpoints.setText(orc.hp + "/50");
if(orc.hp <=0){
System.out.println("you won");
System.exit(0);
}
//orc attacks
wizard.hp -= 1 + dice.nextInt(4) + orc.strong; //1d4 + 2 
ylife.setValue(wizard.hp*4);
yhitpoints.setText(wizard.hp + "/25");
if(wizard.hp <=0){
System.out.println("you lose");
System.exit(0);
}
}
} 

起初它工作得很好,但我在一个攻击按钮中添加了一个ActionerListener,它的作用是减少生命条和生命值(在文本上(,就像对游戏的真正攻击一样。

每次你降低角色的生命值或增加它时,试着将焦点转移到你想在前面的物体上......前任:-

bar.requestFocus();

相关内容

最新更新