Trouble with CheckBox matrix, loops won't work - java

I am writing a program which will have multiple windows that will pass a value between them.
Currently I am testing one part of my program that is made out of 1-99 checkboxes. But when I want to check their states by clicking on a button it just doesn't work. Here's where the problem is:
public void actionPerformed(ActionEvent event) {
if(event.getSource() == okay) {
for(int i=0;i<box.length; i++){
for(int j=0;j<box.length; j++){
if((i==0)&&(j==0)) continue;
if(box[i][j].getState())
asdf.matra[i][j]=true;
System.out.println(box[i][j].getLabel() + " is " + asdf.matra[i][j]);
}
}
}
}
here's the main class:
public class asdf {
public static boolean matra[][] = new boolean[10][10];
public static void main(String arg[]) {
for(int ii=0;ii<matra.length; ii++){
for(int jj=0;jj<matra.length; jj++){
matra[ii][jj]=false;
}
}
new JFrameDemo();
}
}
and the other class:
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
public class JFrameDemo extends Frame implements ActionListener, ItemListener {
Checkbox box[][] = new Checkbox[10][10];
Button okay;
JFrameDemo() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
add(makePanel());
pack();
show();
}
private Panel makePanel() {
GridBagConstraints con = new GridBagConstraints();
Panel panel = new Panel();
GridBagLayout gridbag = new GridBagLayout();
panel.setLayout(gridbag);
for(int i=0;i<box.length; i++){
for(int j=0;j<box.length; j++){
if((i==0)&&(j==0)) continue;
box[i][j] = new Checkbox(i+j*10+"");
con.gridx = i;
con.gridy = j;
panel.add(box[i][j],con);
}
}
okay = new Button("Unesi");
con.gridx = 10;
con.gridy = 10;
panel.add(okay,con);
return(panel);
}
public void actionPerformed(ActionEvent event) {
if(event.getSource() == okay) {
for(int i=0;i<box.length; i++){
for(int j=0;j<box.length; j++){
if((i==0)&&(j==0)) continue;
if(box[i][j].getState())
asdf.matra[i][j]=true;
System.out.println(box[i][j].getLabel() + " is " + asdf.matra[i][j]);
}
}
}
}
public void itemStateChanged(ItemEvent event) {
}
public void processWindowEvent(WindowEvent event) {
if(event.getID() == WindowEvent.WINDOW_CLOSING)
System.exit(0);
}
}
The program is running without any errors, but the console isn't giving any results. It is supposed to pass value to the global variable also. I think there's an issues with nested fors.

You are forgetting to add the ActionListener to the button.
okay = new Button("Unesi");
okay.addActionListener(this);

Related

JButton method I cannot find

I'm working on a TicTacToe game at the moment as a personal project and so far I know I'm almost complete with the game except for the part where I have to check if the x or o's are equal and in a line. Here's my code below here. My problem is in the connected method, it compiles and run's, but when I tried to add the middle horizontal row after just only one JButton was pressed it said the person won which should not be the case. I think I need a method that is named isDisabled(), instead of isEnabled for the JButton, but for some reason I don't think there is such a method in the java library. I know for sure if I had isDisabled() it would work for sure
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Usman on 5/17/2016.
*/
public class TicTacToeGUI extends JPanel {
boolean turn = true;
JButton[] board;
public TicTacToeGUI() {
setLayout(new GridLayout(3,3));
board = new JButton[9];
for (int i = 0; i < board.length; i++) {
board[i] = new JButton("");
board[i].setPreferredSize(new Dimension(70, 60));
board[i].setFont(new Font("Arial", Font.PLAIN, 40));
int finalI = i;
board[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(board[finalI].isEnabled()){
if(turn){
board[finalI].setText("X");
turn = !turn;
}
else{
board[finalI].setText("O");
turn = true;
}
board[finalI].setEnabled(false);
}
Connected();
}
});
add(board[i]);
}
}
public void Connected(){
int count =0;
//Horizontal top row
if((board[0].isEnabled() == board[1].isEnabled()) && (board[1].isEnabled() == board[2].isEnabled())){
System.out.println(count++);
for(int i = 0; i < board.length; i++)
board[i].setEnabled(false);
}
}
public static void main(String []args){
TicTacToeGUI game = new TicTacToeGUI();
JFrame frame = new JFrame("Tic Tac Toe");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(game);
frame.pack();
frame.setVisible(true);
}
}
Just use (!whatever.isEnabled())
The character '!' is similar to a NOT in Java. So it will behave like isDiabled()

