How to populate a ButtonGroup[] array using a for loop - java

So I have two arrays of JRadioButton[] that I am trying to put into an array of ButtonGroup[]. When I add a single JRadioButton from my array one at a time to a single ButtonGroup, I have no problems. When I use a for-loop to add to an array of ButtonGroup[], there are no syntax errors but I do get a compiler error:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "javax.swing.ButtonGroup.add(javax.swing.AbstractButton)" because "allButtons[x]" is null
I don't mind creating buttonGroups one at a time, but I was just wondering why the first one works and the other doesn't.
The code that works:
//creates radio buttons
JRadioButton[] profButtons = new JRadioButton[profs.length];
JRadioButton[] expButtons = new JRadioButton[profs.length];
for(int i=0; i<profs.length; i++)
{
profButtons[i] = new JRadioButton(profs[i]);
expButtons[i] = new JRadioButton(profs[i]);
}
//makes the radio button groups.
ButtonGroup acrGroup = new ButtonGroup();
acrGroup.add(profButtons[0]);
acrGroup.add(expButtons[0]);
The code that doesn't work:
//creates radio buttons
JRadioButton[] profButtons = new JRadioButton[profs.length];
JRadioButton[] expButtons = new JRadioButton[profs.length];
for(int i=0; i<profs.length; i++)
{
profButtons[i] = new JRadioButton(profs[i]);
expButtons[i] = new JRadioButton(profs[i]);
}
//makes the radio button groups.
ButtonGroup[] allButtons = new ButtonGroup[profs.length];
for(int x=0; x<profs.length; x++)
{
allButtons[x].add(profButtons[x]);
allButtons[x].add(expButtons[x]);
}
profs is a String[] array that I use to label the radio buttons.

In this part of your code, you're creating the array of ButtonGroups, but you never initialize each element, so each of them is null
//makes the radio button groups.
ButtonGroup[] allButtons = new ButtonGroup[profs.length];
for(int x=0; x<profs.length; x++)
{
allButtons[x].add(profButtons[x]);
allButtons[x].add(expButtons[x]);
}
So, inside your for-loop, add this line as the first line
allButtons[x] = new ButtonGroup();
And then, the rest of your code

Related

Putting multiple ButtonGroups in one JFrame

I'm trying to put multiple JButtons on a frame, using ButtonGroup.
I have to put 3 groups of buttons on a frame, seperated form each other.
The following code does create the buttons, but instead of being seperated, they seem to be "deleting" each other.
I'm expecting to see there seperate groups of buttons, 4 buttons each.
The method accepts an ArrayList of a "Question" Objects, which looks like that:
public class Question {
private String _question;
private String _option1;
private String _option2;
private String _option3;
private String _option4;
}
Here's the method. It's inside a class which inherits a frame from another class, "DisplayOnPanel" to set the Panels on the same frame. "this" refers to a frame:
public void addButtonstoFrame(ArrayList<Question> q){
ArrayList<ButtonGroup> BG = new ArrayList<>();
ArrayList<JPanel> JP = new ArrayList<>();
JLabel question1 = new JLabel();
int j=0;
for (int i = 0; i <q.size() ; i++) {
BG.add(new ButtonGroup());
JP.add(new JPanel());
JRadioButton option1 = new JRadioButton(q.get(i).get_option1());
JRadioButton option2 = new JRadioButton(q.get(i).get_option2());
JRadioButton option3 = new JRadioButton(q.get(i).get_option3());
JRadioButton option4 = new JRadioButton(q.get(i).get_option4());
BG.get(j).add(option1);
BG.get(j).add(option2);
BG.get(j).add(option3);
BG.get(j).add(option4);
JP.get(j).add(option1);
JP.get(j).add(option2);
JP.get(j).add(option3);
JP.get(j).add(option4);
this.setLayout(new BorderLayout()); //this referes to a frame
this.add(JP.get(j)); //this referes to a frame
JP.get(i).setLocation(j+10,j+10);
JP.get(j).setVisible(true);
this.setVisible(true);//this referes to a frame
j++;
}
}
And the result is just 4 butoons, instead of 12:
Thank you!
First of all, variable names should NOT start with an upper case character.
JRadioButton option1 = new JRadioButton(q.get(i).get_option1());
JRadioButton option2 = new JRadioButton(q.get(i).get_option2());
JRadioButton option3 = new JRadioButton(q.get(i).get_option3());
JRadioButton option4 = new JRadioButton(q.get(i).get_option4());
BG.get(j).add(option1);
BG.get(j).add(option2);
BG.get(j).add(option3);
BG.get(j).add(option4);
JP.get(j).add(option1);
JP.get(j).add(option2);
JP.get(j).add(option3);
JP.get(j).add(option4);
A component can only belong to a single parent container.
When you add the button to the "JP" contain, you remove it from the "BG" container.
So you need to create 4 more instances of each radio button.

