Java action performed when text is entered into a textarea - java

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.

Related

Reading last character entered from JTextArea [duplicate]

This question already has an answer here:
Java - JTextField - Call function when user press "space bar"
(1 answer)
Closed 8 years ago.
I am making a simple text editor in Java so that I can write programs. I am stuck on making an ActionListener that is activated whenever a space is entered.
So, when you are typing into the text area and you press space, it will read the last word you typed.
Here are the essential parts of my code.
I have made an action listener and all of the other stuff, now I just need to make it read spaces.
JTextArea textarea = new JTextArea("#ECHO off" + "\n");
Font textareaFont = new Font("Arial", Font.BOLD, 15);
action event = new action();
textarea.setFont(textareaFont);
textarea.setForeground(Color.BLUE);
textarea.setLineWrap(true);
textframe.getContentPane().add(new JScrollPane(textarea));
textframe.setSize(525,715);
textframe.setLocationRelativeTo(null);
textframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textframe.setVisible(true);
}
private class action implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
Sorry if I am not being clear.
I think you would want a KeyListener, not an ActionListener.
Perhaps something like this:
textarea.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
//do your stuff here
}
}
}
You cannot do this job with an ActionListener because Swing text components do not fire ActionEvents in response to (most) keystrokes. Consult the key binding docs for information about how to achieve what you're after, but perhaps a refresher on Swing overall would be in order.

JTextField's getText() to printable variable

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

How to fix this ActionListener to pass back the String to the widget

I am really new in Java, and just practising ActionListeners. As the part of the application I work on, I will have a JTextField that lets the user to search a name, and then a JTextArea to show the result of the search. I have a api for searching and fining the the names, only problem is to connect the widgets to the methods and action listener file.
Here is some parts of the code:
Widget File:
//Text Field
JTextField searchbox = new JTextField();
leftSide.add(searchbox, cnt);
String userText = searchbox.getText();
ActionListener sendsText = new SearchListener(search box);
searchbox.addActionListener(sendsText);
//TextArea
JTextArea stationList = new JTextArea(12, 0);
leftSide.add(stationList, cnt);
String entered = userText;
stationList.append(entered);
SearchListener:
public class SearchListener implements ActionListener {
private JTextField searchbox;
private JTextArea stationList;
public SearchListener(JTextField search box) {
this.searchbox = searchbox;
}
public void ListF(JTextArea stationList){
this.stationList = stationList;
public void actionPerformed(ActionEvent event) {
XXXX<NAMES> stations = HHHH.SimilarNames(searchbox.getText());
for (NAMES station : stations) {
//System.out.println(station);
*Problem*> String result = (searchbox.getText());
*Problem*> stationList.append(result);
}
So in this program, the TextFiels is connected and the ActionListener working, but it prints out the list on Similar names in the CMD, (I commented it here). But I want it to send the list back to the Text Area in the API.(Widget File). So I am not sure my ActionListener method at the top of the SearchListener is right. Also the Problem> in the code is where I tired to pass the search result to the text field, which doesnt work.
So anyone know how to fix it?
Thank is advance.
I think you may be twisting a few things around, but perhaps this is what you're trying to accomplish:
A search field who's value determines what the text area is populated with.
If this is the case, then a few things have to change. First, only code within the ActionListener will be axecuted upon UI events, so there is no reason to call getText() on any of the UI elements during initialization.
Second, adding a button to this UI greatly simplifies the logic here. If attaching the listener to the search box, issues begin to arise such as "when do I know the user is done entering text?" and "How do I handle partial text?", however using a "Search" button puts this logic in the hands of a user.
Once the "Search" button is clicked, the action event from the listener that is attached to the button will trigger, and the stationListArea will be populated with the results of similarNames(<text from search box>).
Note that though what is shown below is not the cleanest way to perform this task (which would involve fields and anonymous inner classes), it is straightforward and easy to understand.
Widget (not sure what cnt was, so I omitted in in sample code below)
//Create the search text box
JTextField searchBox = new JTextField();
leftSide.add(searchBox);
// Create a button that will serve as the "Action" for the search box
JButton searchButton = new JButton("Search");
lefSide.add(searchButton);
// Create the station-list text area that will display text
// based on results from the search box
JTextArea stationListArea = new JTextArea(12, 0);
leftSide.add(stationListArea);
// Create a listener that listens to the Button, then performs an
// action from the search box to the text area
ActionListener searchButtonListener = new SearchListener(searchBox, stationListArea);
searchButton.addActionListener(searchButtonListener);
SearchListener
NOTE: Logic here will continue adding text into your stationListArea every time the button is clicked and HHHH.SimilarNames() returns a value. To have the stationListArea just update with the new text every time, replacing the old, add a stationListArea.setText("") at the beginning of actionPerformed().
public class SearchListener implements ActionListener {
private JTextField searchBox;
private JTextArea stationListArea;
public SearchListener(JTextField searchBox, JTextArea stationListArea) {
this.searchBox = searchBox;
this.stationListArea = stationListArea;
}
public void actionPerformed(ActionEvent event) {
XXXX<NAMES> stations = HHHH.SimilarNames(searchBox.getText());
for (NAMES station : stations) {
stationListArea.append(station);
}
}
}
Updated based on feedback in main comments
Your NAMES object needs some way to provide a String representation of itself. This way, you can then append that value to your text area..
public class SearchListener implements ActionListener {
private JTextField searchbox;
private JTextArea stationList;
public SearchListener(JTextField search box) {
this.searchbox = searchbox;
}
public void actionPerformed(ActionEvent event) {
XXXX<NAMES> stations = HHHH.SimilarNames(searchbox.getText());
for (NAMES station : stations) {
stationList.append(station.getLocationName()());
}
}

JTextArea show Caret while setEditable is false

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.

Using JInternalFrame and some button

Can we use a JInternalFame with a button in the main frame? The frame contains a JDesktopPane, of course. The button should open up the JInternalFrame How?
I don't know a way to put a JButton directly on a JDesktopPane, but you can use menu items to create and select a JInternalFrame. In this example, each menu item uses an Action defined in the JInternalFrame to select the corresponding frame.
class MyFrame extends JInternalFrame {
private Action action;
MyFrame(JDesktopPane desktop, String name, int offset) {
…
action = new AbstractAction(name) {
#Override
public void actionPerformed(ActionEvent ae) {
try {
MyFrame.this.setSelected(true);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
};
}
public Action getAction() { return action; }
}
Addendum: as #camickr suggests, it is technically possible to put a JButton directly on a JDesktopPane, but it might prove difficult to use in practice.
I don't really understand the question so I will just make some observations.
a) a JInternalFrme is like a frame in that you can add any component to it that you want
b) A JButton works the same whether it is added to an internal frame or a frame
I suggest you start by reading the Swing tutorial for working examples. You might start with the sections on "How to Use Internal Frames" and "How to Use Buttons".
If you still have problems then post your SSCCE that shows what you have tried.

Categories