I am making a fighting game and the player will choose its class. How do I say If (Player chooses Warrior) then (blah) with my code?
import java.awt.GridLayout;
import javax.swing.*;
public class ButtonTest {
static JDialog dialog;
public static void main(String[] args) {
JDialog dialog = null;
JOptionPane optionPane = new JOptionPane();
optionPane.setMessage("Choose Your Class!");
optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,1));
String[] buttonTxt = {"Warrior","Battlemage","Tank","Archer","Kitty"};
JButton[] buttons = new JButton[buttonTxt.length];
for (int i = 0; i < buttonTxt.length; i++)
{
buttons[i] = new JButton(buttonTxt[i]);
panel.add(buttons[i]);
}
optionPane.setOptionType(JOptionPane.DEFAULT_OPTION);
optionPane.add(panel);
dialog = optionPane.createDialog(null, "Icon/Text Button");
dialog.setVisible(true);
}
}
You can use actionperformed event for all the buttons.
for (int i = 0; i < buttonTxt.length; i++){
buttons[i] = new JButton(buttonTxt[i]);
buttons[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
onClickButton(buttonTxt[i]);
}
});
panel.add(buttons[i]);
}
Make buttonTxt a final variable.
Then you can write your if statement inside onClickButton()
private void onClickButton(String buttonText){
if(buttonText.equals("Warrior")){
//do your stuff
}
}
Related
I am new to java and I am making a Whack a Mole game using a JFrame with JButtons. Currently, I have a 5x5 grid of buttons and that is as far as I got. I am having 3 of the buttons be X (to represent the mole) and 22 be O (to represent an empty hole). I would like for the buttons values to shuffle so that every 2 seconds the values are randomized. How might I go about doing this? Sorry for being such a novice, I literally started java a couple weeks back and JFrames still confuse me lol. Here is the code I currently have, thanks;
import javax.swing.*;
import java.awt.*;
public class Whack_A_Mole extends JFrame {
JButton[][] square = new JButton[5][5];
JButton button1, button2;
static JLabel label = new JLabel();
Whack_A_Mole() {
super("Whack a Mole");
JPanel p = new JPanel(new GridLayout(5,5));
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
square[i][j] = new JButton();
p.add(square[i][j]);
}
}
add(p, BorderLayout.CENTER);
p = new JPanel(new GridLayout(1,2));
setSize(600, 600);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
new Whack_A_Mole();
}
}
If you put the objects in an ArrayList, you can use the shuffle() method to shuffle their order. As to timing, either use Thread.sleep(millisecondsAmt) or a Timer. I prefer the util.Timer, especially when the action repeats indefinitely or for many repetitions.
Create a thread that will add update function into queue every 2 seconds.
import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.util.Random;
public class Wack_A_Mole extends JFrame {
JButton[][] square = new JButton[5][5];
JButton button1, button2;
static JLabel label = new JLabel();
private Thread updateWoker;
Whack_A_Mole() {
super("Whack a Mole");
JPanel p = new JPanel(new GridLayout(5,5));
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
square[i][j] = new JButton();
p.add(square[i][j]);
}
}
add(p, BorderLayout.CENTER);
p = new JPanel(new GridLayout(1,2));
setSize(600, 600);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
setLocationRelativeTo(null);
}
void start(){
updateWoker=new Thread(new Runnable(){
public void run(){
Runnable r=new Runnable(){
public void run() {
buttonUpdate(); // call buttonUpdate every two seconds
}
};
while (true){
javax.swing.SwingUtilities.invokeLater(r);
try{Thread.sleep(2000);} catch (InterruptedException ex) {
return;
}
}
}
}
);
updateWoker.start();
}
public void buttonUpdate(){ // random update can be done in this function
Random r=new Random();
for(int i=0;i<square.length;i++){
for(int j=0;j<square[i].length;j++){
if(r.nextInt() %2==0)
square[i][j].setText("O");
else
square[i][j].setText("X");
}
}
}
public void processWindowEvent(WindowEvent e) {
if (e.getID() == WindowEvent.WINDOW_CLOSING) { // making sure to stop the thread after gui closes
if(updateWoker.isAlive()){
updateWoker.interrupt();
}
dispose();
}
}
public static void main(String[] args) throws InterruptedException {
final Whack_A_Mole theTest=new Whack_A_Mole();
theTest.start();
}
}
I want to have a for loop, that can implement and add a specified number of JButtons the one after the other. I was trying to implement it and this is my code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ArrayForm extends JFrame implements ActionListener
{
JPanel numPanel = new JPanel();
JPanel opPanel = new JPanel();
JTextField textField = new JTextField(25);
JButton [] buttons = new JButton[10];
JButton [] OPbuttons = new JButton[6];
String num="";
String [] operation = {"+","-","*","/","=","C"};
public static void main(String[] args)
{ArrayForm fobject = new ArrayForm();}
public ArrayForm()
{
setLayout(new FlowLayout());
setSize(400,300);
setTitle("Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
numPanel.setPreferredSize(new Dimension(180,150));
numPanel.setLayout(new FlowLayout());
opPanel.setPreferredSize(new Dimension(200,70));
opPanel.setLayout(new FlowLayout());
for (int i = 0; i<10; i++)
{
//The code in here
}
for (int i = 0; i<6; i++)
{
//The code in here
}
add(textField);
this.textField.setEditable(false);
add(numPanel);
add(opPanel);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
}
}
Can you please help me with for loop part? where the first one is buttons array, and the second one is for OPbuttons array.
Your for loop part might be as follows:
for (int i = 0; i<10; i++)
{
buttons[i] = new JButton(""+i);
numPanel.add(buttons[i]);
buttons[i].addActionListener(this);
}
for (int i = 0; i<6; i++)
{
OPbuttons[i] = new JButton(operation[i]);
opPanel.add(OPbuttons[i]);
OPbuttons[i].addActionListener(this);
}
What i have understood, is that you are trying to add the buttons of a calculator automatically, within two different panels...
NB: don't forget to add the code for your Action Listener.
Hello guys I am a rookie programmer so please excuse me if I am trying something stupid.
I started learning about GUI applications today, and I wanted to do a practice to check if I learned it properly. When I run the program, there is a dot on the screen, and I want it to move right when I click on the start button. I accomplished this, however I wanted it to be an animation, I wanted the dot to look as if it was moving slowly. But When I click to button, it just teleports.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Guila extends JFrame {
private JPanel panel;
private JButton myButton;
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 600;
private JPanel[] array = new JPanel[900];
private int i = 0;
int j = 0;
int m = 0;
int k = 0;
public Guila() {
setTitle("Simple Animation");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setLayout(new GridLayout(30, 30));
while(i < 900) {
array[i] = new JPanel();
if(i == 460) {
array[i].setBackground(Color.BLACK);
}
else {
array[i].setBackground(Color.WHITE);
}
panel.add(array[i]);
i++;
}
JPanel panel2 = new JPanel();
myButton = new JButton("Start");
myButton.addActionListener(new myActionListener());
setLayout(new GridLayout(2,1));
add(panel);
panel2.add(myButton);
add(panel2);
setVisible(true);
}
private class myActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
array[460+j].setBackground(Color.WHITE);
array[461+j].setBackground(Color.BLACK);
repeat();
}
}
public void repeat() {
if (j<11) {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
j++;
myButton.doClick();
}
}
public static void main(String[] args) {
new Guila();
}
}
Don't use Thread.sleep() on code that executes on the Event Dispatch Thread.
Use a Swing Timer for animation. Every time the Timer fires you update a property of the component you want to change and then you invoke repaint() on the component.
I agree with using the Swing Timer for animation. Although it might be a challenge to create your desired slow motion effect.
Use the following code to help you get started, if needed:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Bullet extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private static final int SCREEN_WIDTH = 500;
private static final int increments = 5;
int[] xPoints = new int[5];
public void paintComponent(Graphics g)
{
g.setColor(Color.WHITE);
g.fillRect(0,0,800,800);
g.setColor(Color.BLACK);
for (int i = 0; i < xPoints.length; i++)
{
g.fillRect(xPoints[i]+150, 210, 20, 20);
}
Timer timer = new Timer(100, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
for (int i = 0; i <= 1; i++)
{
if (xPoints[i] + increments < SCREEN_WIDTH)
{
xPoints[i] += increments;
} else {
xPoints[i] = 0;
}
}
repaint();
}
});
timer.start();
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Bullet());
frame.setVisible(true);
}
}
So I am relatively new to Java and trying to create a checkers game using JButtons for the board and for the pieces. However I cannot seem to be able to remove a JButton via the ActionListener. Any advice would be appreciated.
public static void main(String[] args) {
checkersBeBitchin begin = new checkersBeBitchin();
}
public checkersBeBitchin(){
box.setLayout(new BorderLayout());
makeBoard();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(600,600);
setTitle("Checkers");
}
private void makeBoard() {
JPanel board = new JPanel();
board.setLayout(new GridLayout(8,8));
for (int i=0; i<8; i++){
for (int j=0; j<8; j++) {
squares[i][j] = new JButton();
ActionListener actionListener = new Board();
squares[i][j].addActionListener(actionListener);
if((i%2 != 0 && j%2 !=0) ||(i%2==0 && j%2 == 0) ){
squares[i][j].setBackground(Color.black);
pieceTracker[i][j]=0;
//System.out.println("Black"+i+","+j); debugging
if(i<3){
int blue = 1;
Icon piece = new ImageIcon(getClass().getResource("/resources/piece.png"));
JButton button = new JButton(piece);
//squares[i][j].setRolloverIcon("image dir") to make it prettier down the road.
squares[i][j].add(button);
pieceTracker[i][j]=blue;
ActionListener Listener = new Blue();
button.addActionListener(Listener);
}
else if (i>4){
int red=-1;
Icon piece = new ImageIcon(getClass().getResource("/resources/piece2.png"));
JButton button = new JButton(piece);
squares[i][j].add(button);
pieceTracker[i][j]=red;
ActionListener Listener = new Red();
button.addActionListener(Listener);
//squares[i][j].setRolloverSelectedIcon("/resources/piece2alt.png");
}
}
else{
squares[i][j].setBackground(Color.white);
pieceTracker[i][j]=0;
//System.out.println("White"+i+","+j); //debugging
}
board.add(squares[i][j]);
}
}
box.add(board, BorderLayout.CENTER);
}
private class Blue implements ActionListener{
public void actionPerformed (ActionEvent e){
System.out.println("You sexy Blue beast.");
Object x = e.getSource();
System.err.println(x);
squares.remove(x);
squares.remove? Should it read squares.remove(x)? Can we see the definition of squares? Is it an array? You must remove the button from the BOARD not the square, e.g. board.remove(x)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class tictac2 implements ActionListener{
static boolean blue = true; //used to keep track of turns. if true, blue's turn, else, red's turn. Blue is x, red is o
static int bWins = 0, rWins = 0;
JFrame mainWindow;
JPanel board;
JButton[] buttons;
public tictac2() {
init();
}
private void init() {
try { //Try to set the L&F to system
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
e.toString();
System.out.println("Couln't change look and feel. Using default");
}
mainWindow = new JFrame("Tic Tac Toe!");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setVisible(true);
mainWindow.setSize(800,600);
JMenuBar bar = new JMenuBar(); //Menu bar init
JMenu file = new JMenu("File");
JMenuItem newGame = new JMenuItem("New Game"), quitItem = new JMenuItem("Quit");
file.add(newGame);
file.addSeparator();
file.add(quitItem);
bar.add(file);
mainWindow.getContentPane().add(bar, BorderLayout.NORTH); //Menu bar done
newGameBoard(); //New Game Board
JPanel infoPane = new JPanel();
infoPane.setLayout(new GridLayout(1,3));
JLabel turn = new JLabel("Blue Player's Turn"), spacer = new JLabel(""), score = new JLabel("Blue: 0, Red: 0");
infoPane.add(turn);
infoPane.add(spacer);
infoPane.add(score);
mainWindow.getContentPane().add(infoPane,BorderLayout.SOUTH);
newGame.addActionListener(this); //Add action listeners
quitItem.addActionListener(this);
}
private void newGameBoard() {
board = new JPanel(); //Game Pane init
board.setLayout(new GridLayout(3,3));
buttons = new JButton[9];
for (int i = 0; i <9; i++){
buttons[i] = new JButton("");
buttons[i].setOpaque(true);
buttons[i].setFont(new Font("sansserif", Font.BOLD, 90));
board.add(buttons[i]);
buttons[i].addActionListener(this);
}
mainWindow.getContentPane().add(board,BorderLayout.CENTER); //Finish game pane init
}
public void actionPerformed(ActionEvent e){
if (e.getSource() instanceof JButton){
JButton j = (JButton)e.getSource();
j.setForeground(tictac2.blue ? Color.BLUE:Color.RED);
j.setText(tictac2.blue ? "X" : "O");
j.setEnabled(false);
tictac2.blue = !tictac2.blue;
}
else if (e.getSource() instanceof JMenuItem){
JMenuItem j = (JMenuItem) e.getSource();
if (j.getText().equals("Quit")) {
System.exit(0);
}
else if (j.getText().equals("New Game")) {
board.removeAll();
mainWindow.remove(board);
board = null;
for (int i = 0; i < 9; i++) {
buttons[i] = null;
}
newGameBoard();
tictac2.bWins = 0;
tictac2.rWins = 0;
tictac2.blue = true;
mainWindow.repaint(100);
}
}
}
public static void main(String[] args) {
new tictac2();
}
}
I am working on a tic tac toe program. In it I have 2 buttons. Whenever I hit new game, the newGameBoard function is supposed to run and make a new board. However, the screen just goes blank! I can't figure it out and would appreciate help. Sorry if I am not posting in the correct format, I am new here.
Thanks so much!
Move mainWindow.setVisible(true) to the end of init(). You don't want to set the frame to visible until you've added everything to it. That way it will validate and layout its subcomponents.
Another solution is to manually call mainWindow.validate() at the end of init(). That's what you have to do if you add components to the frame after making it visible.
use paintAll() or validate() on mainWindow:
mainWindow.validate();
instead of :
mainWindow.repaint(100);
validate and paintAll() as described in API doc.
Your changed code looks like:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TicTac2 implements ActionListener{
static boolean blue = true; //used to keep track of turns. if true, blue's turn, else, red's turn. Blue is x, red is o
static int bWins = 0, rWins = 0;
JFrame mainWindow;
JPanel board;
JButton[] buttons;
public TicTac2() {
init();
}
private void init() {
try { //Try to set the L&F to system
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
e.toString();
System.out.println("Couln't change look and feel. Using default");
}
mainWindow = new JFrame("Tic Tac Toe!");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setVisible(true);
mainWindow.setSize(800,600);
JMenuBar bar = new JMenuBar(); //Menu bar init
JMenu file = new JMenu("File");
JMenuItem newGame = new JMenuItem("New Game"), quitItem = new JMenuItem("Quit");
file.add(newGame);
file.addSeparator();
file.add(quitItem);
bar.add(file);
mainWindow.getContentPane().add(bar, BorderLayout.NORTH); //Menu bar done
newGameBoard(); //New Game Board
JPanel infoPane = new JPanel();
infoPane.setLayout(new GridLayout(1,3));
JLabel turn = new JLabel("Blue Player's Turn"), spacer = new JLabel(""), score = new JLabel("Blue: 0, Red: 0");
infoPane.add(turn);
infoPane.add(spacer);
infoPane.add(score);
mainWindow.getContentPane().add(infoPane,BorderLayout.SOUTH);
newGame.addActionListener(this); //Add action listeners
quitItem.addActionListener(this);
}
private void newGameBoard() {
board = new JPanel(); //Game Pane init
board.setLayout(new GridLayout(3,3));
buttons = new JButton[9];
for (int i = 0; i <9; i++){
buttons[i] = new JButton("");
buttons[i].setOpaque(true);
buttons[i].setFont(new Font("sansserif", Font.BOLD, 90));
board.add(buttons[i]);
buttons[i].addActionListener(this);
}
mainWindow.getContentPane().add(board,BorderLayout.CENTER); //Finish game pane init
}
public void actionPerformed(ActionEvent e){
if (e.getSource() instanceof JButton){
JButton j = (JButton)e.getSource();
j.setForeground(TicTac2.blue ? Color.BLUE:Color.RED);
j.setText(TicTac2.blue ? "X" : "O");
j.setEnabled(false);
TicTac2.blue = !TicTac2.blue;
}
else if (e.getSource() instanceof JMenuItem){
JMenuItem j = (JMenuItem) e.getSource();
if (j.getText().equals("Quit")) {
System.exit(0);
}
else if (j.getText().equals("New Game")) {
board.removeAll();
mainWindow.remove(board);
board = null;
for (int i = 0; i < 9; i++) {
buttons[i] = null;
}
newGameBoard();
TicTac2.bWins = 0;
TicTac2.rWins = 0;
TicTac2.blue = true;
mainWindow.validate();
//mainWindow.repaint();
}
}
}
public static void main(String[] args) {
new TicTac2();
}
}