Specific input from user - java

I started making my own little applet with buttons and labels and text fields, but I want to when you enter a certain thing in the text field it does something. I tried if(fieldTextField.equals(mystringhere)) { but it doesn't work. Could you post an example of what I want?

You have to use a KeyListener, so that you can listen to keyboard and check your text everytime the user types something in your field:
KeyListener kl = new KeyAdapter(){
public void keyTyped(KeyEvent evt)){
if(yourTextField.getText().equals(yourString){
//do something here
}
}
};
yourTextField.addKeyListener(kl);
Note that yourTextField must be an instance variable or a local final variable in order to be used in the KeyListener methods

Take a look at event listeners (http://docs.oracle.com/javase/tutorial/uiswing/events/intro.html). Also you shouldn't be comparing the TextField itself to the String, but it's text, using the getText() method.
EDIT: Better than the link above: http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html

Related

How to validate jTextfield within keypress

im trying to validate a jtextfield from the keypress and would like it to throw an error message in a jLabel. I am trying to do this with in the code below.
private void jTextField2KeyPressed(java.awt.event.KeyEvent evt) {
}
Can't comment, so i'll answer instead. If you are looking to validate the input of the user as he/she type, you might wanna have a look at javax.swing.text.DocumentFilter.
If you are simply looking to update a JLabel when the user types something, you should add a KeyboardListener to the JTextField. You have to be a bit careful with that tho, as swing doesn't guarantee the order in which listeners are called, meaning that the text may not have updated when the KeyboardListener is invoked.

How to add actionListener to each Button

It might be confusing for some to answer this but I will try to put my question in the best way. I am working with jdbc and gui. Basically I want to display (in buttons format) the particular data received from my sql database. I could get the data correctly and put it to my array of buttons as their names. In other words, I have an ArrayList of buttons with different names/texts received from my database. Thus i really need to make an arraylist of buttons since data are dynamically populated. My problem is, I am so confused of how am going to create an actionListener to each button. Everytime each button is clicked, it must show the values associated with its name. I don't know how am i supposed to pass at least the names of the buttons to my actionListener method (or action Event Handler). If you find it confusing, here is the code for my buttons.
todayTaskButton.add(new JButton(taskForToday.get(i)));
todayTaskButton.get(i).setPreferredSize(new Dimension(300,75));
todayTaskButton.get(i).setBackground(Color.GRAY);
todayTaskButton.get(i).setFont(new Font("Century Gothic",Font.PLAIN,30));
todayTaskButton.get(i).setForeground(Color.WHITE);
todayTaskButton.get(i).setFocusable(false);
Thank you so much
You don't need to pass the name of the button to the ActionListener. It is automatically detected. You just need to implement the method actionPerformed(ActionEvent) in you class.
Then add the listener to the button :
todayTaskButton.get(i).addActionListener(this);
In your actionPerformed method, you can do:
JButton b = (JButton) e.getSource();
String text = b.getText();
Honestly there are so many ways you might achieve this, the problem is picking the right one for you...
You could...
Create a anonymous class for each button, each time your create them
todayTaskButton.get(i).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...
}
});
While this can work, it can make the code really messy, you also still need a way to map the action back to the button in some way, which can be done using the actionCommand property or using the source property if you don't mind iterating through the list of available buttons
You could...
Create a purpose build class which implements ActionListener for each button, which possibly takes some kind of reference to the data
todayTaskButton.get(i).addActionListener(new TodayActionListener(taskForToday.get(i)));
This is a little more focused, as you don't really care about the button, as you have the "today" value for the listener, so all the normally repeated code could be isolated into a single class and you would simply pass in the "variable" element
You could...
Take full advantage of the Action API and make individual, self contained actions for each button...
public class TaskAction extends AbstractAction {
public TodayAction(String task) {
putValue(NAME, task);
}
#Override
public void actionPerformed(ActionEvent e) {
// Specific action for task
}
}
Then you could simply use
todayTaskButton.add(new JButton(new TaskAction(taskForToday.get(i))));
While this is similar to the previous option, the Action is a self contained unit of work and has a number of properties which the JButton can use to configure it self. The Action can also be re-used for JMenuItems and key bindings, making it incredibly flexible
Have a closer look at How to Use Actions for more details

Is JTextArea the right class for my purpose?

