How can I put Caret in JTextArea while setEditable is disabled?
A sample code when I need Caret to be visible:
public void run(){
JFrame frame = new JFrame();
JTextArea text = new JTextArea();
text.setEditable(false);
String line = "added line";
text.append(line);
text.setCaretPosition(text.getCaretPosition() + line.length());
frame.getContentPane().add(text);
frame.setSize(300,300);
frame.setVisible(true);
}
What I want to achieve is that, when the user types within TextArea, characters must not be displayed. Typed characters are redirected to OutputStream and appropriate InputStream is received which will be displayed within TextArea. This works fine, but Caret is hidden because of setEditable(false).
text.getCaret().setVisible(true) and/or text.getCaret().setSelectionVisible(true)
Well, I put here a code fragment which shows the caret but don't let edit the JTextArea. I hope it helps you. It's a little trick which plays with the focus of the text area, when focus is gained, the edition is disabled; but when it's losed, the edition it's possible. In this way, the user is unable to edit it but can see the caret.
public void run() {
JFrame frame = new JFrame();
final JTextArea text = new JTextArea();
text.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent fe) {
text.setEditable(true);
}
public void focusGained(FocusEvent fe) {
text.setEditable(false);
}
});
text.setEditable(true);
String line = "added line";
text.append(line);
text.setCaretPosition(text.getCaretPosition() + line.length());
frame.getContentPane().add(text);
frame.setSize(300,300);
frame.setVisible(true);
}
Notice that the user can move the caret, but he/she can't edit the text
I tried the solution originally proposed by StanislavL. However, other issues emerged. For example, after leaving the JTextArea and focusing back later, the caret would turn invisible again.
I suspect that caret was not implemented as most people would expect to behave. While I saw some authors proposing to re-implement the caret, I successfully achieved visible caret behavior with following small listener:
textArea.getCaret().setVisible(true);
textArea.getCaret().setSelectionVisible(true);
textArea.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
textArea.getCaret().setVisible(true);
textArea.getCaret().setSelectionVisible(true);
}
#Override
public void focusLost(FocusEvent e) {
textArea.getCaret().setSelectionVisible(true);
}
});
On example above, I decided to keep the selection visible even if one leaves the text area.
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.
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 want to make a java application, that will contain some text. I want some of these words to act like buttons. My idea is to put all the text in a text panel and the words that I want to act like buttons to be buttons. But i cant get a button to have the same style as the text. The button its always lower than the text from that line. It's possible to fix that ?
Ty.
Example:
John went to the shop.
"shop" is a button and can be clicked, and it looks exactly like the other words.
My problem:
I can't find how to make a JButton look like the other words.
You could just add a mouse listener to your JLabel with your text. That would respond to a mouse click action. You could also had a hover listener to change the border to give your user some indication that the text is clickable and remove the border when you are no longer hovering.
final JLabel lblNewLabel = new JLabel("Click Me!");
lblNewLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0)
{
System.out.println("Label Clicked!");
}
#Override
public void mouseEntered(MouseEvent e)
{
lblNewLabel.setBorder(BorderFactory.createEtchedBorder(1));
}
#Override
public void mouseExited(MouseEvent e)
{
lblNewLabel.setBorder(null);
}
});
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'm wondering if someone can help me out. I entered a character into a text area from a button, and want to use the string entered into the textarea to retrieve words from a list. Bear in mind, there could be numerous characters entered. Is it possible for a text area to detect when text has been entered and to action it?
You can add a DocumentListener to your JTextArea;
class YourClass {
...
public void attachTextAreaToPanel(JPanel panel) {
JTextArea textArea = new JTextArea();
textArea.getDocument().addDocumentListener(new MyDocumentListener());
panel.add(textArea);
}
}
class MyDocumentListener implements javax.swing.event.DocumentListener {
public void changedUpdate(javax.swing.event.DocumentEvent e) {
// text has been altered in the textarea
}
public void insertUpdate(javax.swing.event.DocumentEvent e) {
// text has been added to the textarea
}
public void removeUpdate(javax.swing.event.DocumentEvent e) {
// text has been removed from the textarea
}
}
Edit, this requires that you use Swing - and not AWT.
I assume you are refering to swing JTextArea ?
look at:
http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html
There is a part that is exactly what you are looking for.
Implements the TextListener for that textarea. Then use the conditions.
Otherwise implements ActionListener to your button. Then specify the action you want, while pressing your button.