I have to create a collection of JButtons depending of a size of a certain collection. How to create the List of JButtons :button1, button2, button3...dynamically to have something like
for (int i=0;i<collection.size();i++){
JButton button+i = new Button();
}
Thanks
Use a list of buttons (or even an array of buttons) :
List<JButton> listOfButtons = new ArrayList<JButton>(collection.size());
for (int i=0; i < collection.size(); i++) {
JButton button = new JButton();
listOfButtons.add(button);
}
Make a List<JButton> and each time through your loop add the new JButton to it.
Related
First off thanks for everyone who contributes. It's such a lifesaver. That said, here's my first ever post.
I've created a dynamic array of JButton objects and attached an ActionListener to the button.
public void printFound(ArrayList<Customer> found)
{
buttons = new ArrayList();
texts = new ArrayList();
for(Customer temp: found)
{
JButton btn = new JButton("Edit");
btn.addActionListener(new PushEdit());
btn.setPreferredSize(new Dimension(100, 40));
panel1.add(btn);
buttons.add(btn);
JTextArea text = new JTextArea(temp.toString(), 8, 80);
text.setLineWrap(true);
panel1.add(text);
texts.add(text);
}
}
When I click on an edit button, I want it to pass the index of "btn" in "buttons" to the ActionListener so that I can display the values in "temp" in another GUI. I figure I either need to pass temp directly or I need to pass both the index of "btn" as well as the index of "found".
Thanks!
as i can understand from your question you want to get the index of the jbutton that stored in buttons ArrayList to do some sort of things..
to do this you can use setActionCommand and getActionCommand methods to bind a String along with every jbutton that created and
so your code will be like this
public void printFound(ArrayList<Customer> found)
{
buttons = new ArrayList();
texts = new ArrayList();
Integer index=0;
for(Customer temp: found)
{
JButton btn = new JButton("Edit");
btn.setActionCommand(index.toString());
btn.addActionListener(new PushEdit());
btn.setPreferredSize(new Dimension(100, 40));
panel1.add(btn);
buttons.add(btn);
JTextArea text = new JTextArea(temp.toString(), 8, 80);
text.setLineWrap(true);
panel1.add(text);
texts.add(text);
index=index+1;
}
}
whenever you you want to get the index
System.out.print(btn.getActionCommand());
i have a multiple jradiobutton that is inside a for loop and i am trying to put listener on it and this is what i found:
Action listener for multiple radio buttons
Create two dimensional JRadioButton array like
JRadioButton[][] jRadioButtons = new JRadioButton[8][];
ButtonGroup bg = new ButtonGroup();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(8, 8));
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
JRadioButton btn = new JRadioButton();
btn.addActionListener(listener);
btn.setName("Btn[" + i + "," + j + "]");
bg.add(btn);
panel.add(btn);
// can be used for other operations
jRadioButtons[i][j] = btn;
}
}
Here is single ActionListener for all JRadioButtons
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton btn = (JRadioButton) e.getSource();
System.out.println("Selected Button = " + btn.getName());
}
};
i kinda understand it but i still have few clarifications:
what's the purpose of two dimensional jradiobutton? i mean i kinda see that it is to set a name for the jradiobuttons but as far as my understanding goes, it's only for display. yes to confirm that that is the jradiobutton you've selected but i don't get what's the purpose of it in putting actionlistener
is the two dimensional jradiobutton really that necessary?
can i just use the name of jradiobuttons
to do something like this:
if(NameOfJRadioButton.isSelected())
{
//some procedures
}
^(i can't seem to convert that into code :/)
if so, how can i do it? or do you have any other suggestions on how to put listener for multiple jradiobuttons? thank you for any of your suggestions :)
On your first and second point, the reason for the two dimensional array is unknown as it is not your code, but is not necessary at all for the use of JRadioButtons. However it is useful to have all your buttons in some type of array, whether it be an arraylist, or a buttonGroup (swing list for buttons) for checking things with the buttons when an action is called. e.g. on your 3rd point, this array list would allow you to iterate through and check which buttons have been selected and act accordingly.
The purpose for the action listener is for executing an action when the user clicks on a button. The most general use for this is making it so the user is only allowed to select a certain amount of JRadioButtons or to disable them once they have been selected. e.g. at a character selection menu.
I'm trying to make a simple calculator in Java using Swing, and I've created my buttons the following way:
//Our number keypad
public static JPanel numbers(){
//our panel to return
JPanel panel = new JPanel();
//Create and add 3x4 grid layout to panel
GridLayout gl = new GridLayout(3, 4);
panel.setLayout(gl);
//For creating and adding buttons to panel
for(int i = 0; i < 10; i++){
//Create a new button where the name is the value of i
String name = "" + i + "";
JButton button = new JButton(name);
//add action listener
button.addActionListener(handler);
//Add button to panel
panel.add(button);
}
return panel;
}
My question is how do I reference each specific button in my event handler? I can't think of a way to do this without having to manually create each button rather than using a loop.
Thanks.
In your listener, call event.getSource(), and that will return the button which has been pressed. Get the text of the button, and you have its number.
Or create a different instance of your handler for every button, and pass the value of the button (i) to the constructor of the handler. This last solution is cleaner, IMO, because it doesn't depend on the text of the button. If you replaced the text by an image, for example, the first technique wouldn't work anymore.
You can distinguish created buttons by adding the following inside handler:
String buttonText = ((JButton) e.getSource()).getText();
if (<text1>.equals(buttonText)){
//do the stuff
} else if (<text2>.equals(buttonText)){
//do the stuff
} else {
//do the stuff
}
Method #1: go through the child components of the parent JPanel (quite tedious, has to be rebuilt every time you modify the contents of that JPanel). Make sure they're JButtons by using an if . . instanceof clause.
Method #2: as you create them in that loop, add them to a List (or even better, a Map). I prefer a Map personally as it lets me customise the key for that specific JComponent
i.e.
HashMap<String, JComponent> buttonList = new HashMap<String, JComponent>();
for(. .) {
buttonList.put("nameForEachButton", button);
}
I recommend generating the button name based off of the loop counter. Either use your existing name value, or just set it to "button" + i;
Declare your buttons using an array.
JButton[] button = new JButton[9]; //outside the for loop
for (int i = 0; i < 10; i++) {
//put your code
button[i] = new JButton(name);
//your code
}
I have been working on a program and when I run it I get an error that says line 43 and 84 have a NullPointerException. This is the code. I have put comments where line 43 and 84 are. I am trying to make a word processor like Microsoft Word.
import javax.swing.*;
import java.awt.*;
public class Graphics {
// listing all the components
JFrame f1;
JPanel colorspanel;
JPanel sizepanel;
JPanel fontpanel;
JPanel mainpanel;
JTextField Maintextfield;
JLabel colorlabel;
JLabel sizelabel;
JLabel fontlabel;
JButton colorbuttons[];
JButton sizebuttons[];
JButton fontbuttons[];
Graphics() {
// making instances of panels
colorspanel = new JPanel();
sizepanel = new JPanel();
fontpanel = new JPanel();
mainpanel = new JPanel();
// setting the size of the panels
colorspanel.setSize(216, 144);
sizepanel.setSize(216, 144);
fontpanel.setSize(216, 144);
mainpanel.setSize(612, 756);
// making instances of button
colorbuttons = new JButton[9];
sizebuttons = new JButton[14];
fontbuttons = new JButton[9];
// setting content for buttons
// colorbuttons
colorbuttons[0].setBackground(Color.black);//line 43
colorbuttons[1].setBackground(Color.red);
colorbuttons[2].setBackground(Color.blue);
colorbuttons[3].setBackground(Color.yellow);
colorbuttons[4].setBackground(Color.green);
colorbuttons[5].setBackground(Color.gray);
colorbuttons[6].setBackground(Color.DARK_GRAY);
colorbuttons[7].setBackground(Color.ORANGE);
colorbuttons[8].setBackground(Color.pink);
colorbuttons[9].setBackground(Color.magenta);
// sizebuttons
sizebuttons[0].setText("8");
sizebuttons[1].setText("10");
sizebuttons[2].setText("12");
sizebuttons[3].setText("14");
sizebuttons[4].setText("16");
sizebuttons[5].setText("18");
sizebuttons[6].setText("20");
sizebuttons[7].setText("22");
sizebuttons[8].setText("24");
sizebuttons[9].setText("26");
sizebuttons[10].setText("28");
sizebuttons[11].setText("30");
sizebuttons[12].setText("32");
sizebuttons[13].setText("34");
sizebuttons[14].setText("36");
// fontbuttons
fontbuttons[0].setText("New Times Roman");
fontbuttons[1].setText("Blackadder ITC");
fontbuttons[2].setText("Andy");
fontbuttons[3].setText("Buxton Sketch");
fontbuttons[4].setText("Arial Black");
fontbuttons[5].setText("Comic Sans MS");
fontbuttons[6].setText("Old English Text MT");
fontbuttons[7].setText("SketchFlow Print");
fontbuttons[8].setText("Harlow Solid Italic");
fontbuttons[9].setText("Algerian");
f1.setVisible(true);
}
public static void main(String[] args){
Graphics graphics = new Graphics();//line 84
}
}
You allocate a new JButton array, but you don't allocate the elements therein:
colorbuttons = new JButton[9];
There should be a corresponding:
for (int i = 0; i < 9; i++) {
colorbuttons[i]= new JButton(...);
}
Otherwise, you're allocating space for the array of buttons, but never actually initializing each of the JButtons. Thus, colorbuttons[0] is null, and colorbuttons[0].blah() causes the NPE.
You created an array, but you never populated it with anything. You need to put buttons in the array. A NullPointerException means that you tried to reference something, but a null value was found, not an object with a method or property. For example
Object x = null;
x.toString(); // NPE
vs
Object x = new Object();
x.toString(); // we're in business
In your case, you created an array (over 2 lines; just create everything on one line IMHO), but never put the buttons in it. So when you call colorButtons[0].whatever you are trying to access whatever on the reference at index 0. But since you didn't put anything in the array, that reference is null.
Do something more like
JButton[] colorButtons = new JButton[9]; // initialize array
for (int i = 0; i < colorButtons.length; i++) {
JButton button = ... // initialize button each time thru
// do any common setup on the buttons
colorButtons[i] = button; // put the button in the array.
}
You didn't put anything into the colorbuttons array! Of-course it's null.
Here:
for(int i=0; i<colorbuttons.length; i++)
colorbuttons[i] = new JButton();
You JButton array is empty. You just declared it and nothing more.
Populate your array by adding buttons to it.
Something like this:
colorbuttons = new JButton[9];
for (int i = 0; i < 9; i++) {
//Your logic here
colobuttons[i] = new JButton();
}
I'm having a little trouble building the grids for a Battleship game for my Java class. So far, I can easily make a for loop to add JPanel or JButton objects to the JFrame. However, my issue is that I'll need to use those Panels or Buttons again when playing the game (such as clicking on a button to see if your opponent put a ship on that square, et cetera). Is there a simple way in Java to initialize reference variables for a LOT of objects? Or will I have to declare all of them individually?
You could try a multi dimensional array of JPanels (or any other object). Create an array with the same size as your grid. The line below initializes an array with 5 rows and 5 columns.
JPanel[][] battleField = new JPanel[5][5];
Use nested for loops to create the panels in the array.
for (int rowIndex = 0; rowIndex < battleField.length; rowIndex++)
{
for (int cellIndex = 0; cellIndex < battleField[rowIndex]; cellIndex++)
{
battleField[rowIndex][cellIndex] = new JPanel();
}
}
If you want to reference the battleField array later on you would just make it into a instance variable.
For a battleship game, you most likely want to retrieve the location of a button after is has been clicked. You can create a hashtable using your buttons as keys and the point it is located at as a value.
HashMap<JButton, Point> buttonMap = new HashMap<JButton, Point>();
for (int x = 0; x < COLUMNS; x++)
{
for (int y = 0; y < ROWS; y++)
{
JButton btn = new JButton();
btn.addActionListener(this);
buttonMap.put(btn, new Point(x, y));
//then add the button to your container
}
}
The in your actionPerformed method you can convert the button to the point it is located at like this.
JButton btn = (JButton)actionEvent.getSource();
Point p = buttonMake.get(btn);
Of course you will need to properly handle error conditions such as source not being a button or the button not being in the map...
You can always extend JButton to keep track of the info you need. A simple example:
class MyButton extends JButton{
private MyGameInfo mygameInfo;
private int buttonId;
//More fields....
//Getters/Setters
}
Then instead of creating and adding JButton objects to your layout, create MyButton objects(which is also a JButton so your layout will not be effected) and use its extra functionality for your game logic.
For reference, here is a related matching game that uses a grid of buttons. This related answer demonstrates the application of the Model–View–Controller pattern to a simple game.