Is there any way to get the source of an event? I know event.getSource() however, is there any way to convert it into a string?
For example, if the source is a button, button1, is there anyway to assign the value button1 to a string variable? (I'm dealing with a lot of buttons and so, I can't write if statements)
For the sake of clarity:
The getSource() method returns the object from which the Event initially occurred. You could use this to get some sort of property from the element, like the text inside a label or the name of a button.
These are Strings, but if you chose to go this route, I would make sure you pick something that is uniform across all components that will be calling that ActionListerner.
This is where getActionCommand() might come in handy. You can set unique 'identifiers' when components are created, and the access them later.
JButton button = new JButton("Button");
button.setActionCommand("1");
JButton button = new JButton("Button");
button.setActionCommand("2");
Then you can compare these later using any method you like, or you could do something fancy, like this (because you said you didn't want to use if-else statements):
String command = e.getActionCommand();
int i = Integer.parseInt(command);
switch (i) {
case 1: // do something
break;
}
According to the Java docs:
Returns the command string associated with this action. This string allows a "modal" component to specify one of several commands, depending on its state. For example, a single button might toggle between "show details" and "hide details". The source object and the event would be the same in each case, but the command string would identify the intended action.
Keep in mind that I think this is best approach only if you are using one ActionListerner for lots of components. As another answer pointed out, you could just make unique ActionListeners per each button.
Hope this helps you!
You can pass anything you want to an action listener through the constructor, as DaaaahWhoosh stated in his comment.
package com.ggl.fse;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonActionListener implements ActionListener {
private String buttonText;
public ButtonActionListener(String buttonText) {
this.buttonText = buttonText;
}
#Override
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
}
}
The buttonText String will be available in the actionPerformed method.
You can use a specific ActionListener for each JButton. Try this code:
private static String text;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(200, 200, 200, 200);
frame.setLayout(new BorderLayout());
JButton button1 = new JButton("Button 1");
button1.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
text = button1.getText();
JOptionPane.showMessageDialog(null, "Text is: " + text);
}
});
JButton button2 = new JButton("Button 2");
button2.addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
text = button2.getText();
JOptionPane.showMessageDialog(null, "Text is: " + text);
}
});
frame.add(button1, BorderLayout.NORTH);
frame.add(button2, BorderLayout.SOUTH);
frame.setVisible(true);
}
Related
Okay, I've been searching how to do an auto prediction textfield for days now, and yes I found some solutions but they are completely hard to understand to be honest, and totally confusing since I'm new to Java/GUI. It would have been much easier if I had to click a button to do it, but I cant get how the program will perform such action whenever "a letter gets written". I've made a simple textfield and a button, whenever the button is clicked, the string in the textfield gets added in an arraylist, then prints the whole arraylist in another textfield(Just a simple example to test the auto prediction)
public class Phonebook {
public static ArrayList<String> names = new ArrayList<String>();
public static void main(String[] args) {
JFrame myForm = new JFrame("Phonebook");
myForm.setSize(555, 500);
myForm.setLocation(0, 0);
JButton button = new JButton("Add");
button.setSize(100, 50);
button.setLocation(450, 40);
myForm.add(button);
JTextField t = new JTextField();
t.setSize(200, 60);
t.setLocation(10, 40);
myForm.add(t);
JTextField ttt = new JTextField();
ttt.setSize(500, 300);
ttt.setLocation(10, 100);
ttt.setEditable(false);
myForm.add(ttt);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
names.add(t.getText());
String str = "";
for(int i=0; i<names.size(); i++)
str + =names.get(i) + "\n";
ttt.setText(str);
}
});
myForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myForm.setLayout(null);
myForm.setVisible(true);
}
}
So I want the big textfield to auto complete the small textfield, so if I type "M", it shows only the names in the arraylist that start with an "M", the code for finding the names that start with an "M" would be easy, but making it "Automatic" sounds very difficult to me. If anyone could help me with my code instead of sending me a new whole confusing code, I would really appreciate that. Thank you.
Edit: Or I just want the code that somehow checks if a letter is written, so (if a letter gets written in the textfield), system.out.print("A");
You could try attaching a Document Listener to the text box:
textField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
// search the prediction data for the current contents
// of the text field
}
public void removeUpdate(DocumentEvent e) {
// do stuff
}
public void changedUpdate(DocumentEvent e) {
//Plain text components do not fire these events
}
});
You can then use either the insertUpdate or removeUpdate functions to get a hook into the point when text is changed, access the textFields values and put your auto-complete functionality in there.
I created this little test program. It has 2 buttons and 2 labels. I want to know how I can use 2 buttons. So when I press button-1 then I change the text for text-1 and when I press button-2 then I change text for text-2. I just wanna get an idea of how I can use multiple buttons.
My code:
JLabel text1, text2;
JButton button1, button2;
public Game(String title) {
super(title);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(new FlowLayout());
addComponents();
setSize(250, 250);
setResizable(false);
}
public void addComponents() {
text1 = new JLabel();
getContentPane().add(text1, text2);
text2 = new JLabel();
getContentPane().add(text2);
button1 = new JButton("Button");
getContentPane().add(button1);
button1.addActionListener(this);
button2 = new JButton("Button 2");
getContentPane().add(button2);
button2.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
}
I'm new to programming, so I would also like if someone could write some comments for the code. Just so I get an idea on how the code for multiple buttons work.
In your actionPerformed method you can get the source of the action
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1){
//Do Something
}else if(e.getSource() == button2){
//Do Something Else
}
There are various approaches to add listeners to buttons, here just a couple:
Inner
If you don't have to do much actions in each button you can add inner listener in each button
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// DO STUFF
}
});
Common Listener
If you have more than 2 buttons (i guess your app will be bigger) you can use your actionPerformed(ActionEvent e) and get source of the action
#Override
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
if(source.equals(button1)){
// DO STUFF
}
}
Use actionCommand to clarify
To clarify this approach I would reccommend to use JButton.setActionCommand(stringCommand) so after you can use a switch:
Declaring buttons:
button1.setActionCommand("command1");
button2.setActionCommand("command2");
In ActionListener::actionPerformed()
public void actionPerformed(ActionEvent e) {
String command = ((JButton) e.getSource()).getActionCommand();
switch (command) {
case "command1":
// DO STUFF FOR BUTTON 1
break;
case "command2":
// DO STUFF FOR BUTTON 2
break;
}
}
Using Java 8, its it much more concise to add ActionListeners:
button.addActionListener(ae -> System.out.println("foo"));
Using multiple statements:
button.addActionListener(ae -> {
System.out.println("foo");
System.out.println("bar");
});
You should not use setVisible(true) before the components are added.
There are a few ways to deal with more elements in an ActionEvent:
e.getSource() returns the object on which the event occurred. So, if button1 was pressed, e.getSource() will be the same as button1 (and e.getSource()==button1 will thus be true)
You can use separate classes for each ActionEvent. If you would add the ActionListener "Button1ActionEvent" [button1.addActionListener(new Button1ActionEvent());] you have to create this class, let it implement ActionListener and add the method actionPerformed as you had in your main class. Also, you can create a listener inside of the addActionListener-method [button1.addActionListener(new ActionListener() { // actionPerformed-method here });]
I've just taken up playing with GUIs, and I'm experimenting with getting text input from the user, and assigning it to a variable for later use.
Easy, I thought. Wrong, I was.
I wanted my frame to look something like:
public class firstFrame extends JFrame {
JTextField f1 = new JTextField();
String text;
public firstFrame(String title) {
super(title);
setLayout(new BorderLayout());
Container c = getContentPane();
c.add(f1);
text = f1.getText();
System.out.println(text);
}
}
Where the variable text would get whatever text the user typed in, then print it out to the console. Simple.
I've got a feeling I'm missing something pretty fundamental here, and would appreciate it if anyone could fill me in on what that something is.
The variable won't be updated until an event occurs on the component. For this a DocumentListener or ActionListener can be used
f1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = f1.getText();
...
}
});
getText() only get the text that is in the JTextArea at the time it is called.
You are calling it in the constructor. So when you instantiate new firstFrame, there is no initiital text.
One thing to keep in mind is that GUIs are event driven, meaning you need an event handler to capture and process events.
One option is to add an ActionListener to the JTextField so when you press Enter after entering text, the text will print.
f1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String text = f1.getText();
System.out.println(text);
}
});
See more at how to Create GUI with Swing and Writing Event Listeners
I have a program that, put in short, advances upon the pressing of a button. During certain execution phases the button is temporarily deactivated to prevent it from firing in code at the wrong point in time. I have now created some Key Bindings to act as shortcuts for the pressing of the buttons, but need to disable them during the same aforementioned times, or else they will cause my array to be trashed and wiped before I even use it.
Any tips, methods, or Java methods I can use to [very] easily but a hold via disablement?
Have the bound key press the JButton with doClick(). Then when the button needs to be deactivated, call setEnabled(false) on the button.
As an aside, I suppose your button and key binding could share the same action, but I don't know if calling setEnabled(false) on the Action will prevent the key from running the Action's actionPerformed method. Time to test.... Be right back...
Edit: yep you can just have the JButton and the bound key share the same Action that is enabled/disabled:
import java.awt.event.*;
import javax.swing.*;
public class TestBoundAbstractActions {
public static void main(String[] args) {
final MyAction myAction = new MyAction();
final JButton actionButton = new JButton(myAction);
JRadioButton enableRadioButton = new JRadioButton("Enabled", true);
enableRadioButton.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
myAction.setEnabled(e.getStateChange() == ItemEvent.SELECTED);
}
});
JPanel panel = new JPanel();
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
String mKey = "m key";
panel.getInputMap(condition).put(KeyStroke.getKeyStroke(KeyEvent.VK_M, 0), mKey);
panel.getActionMap().put(mKey, myAction);
panel.add(new JLabel("Press \"m\" to activate key-bound action"));
panel.add(actionButton);
panel.add(enableRadioButton);
JOptionPane.showMessageDialog(null, panel);
}
}
class MyAction extends AbstractAction {
public MyAction() {
super("My Action");
putValue(MNEMONIC_KEY, KeyEvent.VK_M);
}
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("boo!");
}
}
I've got an array that creates buttons from A-Z, but I want to use it in a
Method where it returns the button pressed.
this is my original code for the buttons:
String b[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton(b[i]);
buttons[i].setSize(80, 80);
buttons[i].setActionCommand(b[i]);
buttons[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
JOptionPane.showMessageDialog(null, "You have clicked: "+choice);
}
});
panel.add(buttons[i]);
}
I wasn't sure exactly what you question was, so I have a few answers:
If you want to pull the button creation into a method - see the getButton method in the example
If you want to access the actual button when it's clicked, you can do that by using the ActionEvent.getSource() method (not shown) or by marking the button as final during declaration (shown in example). From there you can do anything you want with the button.
If you question is "How can I create a method which takes in a array of letters and returns to me the last clicked button", you should modify you question to explicitly say that. I didn't answer that here because unless you have a very special situation, it's probably not a good approach to the problem you're working on. You could explain why you need to do that, and we can suggest a better alternative.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TempProject extends Box{
/** Label to update with currently pressed keys */
JLabel output = new JLabel();
public TempProject(){
super(BoxLayout.Y_AXIS);
for(char i = 'A'; i <= 'Z'; i++){
String buttonText = new Character(i).toString();
JButton button = getButton(buttonText);
add(button);
}
}
public JButton getButton(final String text){
final JButton button = new JButton(text);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You have clicked: "+text);
//If you want to do something with the button:
button.setText("Clicked"); // (can access button because it's marked as final)
}
});
return button;
}
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setContentPane(new TempProject());
frame.pack();
frame.setVisible(true);
new TempProject();
}
});
}
}
ActionListener can return (every Listeners in Swing) Object that representing JButton
from this JButton you can to determine, getActionCommand() or getText()
I'm not sure what exactly you want, but what about storing the keys in a queue (e.g. a Deque<String>) and any method that needs to poll the buttons that have been pressed queries that queue. This way you would also get the order of button presses.
Alternatively, you could register other action listeners on each button (or a central one that dispatches the events) that receive the events in the moment they are fired. I'd probably prefer this approach, but it depends on your exact requirements.
try change in Action listener to this
JOptionPane.showMessageDialog(null, "You have clicked: "+((JButton)e.getSource()).getText());
1. First when you will be creating the button, please set the text on them from A to Z.
2. Now when your GUI is all ready, and you click the button, extract the text on the button, and then display the message that you have clicked this button.
Eg:
I am showing you, how you gonna extract the name of the button pressed, i am using the getText() method
butt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, "You have clicked: "+butt.getText());
}
});