How do I refresh the panel with a two dimensional button array? - java

I'm making a chess game in Java. And because I'm a beginner at Swing, I ran into a problem right away. I made a two dimensional array of buttons for the chessboard tiles. The problem is when my first button is clicked I do not know how to refresh that button or the panel it is in.
Here is the code.
public class Table extends JFrame implements ActionListener{
public JButton[][]tile = new JButton[8][8];
JPanel gamePAN = new JPanel();
int size=8;
Tile[][] tileList = new Tile[8][8];
private final Color lightTileColor = Color.decode("#FFFACD");
private final Color darkTileColor = Color.decode("#593E1A");
public Table() {
this.setResizable(true);
this.setVisible(true);
this.setTitle("Chess");
initCompoments();
Toolkit tk = Toolkit.getDefaultToolkit();
int xsize = (int) tk.getScreenSize().getWidth();
int ysize = (int) tk.getScreenSize().getHeight();
this.setSize(xsize, ysize);
private void initCompoments() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
gamePAN.setLayout(new java.awt.GridLayout(8, 8, 0, 0));
getContentPane().add(gamePAN);
gamePAN.setBounds(550, 100, 800, 800);
pack();
}
private void initialize() {
//gamePAN = new JPanel();
//gamePAN.setLayout(new GridLayout(size,size));
for(int i=0;i<size;i++) {
for(int j=0; j<size;j++) {
if(i%2==0) {
if(j%2==0) {
tile[i][j] = new JButton();
tile[i[j].setBackground(lightTileColor)
tile[i[j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}else {
tile[i][j] = new JButton();
tile[i[j].setBackground(darkTileColor);
tile[i[j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}
}else {
if(j%2==0) {
tile[i][j] = new JButton();
tile[i[j].setBackground(darkTileColor);
tile[i][j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}else {
tile[i][j] = new JButton();
tile[i[j].setBackground(lightTileColor);
tile[i][j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}
}
}
}
#Override
public void actionPerformed(ActionEvent ae) {
for(int r=0;r<size;r++) {
for(int c=0;c<size;c++) {
if(ae.getSource()==tile[r][c]) {
if(tileList[r[c].getPiece()!=null) {
tileList[r][c].getPiece().kretanje(tile, tileList);
}
}
}
}

The problem is when my first button is clicked I do not know how to refresh that button or the panel it is in
There is no need for all the looping code in the ActionListener.
The ActionEvent will contain the reference to the button that was clicked.
So in the ActionListener you add to the button your basic code would be:
JButton button = (JButton)ae.getSource();
button.setIcon(...); // do whatever you want with the button

Related

How do I delete an image inside a JLabel by right clicking my mouse

I'm working on an Animal Project and I want to improve the project with the MouseListener functions, but I cannot find out how to do this specific bit and I've looked everywhere. Here is my code so you get a good idea at what I'm doing.
Main Class
public class Animals {
public static void main(String[] args) {
JFrame application = new JFrame("Animal Project");
GUI graphicalInterface = new GUI();
application.add(graphicalInterface);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.setLocation(200, 200);
application.pack();
application.setVisible(true);
application.setResizable(false);
}
Sub Class
public class GUI extends JPanel implements ActionListener {
private JButton animalOption = new JButton();
private JButton save = new JButton();
private JButton load = new JButton();
private JButton clear = new JButton();
private JPanel buttonPanel;
private JPanel imagePanel;
private ImageIcon bear;
private ImageIcon tiger;
private ImageIcon lion;
private JLabel imageBlock1;
private JLabel imageBlock2;
private JLabel imageBlock3;
private int choice;
private int count = 1;
private JLabel currImageBlock = null;
GUI() {
Border blackline = BorderFactory.createLineBorder(Color.black);
//create button panel
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(100, 230));
buttonPanel.setOpaque(true);
buttonPanel.setBackground(Color.white);
buttonPanel.setBorder(blackline);
imagePanel = new JPanel(new GridLayout(3, 3));
imagePanel.setPreferredSize(new Dimension(500, 500));
imagePanel.setOpaque(true);
imagePanel.setBackground(Color.white);
imagePanel.setBorder(blackline);
imageBlock1 = new JLabel();
imageBlock1.setPreferredSize(new Dimension(100, 100));
imageBlock1.setOpaque(true);
imageBlock1.setBackground(Color.white);
imageBlock1.setBorder(blackline);
imageBlock2 = new JLabel();
imageBlock2.setPreferredSize(new Dimension(100, 100));
imageBlock2.setOpaque(true);
imageBlock2.setBackground(Color.white);
imageBlock2.setBorder(blackline);
imageBlock3 = new JLabel();
imageBlock3.setPreferredSize(new Dimension(100, 100));
imageBlock3.setOpaque(true);
imageBlock3.setBackground(Color.white);
imageBlock3.setBorder(blackline);
bear = new ImageIcon("Bear.png");
tiger = new ImageIcon("Tiger.png");
lion = new ImageIcon("Lion.png");
animalOption = new JButton();
//add action listener to each button
animalOption.addActionListener(this);
//set button size
animalOption.setPreferredSize(new Dimension(100, 50));
//set text for each button
animalOption.setText("Animal");
animalOption.setToolTipText("press to select your animal");
//add buttons to gui
buttonPanel.add(animalOption);
save = new JButton();
//add action listener to each button
save.addActionListener(this);
//set button size
save.setPreferredSize(new Dimension(100, 50));
//set text for each button
save.setText("Save");
save.setToolTipText("press to save your selection");
//add buttons to gui
buttonPanel.add(save);
load = new JButton();
//add action listener to each button
load.addActionListener(this);
//set button size
load.setPreferredSize(new Dimension(100, 50));
//set text for each button
load.setText("Load");
load.setToolTipText("press to load your selection");
//add buttons to gui
buttonPanel.add(load);
clear = new JButton();
//add action listener to each button
clear.addActionListener(this);
//set button size
clear.setPreferredSize(new Dimension(100, 50));
//set text for each button
clear.setText("Clear");
clear.setToolTipText("press to clear your selection");
//add buttons to gui
buttonPanel.add(clear);
this.add(buttonPanel);
this.add(imagePanel);
imagePanel.add(imageBlock1);
imagePanel.add(imageBlock2);
imagePanel.add(imageBlock3);
}
public void actionPerformed(ActionEvent e) {
if (count == 1) {
currImageBlock = imageBlock1;
} else if (count == 2) {
currImageBlock = imageBlock2;
} else if (count == 3) {
currImageBlock = imageBlock3;
} else if (count > 3 && e.getSource().equals(animalOption)) {
JOptionPane.showMessageDialog(imagePanel, "Your choices have exceeded, please press clear.");
}
if (e.getSource().equals(animalOption) && count < 4) {
choice = selectAnimal();
if (choice == 1) {
currImageBlock.setIcon(bear);
currImageBlock.setToolTipText("This is a bear");
} else if (choice == 2) {
currImageBlock.setIcon(tiger);
currImageBlock.setToolTipText("This is a tiger");
} else if (choice == 3) {
currImageBlock.setIcon(lion);
currImageBlock.setToolTipText("This is a lion");
}
chooseNumber();
count++;
}
if (e.getSource().equals(clear)) {
imageBlock1.setIcon(null);
imageBlock2.setIcon(null);
imageBlock3.setIcon(null);
imageBlock1.revalidate();
imageBlock2.revalidate();
imageBlock3.revalidate();
count = 1;
}
}
static int selectAnimal() {
int animal = 0;
String theAnimal = JOptionPane.showInputDialog("Please enter animal, type 1 for bear, type 2 for tiger, type 3 for lion");
animal = Integer.parseInt(theAnimal);
return animal;
}
And this is what it looks like when I run the code and after I've selected which Animal I want
I have a clear all button where if I click it, it clears all the images in inside the imageBlock Jlabel, however I want to add a feature where if I right click on the specific JLabel the image and all its contents will be deleted inside that specific JLabel. Any help would really be appreciated.
This example code shows how a mouse listener can be used to perform an action (in this case - remove) on an image set as icon within a JLabel. Note a MouseAdapter is used in the code but a MouseListener interface can be implemented with similar result.
Other ways of performing this function:
Select an image label and click a button to remove it.
Open a context or pop-up menu with remove image menu option - when the image label is right-clicked upon.
The example code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ImageLabelAction {
private JLabel imageBlock;
private ImageIcon koala = new ImageIcon("koala.jpg");
public static void main(String [] args) {
new ImageLabelAction().gui();
}
private void gui() {
JFrame frame = new JFrame();
frame.setTitle("Frame with Image Label");
imageBlock = new JLabel();
imageBlock.setPreferredSize(new Dimension(100, 100));
imageBlock.setOpaque(true);
imageBlock.setBackground(Color.white);
imageBlock.setBorder(BorderFactory.createLineBorder(Color.black));
imageBlock.setIcon(koala);
imageBlock.addMouseListener(new PictureRemoveListener());
frame.add(imageBlock);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(250, 250);
frame.setVisible(true);
}
private class PictureRemoveListener extends MouseAdapter {
#Override public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
imageBlock.setIcon(null);
}
}
}
}
You could set a mouse listener to just move it way out of the frame when right clicked. Or you can make a boolean if mouse is clicked set true and only show that object if the boolean is true, so where you set the image from the file only run that code if right mouse button hasn't been clicked
Something like the following pseudo code:
imageBlock1.addMouseListener(new MouseAdapter() {
public void mouseClicked (MouseEvent e) {
// use flags to figure out if it is right mouse click
imageBlock1.setIcon(null);
}
});
Do this for imageBlock2, 3, 4 etc.
It has been a while but something along those lines could do what you are asking.

Java Repaint gridlayout

I am trying to repaint a snake game I am creating on the new game action.It is working but it isn't clearing the old snake body or blocks from the screen.
public class View extends JFrame implements ActionListener {
private static final long serialVersionUID = -2542001418764869760L;
public static int viewWidth = 20;
public static int viewHeight = 20;
private SidePanel side;
private JMenuBar menuBar;
private JMenuItem newGameButton;
private JMenu menu, mode;
private SnakeController sController;
private GamePanel gamePanel;
/*
* Initialize the game's panels and add them to the window.
*/
public View() {
menuBar = new JMenuBar();
menu = new JMenu("Menu");
menuBar.add(menu);
newGameButton = new JMenuItem("New Game");
menu.add(newGameButton);
newGameButton.addActionListener(this);
mode = new JMenu("Mode");
menuBar.add(mode);
this.setJMenuBar(menuBar);
this.gamePanel = new GamePanel(this);
this.side = new SidePanel(this);
this.add(gamePanel, BorderLayout.CENTER);
this.add(side, BorderLayout.EAST);
Tuple position = new Tuple(10, 10);
sController = new SnakeController(position, side, gamePanel);
this.addKeyListener((KeyListener) new Listener());
// this.requestFocus();
pack();
}
public static void main(String args[]) {
View window = new View();
window.setTitle("og-snake");
window.setSize(700, 400);
window.setVisible(true);
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newGameButton) {
System.out.println("clicked");
gamePanel.removeAll();
gamePanel.revalidate();
gamePanel.repaint();
Tuple position = new Tuple(10, 10);
sController = new SnakeController(position, side, gamePanel);
sController.start();
}
}
This is my main class that basically makes a view adds a side panel and board panel.The action performed is done on the new game action on the game panel.
public class GamePanel extends JPanel {
public static ArrayList<ArrayList<ColorCell>> snakeGrid;
public static int viewWidth = 20;
public static int viewHeight = 20;
ArrayList<ColorCell> data;
SnakeController sc ;
private View game;
public GamePanel(View game) {
this.game = game;
this.snakeGrid = new ArrayList<ArrayList<ColorCell>>();
this.data = new ArrayList<ColorCell>();
for (int i = 0; i < viewWidth; i++) {
data = new ArrayList<ColorCell>();
for (int j = 0; j < viewHeight; j++) {
ColorCell c = new ColorCell(2);
data.add(c);
}
snakeGrid.add(data);
}
setLayout(new GridLayout(viewWidth, viewHeight, 0, 0));
setPreferredSize(new Dimension(400,400));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < viewWidth; i++) {
for (int j = 0; j < viewHeight; j++) {
add(snakeGrid.get(i).get(j).viewCell);
}
}
}
}
gamePanel.removeAll();
gamePanel.fillGrid();
gamePanel.revalidate();
gamePanel.repaint();
Tuple position = new Tuple(10, 10);
this.gamePanel = new GamePanel(this);
this.add(gamePanel,BorderLayout.CENTER);
That code doesn't really do anything. When you add a component to the CENTER of the BorderLayout it does not replace the original component.
The way Swing painting works is that the last component added is painted first. So this means the newly added panel is painted and then the original panel is painted over top of the newly added panel.
So, since you have logic to remove all the components from the original gamePanel, there is no need to create a new gamePanel. Just reset the state of the game panel.

how do i create a virtual keyboard that can be used to insert values in different jtextfields

So I am trying to create a virtual keyboard that can insert values in a Jtextfield of another Jframe. The problem is that the data is overlapping when editing other text fields. So, I tried renewing the object but it replaced the first Jtextfield value as well. what should i do with this, should i start from scratch or is there any other way? . Since, English is not my first language I am struggling to find the correct terminology to research the problem please enlighten me with your knowledge
import java.awt.*;
import javax.swing.*;
public class OnScreenKeyboard implements ActionListener {
JFrame keyboard;
static String keyboardKeys = "0123456789qwertyuiopasdfghjklzxcvbnm.< ";
JButton[] keys = new JButton[39];
GridLayout gl;
FlowLayout fl;
Dimension buttondimension;
JPanel panel1, panel2;
JToggleButton capslock;
private String message = "";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public OnScreenKeyboard() {
buttondimension = new Dimension(45, 40);
fl = new FlowLayout();
capslock = new JToggleButton("capslock");
panel1 = new JPanel(fl);
panel2 = new JPanel(fl);
char[] key = keyboardKeys.toCharArray();
for (int i = 0; i < 39; i++) {
keys[i] = new JButton(String.valueOf(key[i]));
keys[i].setFont(new Font("Arial", Font.PLAIN, 13));
if (i == 38) {
keys[i].setPreferredSize(new Dimension(100, 30));
} else {
keys[i].setPreferredSize(buttondimension);
}
keys[i].addActionListener(this);
}
keyboard = new JFrame("Keyboard");
keyboard.setSize(720, 220);
keyboard.setLocationRelativeTo(null);
keyboard.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
keyboard.setResizable(false);
Container content = keyboard.getContentPane();
content.setLayout(null);
panel1.setBounds(1, 1, 500, 210);
panel2.setBounds(510, 1, 200, 210);
for (int i = 0; i < 10; i++) {
panel2.add(keys[i]);
}
for (int i = 10; i < 39; i++) {
panel1.add(keys[i]);
}
panel1.add(capslock);
content.add(panel1);
content.add(panel2);
capslock.addActionListener(this);
keyboard.setVisible(true);
}
public static void main(String[] args) {
new OnScreenKeyboard();
}
public void reset(){
message = "";
}
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 36; i++) {
if (e.getSource() == keys[i]) {
setMessage(getMessage() + keys[i].getText());
break;
}
}
if (e.getSource() == capslock) {
if (capslock.isSelected()) {
for (int i = 10; i < 36; i++) {
keys[i].setFont(new Font("Arial", Font.PLAIN, 12));
keys[i].setText(keys[i].getText().toUpperCase());
}
} else if (!capslock.isSelected()) {
for (int i = 10; i < 36; i++) {
keys[i].setFont(new Font("Arial", Font.PLAIN, 13));
keys[i].setText(keys[i].getText().toLowerCase());
}
}
}
setMessage(getMessage());
//JOptionPane.showMessageDialog(null, getMessage());
}
}
this is the frame I am trying to put my values from the keyboard in
public class LoginScreen implements ActionListener, FocusListener {
JFrame frame;
Container content;
FlowLayout fl;
JTextField txtusername, txtpassword;
JLabel lblusername, lblpassword;
JPanel panel1, panel2;
JButton keyboard, signup, signin;
OnScreenKeyboard kyb;
Dimension text;
private void init() {
text =new Dimension(100, 30);
fl = new FlowLayout(FlowLayout.CENTER);
lblusername = new JLabel("enter username");
lblpassword = new JLabel("enter password");
txtusername = new JTextField();
txtpassword = new JPasswordField();
keyboard = new JButton("keyboard");
signup = new JButton("signup");
signin = new JButton("sign in");
panel1 = new JPanel(fl);
panel2 = new JPanel(fl);
keyboard = new JButton("keyboard");
txtusername.setPreferredSize(text);
txtpassword.setPreferredSize(text);
kyb = new OnScreenKeyboard();
}
public LoginScreen() {
init();
frame = new JFrame("BorderLayoutDemo");
frame.setTitle("Registration Form");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(3);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
content = frame.getContentPane();
content.setLayout(new GridLayout(2, 1));
panel1.add(lblusername);
panel1.add(txtusername);
panel1.add(lblpassword);
panel1.add(txtpassword);
panel2.add(signup);
panel2.add(signin);
panel2.add(keyboard);
content.add(panel1);
content.add(panel2);
keyboard.addActionListener(this);
txtusername.addFocusListener(this);
txtpassword.addFocusListener(this);
}
public static void main(String[] args) {
new LoginScreen();
}
#Override
public void actionPerformed(ActionEvent e) {
if (!kyb.keyboard.isVisible()) {
if (e.getSource() == keyboard) {
kyb = new OnScreenKeyboard();
}
}
}
#Override
public void focusGained(FocusEvent e) {
if(txtusername == e.getSource()){
txtusername.setText(kyb.getMessage());
}else if(txtpassword == e.getSource()){
kyb.reset();
txtpassword.setText(kyb.getMessage());
}
}
#Override
public void focusLost(FocusEvent e) {
}
The problem is that it's weird how/when the text is taken from the keyboard.
You use the LoginScreen both as actionListener on the keyboard and as focusListener on the 2 textfields.
The way you implemented it now is that you "type" something in on the keyboard and after that put the focus on 1 of the 2 fields. Only at the moment you click the text from the keyboard is fetched (kyb.getMessage()).
It's especially a problem on the password. If you click on the txtpassword field you first reset the kyb and then fetch the message (which you just reset so is empty).
What felt weird for me is that you don't have a way in the keyboard to notion that you are done typing. So the flow of only getting the message when the focus changes to one of the text fields is wrong.
What I would do is create a new kind of KeyboardListener. This listener is put on the txtusername OR txtpassword depending on who last took focus (so in the focusGained() you should change who is listening to the keyboard).
Then each time a key is "typed" you should notify the listener of the letter and then the txtusername/txtpassword (whichever is listening at that time) should add that letter to its text.
This means that the keyboard itself doesn't need to remember any text. It just figures out which key was pressed and then sends the corresponding letter to the listener.
You should be using a TextAction as your ActionListener. The TextAction has a method getFocusedComponent() which will return the last text component to have focus.
Then in the can add the character to the text field. So the basic code in the actionPerformed(...) method of the TextAction might be something like:
JTextComponent component = getFocusedComponent();
component.replaceSelection( the character to add );

Cannot find a way to create a loading screen

I was just messing around with GUI in Java and created a little game. In it, 105 randomly placed buttons are created and then an instruction screen pops up, telling the user which button to find. I've tried to figure out how to program a "Loading..." JDialog, which will pop up while the buttons are being created in the background. The trouble is, when I run the program the JDialog doesn't load until AFTER all the buttons have been created, which kind of defeats the purpose of the box in the first place. How can I force the "Loading..." box to load BEFORE the buttons begin to be created??? Thanks in advance.
Because I've just been tinkering, my code is not perfect but here it is:
import java.util.Scanner;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.ProgressMonitor;
public class ButtonGame {
private static int butNum = 1;
private static JFrame frame;
private static ActionListener notIt;
private static ActionListener it;
private static Random rand = new Random();
private static int butToFind = rand.nextInt(105);
private static JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
//actionlistener for all incorrect buttons (buttons that are "not it")
notIt = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
JFrame frame5 = (JFrame) SwingUtilities.getRoot(component);
frame5.dispose();
}
};
//actionlistener for the correct button (the button that's "it")
it = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame youWin = new JFrame("YOU WON!");
//removes all panels to begin game again
JButton again = new JButton("Play again");
again.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
java.awt.Window windows[] = java.awt.Window.getWindows();
for(int i=0;i<windows.length;i++){
if (windows[i] != frame) { windows[i].dispose(); }
butToFind = rand.nextInt(105);
butNum = 1;
youWin.dispose();
}
frame.setVisible(true);
}
});
//quits game
JButton win = new JButton("Quit");
win.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//layout
youWin.setSize(775, 300);
youWin.setLayout(new FlowLayout());
JLabel label1 = new JLabel("Fantastic!");
Font font1 = new Font("Courier", Font.BOLD,120);
label1.setFont(font1);
label1.setHorizontalAlignment(JLabel.CENTER);
JLabel label2 = new JLabel("You beat the game!");
Font font2 = new Font("Courier", Font.BOLD,60);
label2.setFont(font2);
label2.setHorizontalAlignment(JLabel.CENTER);
youWin.add(label1);
youWin.add(label2);
JPanel panel = new JPanel();
youWin.add(panel);
panel.add(again);
panel.add(win);
youWin.setLocation(260, 100);
youWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
youWin.setVisible(true);
java.awt.Window windows[] = java.awt.Window.getWindows();
}
};
//start window
frame = new JFrame("Window");
frame.setLocation(400, 200);
JButton button1 = new JButton("Click to begin");
//button to begin game
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// JDialog load = new JDialog();
// load.setAlwaysOnTop(true);
// load.setSize(500,500);
// load.setVisible(true);
// load.add(new Label("Loading..."));
// load.pack();
frame.setVisible(false); // "start" window's visibility
// try {
// Thread.sleep(100000);
// } catch (Exception t) {
// }
// creates buttons
for (int i = 0; i < 105; i++) {
JFrame nextFrame = newFrame(butNum);
nextFrame.setVisible(true);
butNum++;
}
//creates instructions and tells user what button to find
JFrame instructions = new JFrame("How to play");
instructions.setSize(300,175);
instructions.setLayout(new GridLayout(4,1));
JPanel instPanel = new JPanel();
//button to remove instruction panel
JButton ok = new JButton("Ok");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
instructions.dispose();
}
});
instPanel.add(ok);
instructions.setLocation(400,200);
//layout of instruction panel
JLabel find = new JLabel("Your goal is to find Button " + butToFind + ".");
find.setHorizontalAlignment(JLabel.CENTER);
JLabel find2 = new JLabel("Click a button to make it disappear.");
find2.setHorizontalAlignment(JLabel.CENTER);
JLabel find3 = new JLabel("Good luck!");
find3.setHorizontalAlignment(JLabel.CENTER);
instructions.add(find);
instructions.add(find2);
instructions.add(find3);
instructions.add(instPanel);
instructions.setVisible(true);
}
});
frame.add(button1);
frame.setSize(150,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//creates frame with button in it
public static JFrame newFrame(int num) {
JFrame frame2 = new JFrame();
JButton button = new JButton("Button " + num);
if (num == butToFind) {
button.addActionListener(it);
frameToClose = frame2;
} else {
button.addActionListener(notIt);
}
frame2.add(button);
frame2.setSize(randNum(90,200), randNum(50,100));
frame2.setLocation(rand.nextInt(1200), rand.nextInt(800));
frame2.getContentPane().setBackground(new Color(rand.nextInt(255),
rand.nextInt(255),
rand.nextInt(255)));
frame2.setVisible(true);
return frame2;
}
//provides random number between high and low
public static int randNum(int low, int high) {
int result = -1;
while (result < low || result > high) {
result = rand.nextInt(high);
}
return result;
}
}
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static? Thanks!
First take a look at The Use of Multiple JFrames, Good/Bad Practice? and understand why I freaked out when I ran your code...
Instead of creating a bunch of frames, why not use something like JButton on another JPanel and add it to the current frame (this would also be a good use for a CardLayout)
JPanel panel = new JPanel(new GridLayout(10, 0));
Random rnd = new Random();
// creates buttons
for (int i = 0; i < 105; i++) {
JButton btn = new JButton(String.valueOf(i));
panel.add(btn);
//JFrame nextFrame = newFrame(butNum);
//nextFrame.setVisible(true);
//butNum++;
}
frame.getContentPane().removeAll();
frame.add(panel);
frame.revalidate();
frame.pack();
Alternatively, if you're really hell bent on using "frames", consider using a JDesktopPane and JInternalFrame instead.
See How to Use Internal Frames for more details
Also, as a side-question, which of the variables defined before main should be static? And how can I get the program to compile without being static?
As much as possible, none. Instead of trying to create the whole thing in the main method, use the classes constructor to initialise the UI and use another method to actually get the game rolling...
public class ButtonGame {
private int butNum = 1;
private JFrame frame;
private ActionListener notIt;
private ActionListener it;
private Random rand = new Random();
private int butToFind = rand.nextInt(105);
private JFrame frameToClose;
//private static int mouseClicks;
//private static double time;
public static void main(String[] args) {
ButtonGame game = new ButtonGame();
game.start();
}
public ButtonGame() {
//... All the code that was once in main...
frame.add(button1);
frame.setSize(150, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void start() {
frame.setVisible(true);
}
Answering to your side questions:
a static method can only accept static global variables
You can put all your code in the constructor and use main to only run the program.
Constructor:
public ButtonGame() {
// All of your code goes here - except the static methods
}
You should also make all other methods non-static.
To run the program:
public static void main(String[] args) {
new ButtonGame();
}

create Jbuttons from ActionListener variable

the mission here is to create JButtons from a String in ActionListener, but we need a way to refresh the GUI panel so it know that there is now variable for the button creater in the GUI. i have a feeling that the button creater must be in ActionListener and there is a command like repaint() or removeAll that is missing inside the ActionListener.
public JButton[] turneringer = null;
JButton AntallTurneringer = new JButton("number of buttons");
JMenuBar meny = new JMenuBar();
JMenu fil = new JMenu("somthing");
JMenuItem angre = new JMenuItem("deleate on button");
JMenuItem angre2 = new JMenuItem("deleate all buttons");
int d;
int i;
public GUI(){
this.setTitle("somthing");
this.setSize(500,500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.setJMenuBar(meny);
meny.add(fil);
fil.add(angre2);
fil.add(angre);
angre2.addActionListener(this);
angre.addActionListener(this);
AntallTurneringer.addActionListener(this);
this.add(AntallTurneringer);
AntallTurneringer.setVisible(true);
if(d > 0){
turneringer = new JButton[d];
for(i = 0; i < d; i++){
turneringer[d] = new JButton();
turneringer[d].addActionListener(this);
turneringer[d].setText("Turnering "+(i+1));
turneringer[d].setVisible(true);
this.add(turneringer[d]);
}}
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource().equals(AntallTurneringer)){
String tu = JOptionPane.showInputDialog(null, "number of buttons");
d = Integer.parseInt(tu);
}
}
You could use a separate panel for the buttons. would simplify the whole thing.
private JPanel buttonPnl;
public void actionPerformed(ActionEvent e){
buttonPnl.invalidate();
buttonPnl.clear();
//create the new buttons
buttonPnl.validate();
buttonPnl.repaint();
}
I have solved it, it were no need for repainting or clearing anything. the first problem in the code were that i had used [d] inside the array, and not[i]. the second problem were the placement of the for loop. this is the working code under.
public JButton[] turneringer = null;
JButton AntallTurneringer = new JButton("Velg antall turneringer");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
int d;
public GUI(){
this.setTitle("Squash Turnering");
this.setLayout(new GridLayout());
this.setSize(500,500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
panel1.setBackground(Color.BLACK);
panel2.setBackground(Color.RED);
AntallTurneringer.addActionListener(this);
AntallTurneringer.setVisible(true);
panel1.add(AntallTurneringer);
add(panel1);
add(panel2);
panel2.setVisible(false);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource().equals(AntallTurneringer)){
String tu = JOptionPane.showInputDialog(null, "number of buttons you want to add");
d = Integer.parseInt(tu);
turneringer = new JButton[d];
for(int i = 0; i < d; i++){
turneringer[i] = new JButton();
turneringer[i].addActionListener(this);
turneringer[i].setText("Turnering "+(i+1));
turneringer[i].setVisible(true);
turneringer[i].setSize(100, 100);
panel2.add(turneringer[i]);
}
panel1.setVisible(false);
panel2.setVisible(true);
}
}}

Categories