How to set a dynamic setIcon on a JRadioButton

I've some issues with my code for studies, it's our first time with Java and I don't know how to change the icon of JRadioButtons contents in an array.
package exo_02_01;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JRadioButton;
import javax.swing.JToolBar;
#SuppressWarnings("serial")
public class ControleEtiquette extends JToolBar {
private ImageIcon[] m_iconesBoutons = new ImageIcon[18];
private JRadioButton[] m_boutons = new JRadioButton[6];
private String m_nomsIcones[] = { "bhgauche", "bhcentre", "bhdroite", "bvhaut", "bvcentre", "bvbas" };
private static final int NUMBER_BUTTONS = 6;
public ControleEtiquette() {
super();
chargerIcones();
creerBoutons();
}
private void chargerIcones() {
for (int i = 0; i < NUMBER_BUTTONS; i++) {
m_iconesBoutons[i] = new ImageIcon("RESGRAF/" + m_nomsIcones[i] + ".gif");
m_iconesBoutons[i + NUMBER_BUTTONS] = new ImageIcon("RESGRAF/" + m_nomsIcones[i] + "R.gif");
m_iconesBoutons[i + NUMBER_BUTTONS * 2] = new ImageIcon("RESGRAF/" + m_nomsIcones[i] + "B.gif");
}
}
private void creerBoutons() {
for (int i = 0; i < m_boutons.length; ++i) {
m_boutons[i] = new JRadioButton(m_iconesBoutons[i]);
add(m_boutons[i]);
m_boutons[i].addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e)
{
((JRadioButton) e.getSource()).setIcon(m_iconesBoutons[0]);
}
public void mouseClicked(MouseEvent e) {
((JRadioButton) e.getSource()).setIcon(m_iconesBoutons[NUMBER_BUTTONS * 2 - 1]);
}
public void mouseExited(MouseEvent e) {
((JRadioButton) e.getSource()).setIcon(m_iconesBoutons[5]);
}
});
if (i == 2)
addSeparator();
}
}
My code in my chargerBoutons() method work well, but my aim is to set the icon according to the current button. I tried to do like
((JRadioButton) e.getSource()).setIcon(m_iconesBoutons[i]);
But i is undefined in this scope.
How can I fix it ?
Thanks
Actually, I think you set the icon correctly, but you have to ask for an update of the UI...
So add the call updateUI() at the end of your creerBoutonsmethod. (it apply on the toolbar (ie: your object).
see JToolbar

action listener doesnt work

I am new in java swing unfortunately when i want to set action listener to one of the button that it has to get the textArea content and send that to another class it doesn't work in a way that i expect and instead it works when i change the text area's content, i don't know What's happened?
first button i named Button and the same problem happened when i use another action listener inside the Button's action listener named Clac
here is my code:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class FFT_Main_Frame extends JFrame {
JLabel label;
JButton button;
TextPanel txtPanel;
JButton Button;
JLabel label1;
// JTextArea[] BoxArray;
makePolynomial mp;
JButton Calc;
Complex[] Nums;
Complex[] Result;
int input;
FFT_Main fft_main;
ShowResult shr;
public FFT_Main_Frame() {
Button.addActionListener(new ActionListener() {
// Test t;
// Integer content;
#Override
public void actionPerformed(ActionEvent arg0) {
try {
Integer content = new Integer(Integer.parseInt(txtPanel.getTextArea()));
input = content;
System.out.println(input);
// inputt=input;
mp = new makePolynomial(content);
setLayout(new FlowLayout());
add(mp);
// setLayout(new BorderLayout());
add(Calc);
Nums = new Complex[input + 1];
Calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
for (int i = input; i >= 0; i--) {
Nums[i] = new Complex(Double.parseDouble(mp.BoxArray[2 * (i + 1) - 1].getText()),
Double.parseDouble(mp.BoxArray[2 * i].getText()));
}
for (int i = 0; i <= input; i++) {
System.out.println(Nums[i]);
}
fft_main = new FFT_Main();
Result = new Complex[input];
Result = fft_main.Recursive_FFT(Nums);
shr = new ShowResult(Result);
setLayout(new BorderLayout());
add(shr, BorderLayout.CENTER);
System.out.println("Result\n\n");
for (int i = 0; i <= input; i++) {
System.out.println(Result[i]);
}
}
});
} catch (NumberFormatException exception) {
JOptionPane.showMessageDialog(null, "Please Enter Just Numbers! ", "Wrong Value",
JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
thanks for your help
You are using action listener wrong way here is an example how to use it
public FFT_Main_Frame() {
JButton Button = new JButton("Button");
Button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
// Code Here
}catch(Exception e) {
// Code Here
}
});
JButton Calc = new JButton("Calc");
Calc.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// Code Here
}
});
}
}
Some tutorials on how to use action listener
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
http://www.tutorialspoint.com/swing/swing_action_listener.htm

