Two events on a button - java

How can I make more than one event on a button?
public JButton getNumero1() {
numero1Button = new JButton();
numero1Button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ic_images/bt_n1.png")));
ActionListener monitorador = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
entradaNumero1.setText(("1"));
entradaNumero1.setEnabled(false);
entradaNumero2.setText(("2"));
entradaNumero2.setEnabled(false);
}
};
numero1Button.addActionListener(monitorador);
return numero1Button;
}
I want to do with the first being a JTextField, and then another!
Thank you!

How can I make more than one event on a button?
Nothing is preventing you as you are allowed to:
Add more than one ActionListener to a JButton
Remove ActionListeners
Swap them (by adding and removing)...
Have listeners that do more than one thing...
Note that this is unclear:
I want to do with the first being a JTextField, and then another!

You can add any number of action listeners to a button
Java 7 way
public JButton getNumero1() {
numero1Button = new JButton();
numero1Button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ic_images/bt_n1.png")));
ActionListener monitorador1 = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
entradaNumero1.setText(("1"));
entradaNumero1.setEnabled(false);
}
};
numero1Button.addActionListener(monitorador1);
ActionListener monitorador2 = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
entradaNumero2.setText(("2"));
entradaNumero2.setEnabled(false);
}
};
numero1Button.addActionListener(monitorador2);
return numero1Button;
}
Java 8 way
public JButton getNumero1() {
numero1Button = new JButton();
numero1Button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ic_images/bt_n1.png")));
ActionListener monitorador1 = e -> {
entradaNumero1.setText(("1"));
entradaNumero1.setEnabled(false);
};
numero1Button.addActionListener(monitorador1);
ActionListener monitorador2 = e -> {
entradaNumero1.setText(("1"));
entradaNumero1.setEnabled(false);
};
numero1Button.addActionListener(monitorador2);
return numero1Button;
}

Related

How to create Botton that run clickevent on Another Botton in java?

I have this code
public class NewClass {
private void btn_NumberONEMouseClicked(java.awt.event.MouseEvent evt) {
}
private void btn_NumberTOWMouseClicked(java.awt.event.MouseEvent evt) {
}
I have 2 Bottons ( Btn number One & Btn Number Tow )
I Want The First Botton will do click Event on the secound Botton
How can I do it ??
You have to use the doClick() method of the JButton class
Here is the code :
JButton but = new JButton();
JButton but2 = new JButton();
but.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
but2.doClick();
}
});
but2.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("It works !");
}
});
I did not use your variables because I didn't understand your methods.
But this works perfectly.

Java how to assign id to button and retrieve them?

I'm getting stuck while building a forum like application which has a vote button.
I have vote up and vote down button for each content which are automatically generated. I want this button to only display the up and down arrow but not any text or label.. how can i find out which button is pressed?
Automated content..
ImageIcon upvote = new ImageIcon(getClass().getResource("vote_up.png"));
ImageIcon downvote = new ImageIcon(getClass().getResource("vote_down.png"));
JButton vote_up = new JButton(upvote);
JButton vote_down = new JButton(downvote);
vote_up.addActionListener(voting);
vote_down.addActionListener(voting);
Action voting = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e){
//What to do here to find out which button is pressed?
}
};
any help is appreciated.
public void a(){
int crt_cnt = 0;
for(ClassA temp : listofClassA)
{
b(crt_cnt);
crt_cnt++;
}
}
public void b(crt_cnt){
//draw button
}
As from above, I have multiple vote_up and vote_down button created by the b function, how can i differentiate which crt_cnt is the button from?
There are multiple ways you might achieve this
You could...
Simply use the source of the ActionEvent
Action voting = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e){
if (e.getSource() == vote_up) {
//...
} else if (...) {
//...
}
}
};
This might be okay if you have a reference to the original buttons
You could...
Assign a actionCommand to each button
JButton vote_up = new JButton(upvote);
vote_up.setActionCommand("vote.up");
JButton vote_down = new JButton(downvote);
vote_down .setActionCommand("vote.down");
//...
Action voting = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e){
if ("vote.up".equals(e.getActionCommand())) {
//...
} else if (...) {
//...
}
}
};
You could...
Take full advantage of the Action API and make indiviual, self contained actions for each button...
public class VoteUpAction extends AbstractAction {
public VoteUpAction() {
putValue(SMALL_ICON, new ImageIcon(getClass().getResource("vote_up.png")));
}
#Override
public void actionPerformed(ActionEvent e) {
// Specific action for up vote
}
}
Then you could simply use
JButton vote_up = new JButton(new VoteUpAction());
//...
Which will configure the button according to the properties of the Action and will trigger it's actionPerformed method when the button is triggered. This way, you know 100% what you should/need to do when the actionPerformed method is called, without any doubts.
Have a closer look at How to Use Actions for more details
You can detect by using the method getSource() of your EventAction
Action voting = new AbstractAction(){
#Override
public void actionPerformed(ActionEvent e){
if (e.getSource() == vote_up ) {
// vote up clicked
} else if (e.getSource() == vote_down){
// vote down clicked
}
}
};
hey thanks for all the help and assistance! I've finally got it! I solved it by
assigning a text on the button, +/- for vote up or down, followed by the content id which i required, then change the font size to 0
vote.setText("+"+thistopic.content.get(crt_cnt).get_id());
vote.setFont(heading.getFont().deriveFont(0.0f));
after that i could easily trace which button is pressed by comparing to the
actionEvent.getActionCommand()
which return the text on the button!
I would wrap the JButton similar to this:
JButton createMyButton(final JPanel panel, final String text,
final boolean upOrDown, final int gridx, final int gridy) {
final JButton button = new JButton();
button.setPreferredSize(new Dimension(80, 50));
final GridBagConstraints gbc = Factories.createGridBagConstraints(gridx,
gridy);
panel.add(button, gbc);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
myActionPerformed(text, upOrDown);
}
});
return button;
}
You could use an int instead of the text, if more convenient.