I want to create a text area where the user inputs some text, presses enter and that text is sent to a class that does something with it ( changes the order of the words for example ), then the editted text is displayed on the next line in the text area.
Furthermore, if the user writes something on the line after the first editted text and again presses enter - only that last line is sent to the editting class. The user should be able to edit all the lines as well, if he wants to. Something like the text area in Wolfram Mathematica, if people know it.
I am new to Java and I have no idea whether I have to use JTextArea and design somekind of a class myself that will do this or there is already something that could help me.
With a JTextArea this is possible, but I would create a new Class, wich extends JTextArea.
Yes, you can do this with JTextArea. I wouldn't extend it as previously suggested, but I would add a KeyListener and implement the specific methods you're interested in. For instance, you're interested in when Enter is typed; so you may do something like this:
public void keyTyped(KeyEvent e) {
//look for the ENTER key and perform specific processing
int keyCode = e.getKeyCode();
switch(keyCode) {
case KeyEvent.VK_ENTER:
//do stuff
break;
}
}

Let ActionListener listen for change in JTextField instead of only enter?

So as you may know, if you have a text field and you add an ActionListener to it, it will only listen to the keypress of the enter button. However, I want to let my ActionListener listen to changes in text of the . So basically I've got this:
public static JPanel mainPanel() {
JPanel mainp = new JPanel();
JTextArea areap = new JTextArea("Some text in the textarea");
JTextField fieldp = new JTextField("Edit this");
areap.setEditable(false);
fieldp.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(//change in textfield, for instance a letterpress or space bar)
{
//Do this
}
}
});
mainp.add(areap);
mainp.add(fieldp);
return mainp;
}
Any way I can listen to changes in text (like documented in the actionPerformed event)?
From an answer by #JRL
Use the underlying document:
myTextField.getDocument().addDocumentListener();
Yeah, but what is a document listener and how do you use it? You're not really answering the question.
I have a JTextField in my app's user interface. When the user makes any change to it, I want a nearby JCheckBox to be checked. The purpose is to tell the app to USE the value that was entered. Users often enter a value there but if they don't explicitly tell the app to use it then the app continues to ignore it. Instead of "training" users I'm supposed to follow the principle of least astonishment and automatically check the "Use this value" box.
But how do I listen for a change? Can't you guys just tell me the easy way, instead of "educating me" about document listeners?
Documents are the mechanisms java swing uses to store the text inside of a JTextField. DocumentListeners are objects that implement the DocumentListener interface and thus make it possible for you to list to changes in the document, i.e. changes in the text of the JTextField.
To use the document and documentlistener capabilities, as suggested above extend your class (probably but not necessarily a JFrame) so that it implements the DocumentListener interface. Implement all the methods for the interface (most likely your java ide can do that semi-automatically for you. FYI, the DocumentListener interface has three methods, one for inserting characters (into the text field), one for removing characters, and one for changing attributes. You are going to want to implement the first two as they are called when characters are added (the first one) or deleted (the second one). To get the changed text, you can either ask the document for the text, or more simply call myTextField.getText().
C'est tout!
Phil Troy

2 input fields displaying the same thing

Bit of a strange one.
I want to have a JTextField, in which the user will type a string. While typing, however, I'd like that text to automatically print to another JTextField in real time.
I'm not sure if this is possible because I can't recall seeing any application do it.
Anyone even seen anything like this before?
Actually, now that I open my eyes a bit, I see that stackoverflow does it.
Are there any known ways of implementing in Java?
You might be able to give the fields the same document instance. For the document you could use one of the classes that swing provides or you could extend your own. The document is the model of the text field.
Alternatively you could use listeners to do the updating. There are many things you can listen and it depends on your needs what suits best. You can listen the document, you can listen keyboard and mouse events, you can listen for action events. (Action events happen in this kind of fields when pressing enter or focus is lost.)
The "same document" approach is the way to go.
Here's some sample code in Groovy (translation to Java is left as an exercise to the reader):
import javax.swing.*
import java.awt.FlowLayout
f = new JFrame("foo")
t1 = new JTextField(10)
t2 = new JTextField(10)
t2.document = t1.document
f.contentPane.layout=new FlowLayout()
f.contentPane.add(t1)
f.contentPane.add(t2)
f.pack()
f.show()
Add an ActionListener, as this will respond for any action changing the text (not just key presses, but also mouse-driven cut-paste). Code not tested...
// changing textField1 updates textField2
textField1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
textField2.setText(textField1.getText());
}
});
You could add an action listener for the jTextField's key released action.
eg:
jTextField1.addKeyListener(new java.awt.event.KeyAdapter()
{
public void keyReleased(java.awt.event.KeyEvent evt)
{
jTextField1KeyReleased(evt);
}
});
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt)
{
jTextField2.setText(jTextField1.getText());
}
You could use the KeyListener interface, and on each keyTyped event you copy the text to the "duplicate" field.

Categories