Declare multiplie swing elements at once

I am working on a little game, a Java project for IT-classes.
To add/declare(???) Java swing elements I've used this type of writing:
JLabel A = new JLabel();
JLabel B = new JLabel();
//More JLabels...
JButton A = new JButton();
JButton B = new JButton();
//More JButtons...
That the code does not become longer and (more) confusing, I continued with this type of writing:
JLabel A = new JLabel(), B = new JLabel()/*More JLabels...*/;
JButton A = new JButton(), B = new JButton()/*More JButton...*/;
/*Generaly more comments everywhere over the code for my teacher (and me)
*and more for a better overview.
*/
My question is:
Is there a shorter way to add/declare(???) multiple Java swing elements at once?
//like this
JLabel A, B, C, D, E, F = new JLabel();
//or
new JLabel[A, B, C, D, E, F];//PLS don't ask what I'm doing in this line xD
or may is there already a semilar question in Stackoverflow that I've not found?
Edit
This question may already have an answer here: Initializing multiple
variables to the same value in Java 6 answers
Here the Link to the question
Your question has been identified as a possible duplicate of another
question. If the answers there do not address your problem, please
edit to explain in detail the parts of your question that are unique.
Not worked with Jbuttons and JLabels.
If you are using Java 8 you can use :
List<String> labels = ....;
Stream<Button> stream = labels.stream().map(Button::new);
List<Button> buttons = stream.collect(Collectors.toList());
From the book Java se 8 for the really impatient
Then you can use :
JPanel p = new JPanel();
buttons.forEach((t) -> p.add(t));//add your buttons to your panel
It depends, if all your objects are JLabel or the same object type, you could try:
An array of JLabel like:
JLabel[] labels = new JLabel[size of your array];
Then access it after inside a for loop:
for (int i = 0; i < labels.length; i++) {
labels[i] = new JLabel("I'm label: " + i);
}
A List of labels:
ArrayList <JLabel> labelsList = new ArrayList <JLabel>();
Then you could:
for (int i = 0; i < 10; i++) { //I take 10 as an arbitrary number just to do it in a loop, it could be inside a loop or not
labelsList.add(new JLabel("I'm label-list: " + i));
}
And later you could add them like:
pane.add(labels[i]); //Array
pane.add(labelsList.get(i)); //List
The above code should be inside a loop or change i for the explicit index of the element to be added.
If you want to do the same thing (or a similar thing) many times in a program, the answer is to use a loop of some kind. Here, you could declare an array (or List) of JButton elements, and loop over it to initialize its elements:
final int NUM_BUTTONS = 6;
JButton[] buttons = new JButton[NUM_BUTTONS];
for (int i = 0; i < NUM_BUTTONS; i++) {
buttons[i] = new JButton();
}
// refer to A as buttons[0], C as buttons[2], etc
You can make variables equal to each other after declaring them.
String one, two, three;
one = two = three = "";
So, I think you could do
JLabel A,B,C,D,E,F;
A = B = C = D = E = F = new JLabel();

Java Button Action Command

