Assign JButton for-loop - java

String[] nomMois =
{"Janvier","FĂ©vrier","Mars","Avril","Mai","Juin","Juillet","Aout",
"Septembre","Octobre","Novembre","Decembre"};
JPanel tabJPanelMois[] = new JPanel[nomMois.length];
for(int indice=0; indice<tabJPanelMois.length; indice++){
tabJPanelMois[indice]= new JPanel();
tabJPanelMois[indice].setLayout(new GridLayout(0,7,8,18));
for(int j=1; j<=Date.dernierJourDuMois(indice+1,2017);j++){
tabJPanelMois[indice].add(new JButton(Integer.toString(j)));
}
I want to put an ActionListener on each Button but with that code i don't assign a name for each JButton so I can't,how must I do?

Define a temporal Button, and use it in the loop, creating a new object will allow you to recycle the variable x as much as you need:
JButton x;
for(int j=1; j<=Date.dernierJourDuMois(indice+1,2017);j++){
x = new JButton(Integer.toString(j));
x.setMyNewListener(abcListner);
tabJPanelMois[indice].add(x);
}

Related

Is there a way I can stick this into a for loop?

I updated the code to use for loops, and an arrayList for the buttons. now it has given me an error.
java.lang.NullPointerException
BlueJ editor is pointing to this line.
for(int i=0; i<=buttonsList.size(); i++){
I think it has something to do with instance variables not existing or something before the arrayList. Also, it compiles perfectly, but when I run main, it then goes back to the line in the code!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
//Created class the extends JFrame, and implements action listener
public class Board extends JFrame implements ActionListener
{
//Instance variables
private JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, reset;
private ArrayList<JButton> buttonsList;
//'playerO' uses the letter 'O', not the number zero
Icon playerO = new ImageIcon("images/playerO.jpg");
Icon playerX = new ImageIcon("images/playerX.jpg");
Icon playerN = new ImageIcon("images/reset.jpg");
//Instance variable to determine player turn
boolean firstPlayer = true;
//Constructor
public Board()
{
//Title of Frame
super("Gui7 - TicTacToe || Jose Reyes");
//Created container and set the layout
Container c = getContentPane();
c.setLayout(new BorderLayout());
//Created a panel, and set the layout
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(3,3));
//Created new JButtons and added them to the array list
for(int i=0; i<=buttonsList.size(); i++){
JButton jBut = new JButton(playerN);
buttonsList.add(jBut);
}
//Created reset button and title
reset = new JButton("Play Again?");
//Added buttons to panel with for loop
for(int i=0; i<=buttonsList.size(); i++){
gridPanel.add(buttonsList.get(i));
}
//Added panel and reset button to container
c.add(gridPanel);
c.add(reset, BorderLayout.PAGE_END);
//Added Action Listeners with loop
for(int i=0; i<=buttonsList.size(); i++){
buttonsList.get(i).addActionListener(this);
}
//Added action listener to reset button
reset.addActionListener(this);
//Set the window size and set visibility
setSize(600,600);
setVisible(true);
}
//ActionEvents
public void actionPerformed(ActionEvent e)
{
//Grab source
Object src = e.getSource();
for (int i = 0; i<=buttonsList.size(); i++){
if(src == buttonsList.get(i)){
if(firstPlayer){
buttonsList.get(i).setIcon(playerO);
firstPlayer = false;
} else {
buttonsList.get(i).setIcon(playerX);
firstPlayer = true;
}
}
}
//Reset button icons with loop
if(src == reset){
for (int i = 0; i < 9; i++){
buttonsList.get(i).setIcon(playerN);
}
firstPlayer = true;
}
}
//Main method
public static void main (String args[])
{
Board t = new Board();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Yes you can do this with a for loop.
First, store all your buttons in an array or arraylist. Since the other answer is an array, I'll do arraylist.
ArrayList<Button> buttonsList = new ArrayList<>();
buttonsList.add(b1);
buttonsList.add(b2);
etc. Then,
for (Button b: buttonsList){
if (src == b) {
if (firstPlayer) {
b.setIcon(playerO);
firstPlayer = false;
} else {
b.setIcon(playerX);
firstPlayer = true;
}
}
}
EDIT:
I suggest you just use an arraylist instead of array. Its much easier to work with since you don't need to specify a size before hand.
Instead of this line:
private JButton buttons[];
Do
private ArrayList<Button> buttonList = new Arraylist()<>;
Additionally change,
for(int i=0; i<10; i++){
buttons[i] = new JButton(playerN);
}
//do this instead
for(int i=0; i<10; i++){
JButton jBut = new JButton(playerN);
buttonsList.add(jBut);
}
//Added buttons to panel with for loop
for(int i=0; i<10; i++){
gridPanel.add(buttons[i]);
}
//Do this instead
//Added buttons to panel with for loop
for(int i=0; i<10; i++){
gridPanel.add(buttonsList.get(i));
}
EDIT2:
This is almost definitely causing one of your problems lol
//Added Action Listeners with loop
for(int i=0; i<10; i++){
buttons[1].addActionListener(this);
}
You are adding the listener to the second button- buttons[1] every time. Change that to buttons[i].addActionListener(this); and it will probably work.
Rather than have a bunch of variables named b1...b9, make an array of whatever type b1 is. Then you can iterate over the array like this:
for (int i = 0; i < 9; i++){
if(src == bArray[i]){
if(firstPlayer){
bArray[i].setIcon(playerO);
firstPlayer = false;
} else {
bArray[i].setIcon(playerX);
firstPlayer = true;
}
}
}
something like below should work.
JButton[] buttons = new JButton[9]; // i'll leave you to fill it
for(int i = 0; i < buttons.length; i++){ // assuming the array is filled
if(src == buttons[i]){
if(firstPlayer){
buttons[i].setIcon(playerO);
firstPlayer = false;
} else {
buttons[i].setIcon(playerX);
firstPlayer = true;
}
}
}

Identify objects in an array created from a for-loop

I have a project that deals with a three panels populated with jbuttons. The jbuttons are created from a for-loop and I was too lazy to recreate a class that has a jpanel populated with jbuttons because it conflicts with my actionlisteners.
Lets say I have three panels each populated with the code:
JPanel panel109 = new JPanel(); //113, 115 for the other two
roomPanel.add(panel109);
for(int j = 0; j < 6*28; j++) {
btn[j] = new JButton();
btn[j].setName("a" + j);
btn[j].setBackground(Color.white);
btn[j].setText("");
btn[j].setPreferredSize(new Dimension(35,9));
btn[j].addActionListener(this);
panel109.add(btn[j]);
}
For each panel, how do I identify each btn[] created? I wanted to serialize each button after the user specifies datas to change the button's color, tool tip text and etc. Pretty much I just want to know how to access the buttons I created since three panels use the same loop.
The serialization of all the buttons are from a "store" button, and then "restore" if I want to restore from a file created from it.
Store code:
JButton btnStore = new JButton("Store");
btnStore.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream (new FileOutputStream("myFile"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
for (int i=0;i<6*28;i++){
//deregister
btn[i].removeActionListener(this);//Heres my problem,
//serialize //I Don't know how to access
try { //the buttons created from the
out.writeObject(btn[i]); //three loops.
} catch (IOException e1) {
e1.printStackTrace();
}
try {
out.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
//register
btn[i].addActionListener(this);
}
}
});
You can use JPanel.putClientProperty() to store the JButton[]:
panel109.putClientProperty("btn", btn);
then access it by
JButton[] btn = (JButton[])panel109.getClientProperty("btn");
You could also use a Map (which is what putClientProperty() is using in the end, though it's a more general Map<Object,Object>):
Map<JPanel,JButton[]> mapPanelButtons = new HashMap<>();
mapPanelButtons.put(panel109, btn);
...
JButton[] btn = mapPanelButtons.get(panel109);
Edit: from your edit with the Store button code, I think you would be better off subclassing JPanel to include the JButton[] as a member and get direct access anywhere. Laziness is good when it helps you figure out the quickest approach, not the dirtiest ;)
That said, you could be using getClientProperty() in your Store button action listener code like this:
public void actionPerformed(ActionEvent e) {
...
JButton[] btn = (JButton[])panel109.getClientProperty("btn");
for (int i=0;i<6*28;i++){ // You might want to use btn.length instead of 6*28
// ... rest of your code
}
}
Nested loop?
for (int i = 0; i < roomPanel.size(); i++) {
JPanel panel = roomPanel[i];
for (int j = 0; j < numButtons; j++) {
btn[i][j] = new JButton();
btn[i][j].setName(i +"-"+ j);
btn[i][j].setBackground(Color.white);
btn[i][j].setText("");
btn[i][j].setPreferredSize(new Dimension(35,9));
btn[i][j].addActionListener(this);
panel.add(btn[i][j]);
}
}
Assuming roomPanel is your list of panels.
I ultimately ended up creating 3 different JButton[] arrays for each panel respectively to make things simpler and to meet the deadline, but honestly I think there's a more simpler way to do it.
JPanel panel109 = new JPanel();
JButton[] btnOne = new JButton();
for(int j = 0; j < 6*28; j++) {
btnOne[j] = new JButton();
btnOne[j].setName("a" + j);
btnOne[j].setBackground(Color.white);
btnOne[j].setText("");
btnOne[j].setPreferredSize(new Dimension(35,9));
btnOne[j].addActionListener(this);
panel109.add(btnOne[j]);
}
JPanel panel115 = new JPanel();
JButton[] btnTwo = new JButton();
for(int j = 0; j < 6*28; j++) {
btnOne[j] = new JButton();
btnTwo[j].setName("b" + j);
btnTwo[j].setBackground(Color.white);
btnTwo[j].setText("");
btnTwo[j].setPreferredSize(new Dimension(35,9));
btnTwo[j].addActionListener(this);
panel115.add(btnTwo[j]);
}
....
This makes each array of JButtons unique to itself and can be accessed more easily.

Adding JButton by loop causes ArrayIndexOutOfBoundsException

I have a swing application which I have declared a JButton array inside it's constructor inside that class I have created a for loop in order to add a number of 114 JButton to class container.
but when that class runs it gives the exception
java.lang.ArrayIndexOutOfBoundsException: 0
On the statement that adding the Buttons to Container.
Can someone see the problem?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main extends JFrame implements ActionListener
{
public Main()
{
Container pane = getContentPane();
JPanel panel = new JPanel();
JButton b[];
int i;
for (i = 0; i < 114; i++)
{
b = new JButton[i];
panel.add(b[i]);
}
pane.add(panel);
}
public void actionPerformed(ActionEvent ae)
{
}
public static void main(String[] args)
{
Main m = new Main();
m.setSize(500, 500);
m.setVisible(true);
}
}
You can't made expression like that
for(i=0; i<114;i++)
{
b = new JButton[i];
panel.add(b[i]);
}
In first execution it is new JButton[0], so your array size is 0.
You should use Collection (fe. ArrayList) or fixed size JButton array.
JButton[] b = new JButton[114];
for(i=0; i<114;i++)
{
b[i] = new JButton();
panel.add(b[i]);
}
At i = 0, b = new JButton[i]; creates an array of size 0, so trying to reference b[0] (i.e. the first element) will be out of bounds.
And you never construct b[i].
You probably want to move the array construction outside the loop, something like:
b = new JButton[114];
for (i = 0; i < 114; i++)
{
b[i] = new JButton();
panel.add(b[i]);
}
since b is an array type which holding collection of JButton objects.So you need to create
one JButton object for each location of that array. The code what Dukeling is given is
correct approach. And also one thing you have forgotten,You need to define the size of
your array like JButton b[]=new JButton[size];

how to add label to hangman game

these are my code I've problem with label when i read line from the text filed i can add the labels "_" that they are equal to the size of the word the program road it before.
I've problem creating label , I hope you understand my problem & please if you can can you give me a solution ?
public class HangGame extends JFrame {
JLabel lbl;
JLabel word ;
private String[]myword = new String [20];
Game() {
}
void readfile () {
Properties prob = new Properties();
try{
for(int x=0; x<n; x++){
}
}}
private void initLabelPanel() {
//craete array of labels the size of the word
letterHolderPanel = new JPanel();
int count =0;
//if you run my code I've problem with this array [myword.length()] the compiler can not find it.
wordToFindLabels = new JLabel[myword.length()];
//Initiate each labels text add tp array and to letter holder panel
for (int i = 0; ih; i++) {JLabel lbl = new JLabel("_");
letterHolderPanel.add(lbl);
lbl.setBounds();
}
}
}
myword is an array of Strings, not a single String so you need to replace:
wordToFindLabels = new JLabel[myword.length()];
with
wordToFindLabels = new JLabel[myword.length];
You could rename the variable to, say, mywordArray, to avoid confusion.
Also use a layout manager rather than using absolute positioning(null layout).
See: Doing Without a Layout Manager (Absolute Positioning)
length is property not method change the code accordingly
wordToFindLabels = new JLabel[myword.length];
and now youre code will be
for (int i = 0; i < wordToFindLabels.length; i++) {
String labelValue="";
if(myword[i] != null) {
for (int j = 0; j < myword[i].length(); j++){
labelValue+="_"
}
}
JLabel lbl = new JLabel(labelValue);
wordToFindLabels[i] = lbl;
letterHolderPanel.add(lbl);
lbl.setBounds(30, 60, 20, 20);
}

How do I parse a string to an object's name?

So I have a small amount of objects (10 JLabels) and I want to change their text depending on the users input.
The Initializer for the labels goes like this:
private JLabel j1 = new JLabel();
private JLabel j2 = new JLabel();
private JLabel j3 = new JLabel();
...etc
and continues on to 10.
How do I mass change the text of each JLabel without writing each variable name every time?
I had an idea like below, but I don't know how to access the variable by name from strings.
for(int x=1;x<=10;x++){
String d = (String) x; //this isn't what d equals, it's example.
String label = "j"+x;
label.setText(d); //I know this won't work, but this is what I want to do
}
Is there any way this can be done without errors?
This is an excellent chance to use an array to store your JLabel objects:
private JLabel[] labels = new JLabel[10];
for (int i=0; i<10; i++) {
labels[i] = new JLabel();
}
/* ... */
for (int i=0; i<10; i++) {
labels[i].setText("Hello from label " + i);
}
If you have created the JLabel as an array like JLabel j[10] = new JLabel[10]. Then you can use the for loop to create an instance for each index and then set the text as well.
for(int x=0;x<10;x++){
j[x] = new JLabel();
String d = String.valueOf(x);
String label = "j"+x;
j[x].setText(d);
}

Categories

Resources