Specify array length to call - java

I'll explain my problem with an example:
buttons[0][0].addActionListener(new ActionListener() {
In the code above I'm adding a listener to my button in the upper left corner. Now I was wondering if there's an option, so I can call the entire line, something like [0][0-3], so I can add the same action listener for all 4 of them (I know 0-3 will not work since it says that -3 isn't specified in the array).
I know I can do this by adding a listener to the buttons one by one, but I have to make an if statement that when all the buttons have been pressed for example, it returns something.

You can't do this in one call, the easiest way is to iterate over them:
ActionListener toAddToThoseButtons = new ActionListener() { /*...*/ };
for (int i=0; buttons[0].length; i++) {
buttons[0][i].addActionListener(toAddToThoseButtons);
}

Related

Hard coded buttons do not appear in design view, or in the running program

Whenever I choose to hard code an object (so far, I have sampled buttons, text fields and comboboxes), it does not appear on the associated form. Is there a separate piece of code that handles this, or can I use the following? Additionally, are layout bonds strictly necessary?
JButton startButton = new JButton("Start for loop ex");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0){
int start = 1;
int end = 5;
int answer = 0;
for (int i = start; i < end; i++){
answer = answer + i;
}
};
IDEOne showing the entirety of the code:
http://ideone.com/u7CuoG
I think you only created the button, but forgot to put it in the JFrame.
Assuming that this is a subclass of JFrame, you can do this to add the button to the frame:
this.add(startButton);
Also check if you have called setContentPane. If you have not, the button will fill up the whole frame.
It is only natural that dynamically added buttons don't appear in the design view because it would be very slow to compile and run your code every time you open the design view!
EDIT:
I ran the code you gave me and produced this frame. As you can see, the button is on the frame:

Swing - How to create a Jbutton that adds e.g Boats to a fleet

For my Project i have to be able to add/remove boats to a fleet.I would like to use a Jbutton for that. I have 10 buttons which 5 are boats and i want to add them to fleet. Code for 1 of 10 jbutton using addActionListener() the thing im trying to do is that if a press a boat button it will print out in a textarea one after another (like a receipt). i have the same code structer for all buttons my second question is-Is there a way of making the code a bit shorter.
button9.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
addBoat.setVisible(true);
button6.setVisible(true);
button7.setVisible(true);
button8.setVisible(true);
button9.setVisible(true);
button10.setVisible(true);
text.setText(john.getText());
text.validate();
okButton.setVisible(true);
}
});
What you did is probably the simplest way that I know of. The only way to make it slightly shorter would be to make an array that includes all of the buttons then make a for loop that does that for you. An example of setting up the array would be:
JButton[] boats = new JButton[5];
And then the for loop would be:
for(int n = 0; n < boats.length; n++){
boats[n].setVisible(true);
}
The only thing I left out is actually adding the JButtons to the array, but this should do it. In the future I would recommend using more helpful names for your buttons to make it easier for others to read your code.

Refresh JPanel in Java Swing

Let's suppose I've a list of String like this
List<String> button_names={"Button1","Button2","Button3","Button4"};
I've to insert JButtons with those texts in a JPanel so I do
for (int i=0; i<button_names.length; i++)
myJPanel.add(new JButton(button_name[i]));
My question is... If my model (in this case, my List button_names) changes for any reasons, how can I refresh my JPanel in order to show that change?
Should I do
myJPanel.removeAll()
and insert again my JButtons()? Thank you in adance
Yes removeAll and then reinserting new buttons is the easiest and generally the best way to go. Otherwise, you have to start figuring out which buttons have been removed, which have been added, and where in the list these new buttons are. Also, buttons in the list should change position I guess, so you'd have to cover that case to.
You can write a method like this that you could use in initial creation, and when you want to reload the list
void addButtonsToPanel(JPanel p) {
p.removeAll();
for (int i=0; i<button_names.length; i++)
myJPanel.add(new JButton(button_name[i]));
validate();
repaint();
}

Issues with JtextArea. JAVA

I have a GUI setup with with buttons on them and a JTextArea.
I also have an array of Strings with say size of 3.
What I want to do is use an action listener in a way that when the button called "next" is pressed, the JTextArea will then show the next cell in the array. The only problem is it displays the array at the same time. I need it to display the next cell when the button is hit
Can anyone help me with the code? Please and thank you.
final ActionListener m2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
arr = new String[3];
arr[0]= "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
arr[1]= "sssssssssssssssssssssss";
arr[2]= "xxxxxxxxxxxxxxxxxxxxx";
for (int i = 0; i<arr.length; i++){
text.append(arr[i]);
}
}
};
next.addActionListener(m2);
So the basic concept is. You need a index value to maintain the current index of the array that is being displayed.
From there, each time the user clicks next, you would increment the index and display the next value in the String
public void actionPerformed(ActionEvent e) {
currentIndex++;
// You need to decide what to do when we reach the end of the array...
String value = myStrings[currentIndex];
textArea.setText(value);
}
To create the button, use the JButton class. To respond to events, use the JButton#addActionListener() method. If you are having trouble, post what you have tried. Good luck!

Hold down a key while clicking on a JTextField in Java, how to get the key?

I have a JTextField represents a day in a week, such as "Friday", when I click on it, I want to have a choice such as "1st of month, 3rd of month or last of month", so I came up with two options :
<1> Hold down a number or letter, let's say "2" or "L", then click on "Friday" means 2nd (or last) Friday of the month, in this case, how to get the number while mouse clicks on the JTextField ?
<2> Right mouse click on the "Friday" JTextField, drop down a menu, with either buttons or checkboxes that let me choose, then close the menu and get the value.
My code look like this so far :
private final JTextField[] dayHeadings=new JTextField[]{new JTextField("Su"),
new JTextField("Mo"),
new JTextField("Tu"),
new JTextField("We"),
new JTextField("Th"),
new JTextField("Fr"),
new JTextField("Sa")};
......
for (int ii=0; ii < dayHeadings.length; ii++)
{
dayHeadings[ii].setEditable(false);
dayHeadings[ii].setFocusable(false);
dayHeadings[ii].addMouseListener(new MouseAdapter() { public void mouseClicked(final MouseEvent evt) { onHeadingClicked(evt); } });
add(dayHeadings[ii],new AbsoluteConstraints(x,38,X_Cell_Size+1,Y_Cell_Size+1));
}
......
void onHeadingClicked(final java.awt.event.MouseEvent evt)
{
final javax.swing.JTextField fld=(javax.swing.JTextField) evt.getSource();
...
}
How to do either of the above, are they doable in Java ?
getModifiers is actually that what I needed. a sample for the modifiers can be found
here
Option 1:
There is no way to do this in one step. You would need to add a KeyListner to track whenever a key is pressed and then save the character value. Then you would need to add a MouseListener to listener for mousePressed events. When the mousePressed event fires you would need to to check which character is saved and then do your processing. Therefore your listener would to implement both the KeyListener and MouseListener interfaces.
Option 2:
You need to add a mouse listener and listen for a right mouse click, then display a popup menu.
I think option 2 is more intuitive and more easily done. Its always easier to work with one hand then be forced to use two hands.
Another, lazier way to do it would be using getModifiers() on the mouseclick event. It shows which modifier keys (ctrl, alt, shift, etc), if any, were pressed during the mouse click. Using these buttons isn't as intuitive as a drop down menu or numbers in my opinion, but could work.
Read more here

Categories