ActionListener in java performs action on the second click

I am programming my first complex application in Java, Swing. When I have added ActionListener to my JButton.
ActionListener changeButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e){
if(startButton.getText() == "Spustit") {
startButton.setText("STOP");
} else {
startButton.setText("Spustit");
}
}
}
I am adding ActionListener to the button itself
private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
startButton.addActionListener(changeButton);
}
Can you tell me where I coded ActionListener badly?
Thanks to all!
You have coded the ActionListener good enough to be working, at least, for the action listener itself. The problem is that you are adding the action listener after an event (your second sample), thus your action listener will get called the second time you will click it.
A solution is very simple:
JButton button = new JButton();
button.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//...
}
});
Now the action listener should activate on the first click if you directly add a new ActionListener to the button, not after an action is performed
Why are you adding the actionlistener in actionPerformed? I think you should do something like this:
public static void main(String[] args) {
final JButton startButton = new JButton("Spustit");
ActionListener changeButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (startButton.getText() == "Spustit") {
startButton.setText("STOP");
} else {
startButton.setText("Spustit");
}
}
};
startButton.addActionListener(changeButton);
// Add it to your panel where you want int
}

When adding class in DefaultListModel, did it save the value of toString or the entire class?

Newbie here.
When I added an element in the DefaultListModel, I used a class with an overriden toString.
Based on the sample code below, I want to display the selected item's ID when I click the button btnid.
The commands under displayID doesn't seem to work. Help please. Thanks!
class SomeClass {
JFrame f = new JFrame("Sample");
JScrollPane sp = new JScrollPane();
DefaultListModel dlm = new DefaultListModel();
JList lst = new JList(dlm);
public SomeClass() {
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnadd = new JButton("Add");
JButton btnid = new JButton("View ID");
Container p = f.getContentPane();
sp.getViewport().add(lst,null);
p.add(sp, BorderLayout.WEST);
p.add(btnadd, BorderLayout.EAST);
p.add(btnid, BorderLayout.SOUTH);
btnadd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dlm.addElement(new ElementDisplay(dlm.getSize(),"Element " + dlm.getSize()));
}
});
btnid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
displayID();
}
});
f.pack();
f.setVisible(true);
}
private void displayID() {
ElementDisplay ed;
ed = dlm.getElementAt(lst.getSelectedIndex());
System.out.println(ed.elementID);
}
public static void main(String args[]) {
SomeClass sc = new SomeClass();
}
class ElementDisplay {
public int elementID;
private String elementDescription;
public ElementDisplay(int pid, String pdesc) {
elementID=pid;
elementDescription=pdesc;
}
#Override
public String toString() {
return elementDescription;
}
}
}
Works fine for me. What makes you think it doesn't work? You need to actually have an item selected in the list for the button press to work, you will get ArrayIndexOutOfBoundException
Instead of depending on a button press, just add a listener to the JList. That way only when the item in the JList is selected, does it print. No need for the button and trying to avoid the ArrayIndexOutOfBoundException
lst.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting()) {
JList list = (JList)e.getSource();
DefaultListModel model = (DefaultListModel)list.getModel();
ElementDisplay ed = (ElementDisplay) model.getElementAt(lst.getSelectedIndex());
System.out.println(ed.elementID);
}
}
});
See How to Write Event Listeners where you will run into possible listeners you can use for different components. As GUIs are event driven, you should take time to learn most of them.

How can I find out which button was clicked?

I've got my buttons working right, and I'm a listener to each button like this:
for(int i = 0; i <= 25; ++i) {
buttons[i] = new Button(Character.toString(letters[i]));
buttons[i].addActionListener(actionListener);
panel1.add(buttons[i]);
}
Here as you can see the listener is called, and I want to find out which button I'm clicking. Is there a way to do that?
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getSource());
}
};
I need some way to find the button in the array.
try this
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand());
}
};
In order to get label, try this.
ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent) {
JButton button = (JButton)actionEvent.getSource();
String label = button.getLabel(); //Deprecated
String label2 = button.getText();
}
};
ActionEvent has a method getActionCommand() that will get a JButton's actionCommand String. This is usually it's text as well (for JButtons).
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
l1.setText("");//name of level what you want
t1.setText(null);//text field what you want
t2.setText(null);//text field what you want
}

Categories

Resources