2D JTextField array setText using MouseClicked/MousePressed - java

So I have a JTextField array called fields and I have a string called value (the value of value is replaced when I click on a button). What I want is when I click on one of the JTextFields, I want to put the value in it (using setText, maybe).
private JTextField[][] fields;
fields = new JTextField[totalX][totalY];
Is there a way to do this with a MouseClicked/MousePressed event. Any help is appreciated. Thank you.

Use FocusListener instead of mouse listener. Example:
JTextField field = new JTextField();
field.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
field.setText(value);
}
});
Tutorial - https://docs.oracle.com/javase/tutorial/uiswing/events/focuslistener.html

Related

JBTable ColumnInfo with button

I have a JBtable and in one of the columns I would like to insert a button.
My attempt was as follows:
private class DeleteColumn extends ColumnInfo<Field, JButton> {
public DeleteColumn() {
super("Delete");
}
#Nullable
#Override
public JButton valueOf(final Field field) {
final JButton removalButton = new JButton();
removalButton.setText("-");
removalButton.addActionListener((e) -> {
// do something
});
return removalButton;
}
#Override
public Class<?> getColumnClass() {
return JButton.class;
}
}
However when this is rendered, it still only displays the .toString() of the JButton. How can I display a button in the table?
You should write a custom renderer. Please look at:
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#editrender
There are also examples you could look at:
http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TableRenderDemoProject/src/components/TableRenderDemo.java
I would like to insert a button
You should NOT be adding a JButton to the table. The data of the JTable should not be a Swing component. You should just be storing text in the column and then use a JButton to render the text.
For example check out Table Button Column for a class that allow you to use a button as the renderer/editor.

How to add actionlistener to textfield in Java

so this is the concept: Simply, there's a textbox with "Name" as the value, and I wanted that if I click anywhere IN the textbox, the value "Name" will disappear. This is what I've done in my code:
JTextField t1 = new JTextField("Name", 10);
t1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent cl){
t1.setText(" ");
}
});
There's no syntax errors but when I run the program and clicked somewhere in the textbox, nothing happens and the value "Name" is still there
Any help would be greatly appreciated, thank you!
You can try this:
t1.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
t1.setText(null); // Empty the text field when it receives focus
}
});
You shouldn't use an ActionListener for this purpose. Instead of that the FocusListener should work for you, explained here: http://www.java2s.com/Code/JavaAPI/javax.swing/JTextFieldaddFocusListenerFocusListenerl.htm
Don't use ActionListener, it isn't implementing classes for your needs. You can also add MouseListener by:
t1.addMouseListener(new MouseListener(){...});
http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseListener.html

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()());
}
}

Multiple JComboBox Event Handling in Same Class

I have two JComboBox and one button. I am trying to do that if I select an item from the two combo box individually and press the button called search. Then the two selected items from the two combo box will save in a new two separate string.
Please anyone help me to solve the problem.
Here is the code snippet
//here is the strings that in the combo box
String lc[] = {"Kolabagan-Dhaka", "Gabtoli-Dhaka", "Fakirapul-Dhaka", "Shaymoli-Dhaka"};
String rc[] = {"Banani-Bogra", "Rangpur","Shatrasta-Bogra"};
//here is my two jcombo box
JComboBox lcCombo = new JComboBox(lc);
JComboBox rcCombo = new JComboBox(rc);
// here is my search button
JButton searchButton = new JButton("Search");
There are two ways to go about this. The first is to have one class that implements ActionListener and in the implementation, check the source (ActionEvent.getSource()). Based on which component sourced the event, you take the appropriate action.
The other option (and my preference) is to create an ActionListener for each component that requires one. You can use anonymous classes if you don't want to explicitly define one for each case. This way each listener knows exactly what component caused the event and what action to take.
Example:
JComboBox lcCombo = new JComboBox(lc);
lcCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do left stuff
}
});
JComboBox rcCombo = new JComboBox(rc);
rcCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do right stuff
}
});
To expand on unholysampler, once you have the ActionListener working you can use lcCombo.getSelectedIndex() to check which item has been selected.

Categories