java programing swing application

import java.awt.BorderLayout;
import java.applet.Applet;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.awt.*;
public class MemoryGame implements ActionListener
{
Label mostra;
public int delay = 1000; //1000 milliseconds
public void init()
{
//add(mostra = new Label(" "+0));
}
public void Contador()
{
ActionListener counter = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tempo++;
TempoScore.setText("Tempo: " + tempo);
}
};
new Timer(delay, counter).start();
}
public void updateHitMiss()
{
HitScore.setText("Acertou: " + Hit);
MissScore.setText("Falhou: " + Miss);
PontosScore.setText("Pontos: " + Pontos);
}
private JFrame window = new JFrame("Jogo da Memoria");
private static final int WINDOW_WIDTH = 500; // pixels
private static final int WINDOW_HEIGHT = 500; // pixels
private JButton exitBtn, baralharBtn, solveBtn, restartBtn;
ImageIcon ButtonIcon = createImageIcon("card1.png");
private JButton[] gameBtn = new JButton[16];
private ArrayList<Integer> gameList = new ArrayList<Integer>();
private int Hit, Miss, Pontos;
public int tempo = 0;
private int counter = 0;
private int[] btnID = new int[2];
private int[] btnValue = new int[2];
private JLabel HitScore, MissScore,TempoScore, PontosScore;
private JPanel gamePnl = new JPanel();
private JPanel buttonPnl = new JPanel();
private JPanel scorePnl = new JPanel();
protected static ImageIcon createImageIcon(String path)
{
java.net.URL imgURL = MemoryGame.class.getResource(path);
if (imgURL != null)
{
return new ImageIcon(imgURL);
}
else
{
System.err.println("Couldn't find file: " + path);
return null;
}
}
public MemoryGame()
{
createGUI();
createJPanels();
setArrayListText();
window.setTitle("Jogo da Memoria");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setVisible(true);
Contador();
}
public void createGUI()
{
for (int i = 0; i < gameBtn.length; i++)
{
gameBtn[i] = new JButton(ButtonIcon);
gameBtn[i].addActionListener(this);
}
HitScore = new JLabel("Acertou: " + Hit);
MissScore = new JLabel("Falhou: " + Miss);
TempoScore = new JLabel("Tempo: " + tempo);
PontosScore = new JLabel("Pontos: " + Pontos);
exitBtn = new JButton("Sair");
exitBtn.addActionListener(this);
baralharBtn = new JButton("Baralhar");
baralharBtn.addActionListener(this);
solveBtn = new JButton("Resolver");
solveBtn.addActionListener(this);
restartBtn = new JButton("Recomecar");
restartBtn.addActionListener(this);
}
public void createJPanels()
{
gamePnl.setLayout(new GridLayout(4, 4));
for (int i = 0; i < gameBtn.length; i++)
{
gamePnl.add(gameBtn[i]);
}
buttonPnl.add(baralharBtn);
buttonPnl.add(exitBtn);
buttonPnl.add(solveBtn);
buttonPnl.add(restartBtn);
buttonPnl.setLayout(new GridLayout(1, 0));
scorePnl.add(HitScore);
scorePnl.add(MissScore);
scorePnl.add(TempoScore);
scorePnl.add(PontosScore);
scorePnl.setLayout(new GridLayout(1, 0));
window.add(scorePnl, BorderLayout.NORTH);
window.add(gamePnl, BorderLayout.CENTER);
window.add(buttonPnl, BorderLayout.SOUTH);
}
public void setArrayListText()
{
for (int i = 0; i < 2; i++)
{
for (int ii = 1; ii < (gameBtn.length / 2) + 1; ii++)
{
gameList.add(ii);
}
}
}
public boolean sameValues()
{
if (btnValue[0] == btnValue[1])
{
return true;
}
return false;
}
public void actionPerformed(ActionEvent e)
{
if (exitBtn == e.getSource())
{
System.exit(0);
}
if (baralharBtn == e.getSource())
{
//
}
if (solveBtn == e.getSource())
{
for (int i = 0; i < gameBtn.length; i++)
{
gameBtn[i].setText("" + gameList.get(i));
gameBtn[btnID[0]].setEnabled(false);
gameBtn[btnID[1]].setEnabled(false);
}
}
for (int i = 0; i < gameBtn.length; i++)
{
if (gameBtn[i] == e.getSource())
{
gameBtn[i].setText("" + gameList.get(i));
gameBtn[i].setEnabled(false);
counter++;
if (counter == 3)
{
if (sameValues())
{
gameBtn[btnID[0]].setEnabled(false);
gameBtn[btnID[1]].setEnabled(false);
gameBtn[btnID[0]].setVisible(false);
gameBtn[btnID[1]].setVisible(false);
Hit = Hit +1;
Pontos = Pontos + 25;
}
else
{
gameBtn[btnID[0]].setEnabled(true);
gameBtn[btnID[0]].setText("");
gameBtn[btnID[1]].setEnabled(true);
gameBtn[btnID[1]].setText("");
Miss = Miss +1;
Pontos = Pontos - 5;
}
counter = 1; //permite 2(3) clikes de cada vez
}
/*if (Pontos <= 0)
{
Pontos=0;
} */
if (counter == 1) // se carregar 1º botão
{
btnID[0] = i;
btnValue[0] = gameList.get(i);
}
if (counter == 2) // se carregar 2º botão
{
btnID[1] = i;
btnValue[1] = gameList.get(i);
}
}
}
if (restartBtn == e.getSource())
{
Hit=0;
Miss=0;
tempo=-1;
Pontos=0;
for (int i = 0; i < gameBtn.length; i++) /* what i want to implement(restart button) goes here, this is incomplete because it only clean numbers and "transforms" into regular JButton, the last two clicks
on the 4x4 grid (btnID[0] and btnID[1]), but i want to clean all the visible
numbers in the grid 4x4, and want to transform all grid 4x4 into default (or
regular color, white and blue) JButton, the grid numbers stay in same order
or position. */
{
gameBtn[btnID[0]].setEnabled(true);
gameBtn[btnID[0]].setText("");
gameBtn[btnID[1]].setEnabled(true);
gameBtn[btnID[1]].setText("");
}
/*
restartBtn.addActionListener(new ActionListener()
{
JFrame.dispatchEvent(new WindowEvent(JFrame, WindowEvent.WINDOW_CLOSING)); // this line is getting errors (MemoryGame.java:233: error: <identifier> expected
JFrame.dispatchEvent(new WindowEvent(JFrame, WindowEvent.WINDOW_CLOSING));
illegal start of type,')' expected, ';' expected all in the same line )
private JFrame window = new JFrame("Jogo da Memoria");
// something not right, i think frame is replaced by JFrame but i dont know, be
}); */
}
updateHitMiss();
}
public static void main(String[] args)
{
new MemoryGame();
}
}
</code>
Hi,
I want to add a restart button (mouse click), i am running notepadd++, when i click on restart button (recomeçar), it should restart this memory game, all counters set to zero etc, clean the grid 4x4, all numbers that were visible when i click the restart the button they all disaapear (but they are in same place or order) thus only show regular JButtons, the game should go to the starting point like when it first open the application, all numbers are not visible. (the functionality of restart button is equal to exit application and then restart).
Restart button code in lines 215 to 239, issues reported on comments between those lines.
I'm not sure if I fully understand your question, but here's what i think would help:
Add an ActionListener to your button with:
button.addActionListener(new ActionListener() {
});,
with button being the name of your JButton.
Within your ActionListener, call frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));, with frame being the name of your JFrame.
Then, run all of the methods you use to initialize your game (including the one that opens the JFrame).
Comment if you need clarification or more help.