I'm creating a simple Minesweeper game in Java. Size 9x9.
I create an array of JPanels and an array of buttons; I add each button to its respective JPanel. then i add the JPanels to the JFrame.
How do i distinguish between each button on the action event?
Here's some of my code:
int gridx = 9;
int gridy = 9;
JButton[] buttons = new JButton[gridx*gridy];
JPanel[] jpanels = new JPanel[gridx*gridy];
public Minesweeper(){
super("Minesweeper");
setLayout(new GridLayout(9,9));
JPanel panel = new JPanel();
int i = 0;
for(i = 0; i<gridx*gridy; i++){
jpanels[i] = new JPanel();
buttons[i] = new JButton();
buttons[i].addActionListener(buttonEvent);
jpanels[i].setLayout(new GridLayout(1,1));
jpanels[i].add(buttons[i]);
add(jpanels[i]);
}
//buttons[67].setEnabled(false);
setSize(300,300);
setVisible(true);
}
The only way i can think about doing this is adding text to the button like so:
buttons[i] = new JButton(i);
Then calling getActionCommand() but i dont want text to show up on the button. Any other ideas?
You can use AbstractButton#setActionCommand.
In your loop:
buttons[i].setActionCommand(i+"");
Then you'll get i back when you use getActionCommand
Note I did mention in a comment on another answer that I would create a new class Mine which extends JButton which I believe to be a better and more complete solution. This however gets the job done rather quickly.

NetBeans GuiBuilder - adding table of objects

Is there any way to add "n" Jlabels to the frame, where n is specified somewhere in code? Can I make an Array of Jlabels?
Yes you can
JLabel [] labels = new JLabel[n];
for(int i = 0 ; i <labels.length;i++){
labels[i] = new JLabel("sometext");
//.... and other things
}
It's better to use java.util.List instead of array:
List<JLabel> labels = new ArrayList<>();
for(int i = 0 ; i <labels.length;i++){
labels.add(new JLabel("SomeText"));
labels.get(i).setForeground(Color.red);
//.... and other things
}

how to update a container in java that already has data in it

Hi all i need to update a containers data for a sudoku game i am creating but am struggling to get the field to update with the new data.the container uses a grid layout and each cell contains a button with the appropriate number for sudoku in it and i need to know how to update the text in these buttons. any help with what methods i could use or any help in general would be greatly appreciated. please see the code i currently have to try and update below i know its probably messy and completely on the wrong track but ive just been trying to mess with stuff hoping it would work.
public void update(int[][] grid2)throws NullPointerException{
myGrid = new Container();
try{
for(int i = 0; i<9; i++){
for(int j = 0; j<9; j++){
String appropriateNumber = convertSimple(grid2[i][j]);
JButton button = new JButton(appropriateNumber);
button.addActionListener(new sudokuListener());
myGrid.add(button);
}
}
}
catch(NullPointerException e){
}
myGrid.setLayout(new GridLayout(9, 9));
myGrid.setPreferredSize (new Dimension(400, 400));
add(myGrid);
puzzleGUI.update();
}
puzzlGUI.update simply contains puzzle.validate() (puzzle being the GUI)
[edit]
ok i have changed things around a bit and used the JButton arrya as suggested and i have been able to set the text of the buttons in this array (i know through a system.out.print) but this does not update the text which is in the actual GUI. aaaaahhh coding is not fun at the end of a semester please help anyone
To re-iterate, if you have a grid of JButtons, why re-create them every time? Why not simply iterate through the components that are already in the grid and update their state, such as perhaps the text showing on the JButtons?
for(int i = 0; i<9; i++){
for(int j = 0; j<9; j++){
String appropriateNumber = convertSimple(grid2[i][j]);
someButtonArray[i][j].setText(appropriateNumber);
// no longer need this stuff
// JButton button = new JButton(appropriateNumber);
// button.addActionListener(new sudokuListener());
// myGrid.add(button);
}
}
Your update method is creating new Swing components every time it is called which is unnecessary if you just need to update the text. To directly update the text in any JButton you could create a button array like so:
JButton[][] buttons = new JButton[9][9];
and create like this (called only once):
for (int i = 0; i<9; i++) {
for(int j = 0; j < 9; j++){
String appropriateNumber = convertSimple(grid2[i][j]);
button[i][j] = new JButton(appropriateNumber);
button[i][j].addActionListener(new sudokuListener());
myGrid.add(button[i][j]);
}
}
then to update :
buttons[row][column].setText("New Text");

Categories