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.
Related
I am having problems clearing contents of TextField in AWT using setText() method. Apparently, setText("") does not clear the contents of the TextField on pressing the 'Reset' button. Here's my program:
import java.awt.*;
import java.awt.event.*;
public class form extends Frame
{
Label lbl = new Label("Name:");
TextField tf = new TextField();
Button btn = new Button("Reset");
public form()
{
tf.setColumns(20);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
tf.setText(""); //Problem occurs here. This does not clear the contents of the text field on pressing the 'Reset' button.
}
});
add(lbl);
add(tf);
add(btn);
setLayout(new FlowLayout());
setSize(400,100);
setVisible(true);
setTitle("Form");
}
public static void main(String[] args)
{
new form();
}
}
Can someone please tell me where I went wrong or suggest an alternative? Thanks.
I see the problem as well using Java 8u11. I seem to remember this being filed as a known bug, but I can't seem to find it now.
A solution that works for me is to add an intermediate step:
public void actionPerformed(ActionEvent e) {
tf.setText(" ");
tf.setText("");
}
I'm not sure why this is necessary, I think it's a bug with the setText() function specifically ignoring empty Strings. If somebody finds the filed bug there would be more information there.
Add space in setText(" ") in function and see if it works. But there after there will be one space.
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);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
For some reason getText is not working for a text field.
Perhaps I am doing something wrong with this.
private JTextField txtTemp;
txtTemp = new JTextField();
txtTemp.setBounds(350, 57, 86, 20);
mainPanel.add(txtTemp);
txtTemp.setColumns(10);
String filePath = txtTemp.getText();
System.out.println("File path is" +filePath);
Nothing is being printed when something is typed in the text box.
I also did it with using an action listener. Load the program, and have the user add some text.
btnTest = new JButton("TEST");
btnTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String filePath = txtTemp.getText();
System.out.println("File path is" +filePath);
}
});
Still returns blank.
Any ideas?
"Nothing is being printed when something is typed in the text box."... "Still returns blank."
Sounds like you want something to happen whenever the text field is being type into. For that we would use a DocumentListener, which listener for changes in the underlying Document of the text field.
final JTextField field = new JTextField(20);
field.getDocument().addDocumentListener(new DocumentListener(){
#Override
public void insertUpdate(DocumentEvent e) { printText(); }
#Override
public void removeUpdate(DocumentEvent e) { printText(); }
#Override
public void changedUpdate(DocumentEvent e) { printText(); }
private void printText() {
System.out.println(field.getText());
}
});
See more explanation at How to Write a Document Listener
Aside, if you want something to happen when the use type enter, then add an ActionListener to the text field.
Your JTextField seems empty, as long as you dont give any input, however common mistakes may be:
is it editable?
txtTemp.setEditable(true);
any text added?
public void changeTxtField(String text)
{
txtTemp.setText(text);
System.out.println(text);
}
your code looks fine so
Don't also do it 'also in the Action Listener' , DO it only in the ActionListener ?
I have no idea where you are going wrong , are you expecting the output on the GUI screen ?if so you are mistaken , look into the terminal...
Here I just tried and it perfectly works , it prints the user input text after clicking the button onto the terminal ,
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class TestText{
public static void main(String[] args)
{
JFrame frame=new JFrame("TextFieldTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel=new JPanel();
JTextField txtTemp;
txtTemp = new JTextField();
txtTemp.setBounds(350, 57, 86, 20);
mainPanel.add(txtTemp);
txtTemp.setColumns(10);
JButton btnTest = new JButton("TEST");
btnTest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String filePath = txtTemp.getText();
System.out.println("File path is" +filePath);
}
});
frame.add(BorderLayout.SOUTH,btnTest);
frame.add(mainPanel);
frame.setSize(600,600);
frame.pack();
frame.setVisible(true);
}//main ends
}//class ends
I ended up figuring out this issue.
At the top if i declare and Instantiate the object it works.
private JTextField txtTemp = new JTextField();
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'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());
}
});