How to acces an int from the main class in another class in java?

I have an int a; in the main class and i'd like to use it in the Action Listner class. I've checked for answers but didnt really understand what i had to do since I'm still just a begginer in any kind of programing so if its possible i'd really appreciate a simple solution.
here is my code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Start {
public static void main(String[] args){
JFrame okno = new JFrame("Nonogram");
okno.setVisible(true);
okno.setSize(700, 700);
okno.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
okno.add(panel);
JButton [][] gumbi = new JButton[15][15];
JPanel polje = new JPanel(new GridLayout(15, 15));
panel.add(polje, BorderLayout.CENTER);
int a = 1;
int b = 1;
for(int i = 0; 0 < 15; i++){
for(int j = 0; j < 15; j++){
if(i < 5 && j < 5){
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.RED);
//gumbi[i][j].addActionListener(new Listener(gumbi));
polje.add(gumbi[i][j]);
}else if(i < 5 || j < 5){
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.YELLOW);
//gumbi[i][j].addActionListener(new Listener(gumbi));
polje.add(gumbi[i][j]);
gumbi[i][j].setEnabled(false);
}else{
if(Math.random() <= 0.6){
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.WHITE);
gumbi[i][j].addActionListener(new Listener(gumbi));
gumbi[i][j].setText("3");
polje.add(gumbi[i][j]);
}else {
gumbi[i][j] = new JButton();
gumbi[i][j].setBackground(Color.WHITE);
gumbi[i][j].addActionListener(new Listener(gumbi));
gumbi[i][j].setText("4");
polje.add(gumbi[i][j]);
}
}
if(gumbi[i][j].getText() == "3"){
a += 1;
}
if(i == 14 && j == 14){
gumbi[i][j].setText("" + a);
}
}
}
}
}
and this is what i have in Action Listener
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Listener implements ActionListener {
JButton[][] gumbi;
public Listener(JButton[][] gumbi) {
this.gumbi = gumbi;
}
public void actionPerformed(ActionEvent e){
JButton gumb = (JButton) e.getSource();
if( gumb.getBackground() == Color.WHITE){
gumb.setBackground(Color.BLACK);
} else if (gumb.getBackground() == Color.BLACK){
gumb.setBackground(Color.WHITE);
}
}
}
Thanks for your time.
Define that int a as static with public access and remove it's definition from within your main method as below:
public class Start {
public static int a = 1;//static since you want to use in static method
public static void main(String[] args){
And then in your listener call, you could use .variable like below:
int number = Start.a;
in your current implementation int a is defined in main method and anything declared in a method will be local to the method, you really have to get the basics right , for now u can define the int a public static int a outside the main method , and then access the variable with the class name reference as shown below
public class Start {
public static int a ;
public static void main() {
//your logic
}
}
public class Listener implements ActionListener {
int temp = Start.a;
}
While I agree with another answer that you can make a static in the main class, there might be a neater solution, even though that it is not exactly what was asked.
Instead of attempting to get the value of a from the main, it makes more sense to send along the value of a in the constructor of Listener.
public class Listener implements ActionListener {
JButton[][] gumbi;
final int a;
public Listener(JButton[][] gumbi, int a) {
this.gumbi = gumbi;
this.a = a;
}
...
In the main method simply change the method that adds the listener as follows:
gumbi[i][j].addActionListener(new Listener(gumbi, a));

Categories