Thursday, May 20, 2021

[Java Code Sample] Create a Health Bar with JProgressBar

Here's a sample code to create a simple health bar with JProgressBar.


In this code, the bar represents player's HP and the meter decreases if you hit the "damage" button.


Check the video tutorial for details:








import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;

public class Game {
	
	JFrame window;
	JPanel healthBarPanel, buttonPanel;
	Container con;
	JProgressBar healthBar;
	JButton button;
	int hp;
	
	DamageHandler damageHandler = new DamageHandler();


	public static void main(String[] args) {
		
		new Game();

	}
	
	public Game(){
			
		window = new JFrame();
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().setBackground(Color.black);
		window.setLayout(null); 	
		con = window.getContentPane();	
		
		healthBarPanel = new JPanel();
		healthBarPanel.setBounds(250, 250, 300, 30);
		healthBarPanel.setBackground(Color.black);
		con.add(healthBarPanel);
		
		healthBar = new JProgressBar(0,100);
		healthBar.setPreferredSize(new Dimension(300,30));
		healthBar.setValue(100);
		healthBarPanel.add(healthBar);
		
		buttonPanel = new JPanel();
		buttonPanel.setBounds(250, 300, 300, 40);
		buttonPanel.setBackground(Color.black);
		con.add(buttonPanel);
		
		button = new JButton("Receive Damage");
		button.setBackground(Color.black);
		button.setForeground(Color.white);
		button.setFocusPainted(false);
		button.addActionListener(damageHandler);
		buttonPanel.add(button);
		
		hp = 100;
			
		window.setVisible(true);
		
	}
	
	public void damageReceived(){
		
		hp = hp -10;
		healthBar.setValue(hp);
	}
	

	public class DamageHandler implements ActionListener{
		
		public void actionPerformed(ActionEvent event){
			
			damageReceived();
		}
	}

}

Here's the result:


*If you press the button, the HP decreases.


No comments:

Post a Comment