Apply common code to group of jbuttons - java

Is it possible to apply a common code to multiple jbuttons in a frame on click of any jbutton.
Its like when I click, say jbutton80, then:
from jbutton1 to jbutton75
{
// common code that applies to all jbutton in loop
}
I am making quiz app in java and have around 70-80 buttons in jframe. Each button corresponds to a question. Questions are divided in sections.
So I want:
//if user selects(or clicks on jbutton) section a setvisible(true) from jbutton1 to jbutton20 and setvisible(false) from jbutton21 to jbutton 80.
Sorry, if this question has been asked before. I tried to search any relevant post but couldn't find one.

Did you try making an action listener
ActionListener l = new ActionListener() { /* code here */ };
And then adding the same one to all of the JButtons?
for (JButton b : buttons) {
b.addActionListener(l);
}

Related

Which button was clicked in Java?

I'm working (failing pretty bad so far tbh) on a battleship game for my high school Java programming class. So far I have the game board for both the computer and the player and I have generated the ships for the computer and made sure the player can sink them. Both of the boards have a grid layout, and each of them is assigned to a 2-D array for both the player and the computer and is part of the specific Grid Layout (to be honest I don't really understand a lot of the code because it was supplied by our teacher, so I can't really tell which parts are relevant and which aren't - which is also why I am not posting any of my code).
What I want to do now is let the Player place their ships by letting them pick a starting place by clicking on the board.
inside of a for loop
1: a button in buttonsPlayer is clicked
2: when a button is clicked, the two coordinates are calculated and stored as x, y coordinates
3: a ship is generated with the starting coordinates of x, y
I know how to generate a ship with random x and y starting coordinates as I have done that before. Is there a way to get a button's number in an array after clicking on a button?
(I did read through like 5 other threads on here that seemed to ask the same question, but I don't really get any of the answers)
You could create a class that extends JButton and adds more functionality to a JButton like so:
public class BoardPiece extends JButton{
private int x,y;
//rest of class including getters and setters
}
This will bring all the functionality of JButton along with it and you can add in essentially meta-data about each square.
Then in your event listener you would be able to just call .getX() and .getY() like so:
boardPiece.addActionListener((e)->{
BoardPiece clicked = (BoardPiece)e.getSource();
int x = clicked.getX();
// and so on
});
A JButton has an 'action command' which allows you to put information in it to distinquish it from other buttons.
using
JButton.setActionCommand
JButton.getActionCommand
So if you encode the coordinates of that button in that string, in your actionListener you can
JButton b = (JButton) eventListener.getSource();
and
String cmd = b.getActionCommand();
and then process that cmd string to figure out where on the board you are.
You can give a JButton an ActionCommand, e.g.
JButton button1 = new JButton("Button 1");
button1.setActionCommand("Button1id");`
Then if you implement an ActionListener to listen for the buttonpress, you can write code like
#Override
public void actionPerformed(ActionEvent ae) {
String buttonid = ae.getActionCommand();
}
By checking the value of buttonid, you will know which button was pressed.

Can't switch between tabs having ToolTipText assigned (JTabbedPane)

I have a JFrame extended class that implements a multi-tab chat. Every tab is a chat with someone or with a group of people. What I have implemented works fine, except when I assign a ToolTipText to the label of a tab. In this case I can't click anymore (and select) the tab that has a ToolTipText assigned. The others work fine.
Graphical example:
As you can see the tabs are properly being added, and the first two tabs ("Gruppo prova" and "Gruppo test") have a ToolTipText, the other two don't. I can switch between the last two, but I can't do the same with the first two. I thought that the icon next to the label could be a problem, but I removed it and still doesn't work. However I can still click all the 'X' (close) buttons (working properly).
This is a piece of the code I used to add a tab:
// Some stuff...
JChat chat = new JChat(gui.chatClient, email, name, group);
jTabbedPane.add(email, chat); // I instantiated this before
int index = jTabbedPane.indexOfTab(email);
JPanel pnlTab = new JPanel(new GridBagLayout());
pnlTab.setOpaque(false);
// Core function
JLabel lblTitle;
if (group == 1) {
// If it's a group and not a single chat I assign a name, an icon and a ToolTipText to the tab
lblTitle = new JLabel(name, icon, JLabel.LEFT);
lblTitle.setToolTipText(membersList.toString());
} else {
// otherwise I only assign a name to the tab
lblTitle = new JLabel(name);
}
jTabbedPane.setTabComponentAt(index, pnlTab);
// This applies the 'X' (close) button next to the tab name
CloseButton btnClose = new CloseButton(this, jTabbedPane, tabs, email);
lblTitle.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
pnlTab.add(lblTitle);
pnlTab.add(btnClose);
Is this a Swing bug or am I doing something wrong?
you can use :
void setToolTipTextAt(int, String) to set tool-tip text to specific tab.
void setIconAt(int index, Icon icon) to set the icon to specific tab.
No need to use JLabel for setting tool-tip text or icon.
The above solution, however doesn't however answer your question:
except when I assign a ToolTipText to the label of a tab. In this
case I can't click anymore (and select) the tab that has a ToolTipText
assigned
The only reason i am suspecting:
JLabel doesn't register to any mouse listener by default. When no mouse listener is set to JLabel any mouse clicked event will go through to the UI objects underneath: in this case the JTabbedPane. But when we are setting tool-tip text using setToolTipText(text), the ToolTipManger adds a mouse listener to this JLabel, which will continue to consume the mouse click event.
Check the following code snippets demonstrating the issue and providing a work around setSelectedIndex function:
JLabel label = new JLabel("a Label");
System.out.println(label.getMouseListeners().length); // length is printed as 0
label.setToolTipText("Danger: setting tool tip will consume mouse event");
System.out.println(label.getMouseListeners().length); // length is printed as 1
jTabbedPane1.setTabComponentAt(0, label);
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int index = jTabbedPane1.indexOfTabComponent((Component)e.getSource());
jTabbedPane1.setSelectedIndex(index);
}
});

How do I use requestFocus in a Java JFrame GUI?

I am given an assignment but I am totally new to Java (I have been programming in C++ and Python for two years).
So we are doing GUI and basically we extended JFrame and added a couple fields.
Say we have a field named "Text 1" and "Text 2". When user presses enter with the cursor in Text 1, move the focus to Text 2. I tried to add
private JTextField textfield1() {
textfield1 = new JTextField();
textfield1.setPreferredSize(new Dimension(200, 20));
textfield1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
textfield1text = textfield1.getText().trim();
textfield1.setText(textfield1text);
System.out.println(textfield1text);
textfield1.requestFocus();
}
});
return textfield1;
}
But that doesn't work at all.
I noticed that requestFocus is not recommended, and instead one should use requestFocusWindows. But I tried that too. Upon some readings it seems like I have to do keyboard action and listener? But my teacher said it only requires 1 line...
Well, you have textfield1.requestFocus(), but your description would imply you need textfield2.requestFocus(). (that's 2).
Another option might be to use:
textField1.transferFocus();
This way you don't need to know the name of the next component on the form.

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

Java GUI repaint() problem?

I have a JFrame. This JFrame contains a JButton. I click the JButton and 10 JTextFields are created.
the problem:
I cannot see them until "I force a repaint()" by resizing the window. Only then do I see the JTextFields created.
CODE:
JPanel points = new JPanel();
//Creating the JTextFields:
for (int i=0; i<10; i++) {
JTextField textField = new JTextField();
points.add(textField);
}
repaint();
this.repaint();
super.repaint();
points.repaint();
THANK YOU - after the for loop, I just called points.validate() and it worked...
Container.add API docs sayeth:
Note: If a component has been added to
a container that has been displayed,
validate must be called on that
container to display the new
component. If multiple components are
being added, you can improve
efficiency by calling validate only
once, after all the components have
been added.
It's obscure and not very clever, but it's the rules. It may be better to call JComponent.revalidate

Categories