The use case in my UI is to populate two JTextField components based on double clicking items in a JList. The easy was is to use a JCheckBox populate jTextField1 if the checkbox is selected, and populate the other if it is not selected or vice versa which is working perfectly.
But I would like to explore if this can be done without the checkbox.
As in, if I type something in jtextfield1 and double click the item in list to complete the text, the item clicked should be appended to jtextfield1 based on fetching the latest KeyStroke I used.
Is there are any way to do this?
The use case in my UI is to populate two jTextField's based on double clicking items in a jlist.
Well, normally a UI should be designed so that you can use the mouse or the keyboard to invoke an Action. That is you should be able to double click or use the Enter key on the selected item.
Check out List Action for a simple class that allows you to implement this functionality by using an Action.
Now when you create your Action you can extend TextAction. Then you can use the getFocustComponent() method from the TextAction to determine the text component that last had focus and add the text from the selected item to that text field.
The basic code for the custom Action would be:
JList list = (JList)e.getSource();
JTextComponent textField = getFocusedComponent();
textField.setText( list.getSelectedValue().toString() );
Note: you will need to verify if focus is on one of the two fields if your window contains more than two text components.
To use the FocusListener approach you would need to define an instance variable in your class:
private JTextField lastFocusedTextField = null;
Then in the constructor of your class where you create the text fields you would create the listener:
FocusListener fl = new FocusAdapter()
{
#Override
public void focusGained(FocusEvent e)
{
lastFocusedTextField = (JTextField)e.getSource();
}
};
JTextField textField1 = new JTextField(...);
textField1.addFocusListener( fl );
// same for the other text field
Now you need to add a MouseListener to the JList. In the mouseClicked(...) method you do something like:
JList list = (JList)e.getSource();
lastFocusedTextField.setText( list.getSelectedValue().toString() );
So you need:
an instance variable
a FocusListener
a MouseListener
As everyone has suggested initialize a FocusListener to both the text fields and and point it to a string variable when either of the loses focus.
Code:
String LastFocusLost = null;
jTextField1.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
LastFocusLost = "jTextField1";
}
});
jTextField2.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
LastFocusLost = "jTextField2";
}
});
In the mouseListener add a if-else then:
if ("jTextField1".equals(LastFocusLost))
{
//;
}
else if ("jTextField2".equals(LastFocusLost))
{
//;
}
Related
The use case in my UI is to populate two JTextField components based on double clicking items in a JList. The easy was is to use a JCheckBox populate jTextField1 if the checkbox is selected, and populate the other if it is not selected or vice versa which is working perfectly.
But I would like to explore if this can be done without the checkbox.
As in, if I type something in jtextfield1 and double click the item in list to complete the text, the item clicked should be appended to jtextfield1 based on fetching the latest KeyStroke I used.
Is there are any way to do this?
The use case in my UI is to populate two jTextField's based on double clicking items in a jlist.
Well, normally a UI should be designed so that you can use the mouse or the keyboard to invoke an Action. That is you should be able to double click or use the Enter key on the selected item.
Check out List Action for a simple class that allows you to implement this functionality by using an Action.
Now when you create your Action you can extend TextAction. Then you can use the getFocustComponent() method from the TextAction to determine the text component that last had focus and add the text from the selected item to that text field.
The basic code for the custom Action would be:
JList list = (JList)e.getSource();
JTextComponent textField = getFocusedComponent();
textField.setText( list.getSelectedValue().toString() );
Note: you will need to verify if focus is on one of the two fields if your window contains more than two text components.
To use the FocusListener approach you would need to define an instance variable in your class:
private JTextField lastFocusedTextField = null;
Then in the constructor of your class where you create the text fields you would create the listener:
FocusListener fl = new FocusAdapter()
{
#Override
public void focusGained(FocusEvent e)
{
lastFocusedTextField = (JTextField)e.getSource();
}
};
JTextField textField1 = new JTextField(...);
textField1.addFocusListener( fl );
// same for the other text field
Now you need to add a MouseListener to the JList. In the mouseClicked(...) method you do something like:
JList list = (JList)e.getSource();
lastFocusedTextField.setText( list.getSelectedValue().toString() );
So you need:
an instance variable
a FocusListener
a MouseListener
As everyone has suggested initialize a FocusListener to both the text fields and and point it to a string variable when either of the loses focus.
Code:
String LastFocusLost = null;
jTextField1.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
LastFocusLost = "jTextField1";
}
});
jTextField2.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
LastFocusLost = "jTextField2";
}
});
In the mouseListener add a if-else then:
if ("jTextField1".equals(LastFocusLost))
{
//;
}
else if ("jTextField2".equals(LastFocusLost))
{
//;
}
help,
my questions are:
why isn't itemStateChanges triggered, I tried to put it in the inner class ButtonHandler and also in RadioButtonHandler Im having trouble with it, what is the right way to do it?
I want to trigger and check the marked JRadioButtons after the user click the "check" button.
What is the right way to check which button was clicked, I feel like comparing the strings is bad programming practise. Maybe using an ID ?
How should I make a "reset" button(start over), I want to uncheck all radio buttons and run the constructor once again.
Thank you for your help !
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class ExamFrame extends JFrame {
static ArrayList<Question> qArrList;
JRadioButton a1,a2,a3,a4;
public ExamFrame() {
super("Quiz");
setLayout(new GridLayout(0, 1));
GridBagConstraints gbc = new GridBagConstraints();
Exam exam = new Exam();
qArrList = exam.getExam();
int count=0;
for(Question q : qArrList){
count++;
JLabel questionLabel = new JLabel(count+". "+q.getQustion()); //swing constant ?
ArrayList<String> ansRand = q.getAllRandomAns();
a1 = new JRadioButton(ansRand.get(0));
a2 = new JRadioButton(ansRand.get(1));
a3 = new JRadioButton(ansRand.get(2));
a4 = new JRadioButton(ansRand.get(3));
add(questionLabel);
add(a1);add(a2,gbc);add(a3);add(a4);
ButtonGroup radioGroup = new ButtonGroup(); //logical relationship
radioGroup.add(a1);radioGroup.add(a2);radioGroup.add(a3);radioGroup.add(a4);
}
//buttons:
JButton checkMe = new JButton("Check Exam");
JButton refresh = new JButton("Start Over");
ButtonHandler handler = new ButtonHandler();
checkMe.addActionListener(handler);
refresh.addActionListener(handler);
add(checkMe);
add(refresh);
}
/** Listens to the radio buttons. */
public class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e) {
if(e.getActionCommand().equals("Start Over")){ //id?
//how to do this?
}
else{
RadioButtonHandler handler = new RadioButtonHandler();
a1.addItemListener(handler);
System.out.println("success?");
}
JOptionPane.showMessageDialog(ExamFrame.this, String.format("You pressed: %s", e.getActionCommand()));
}
public void itemStateChanged(ItemEvent e) //can i add it here?
{
JOptionPane.showMessageDialog(ExamFrame.this, String.format("yes?"));
System.out.println("success!");
}
}
public class RadioButtonHandler implements ItemListener
{
public void itemStateChanged(ItemEvent e)
{
JOptionPane.showMessageDialog(ExamFrame.this, String.format("radio state changed"));
}
}
}
why "itemStateChanges" isn't triggered, i tried to put it in the inner
class "ButtonHandler" and also in "RadioButtonHandler" Im having
troubles with it, what is the right way to do it? I want to trigger
and check the marked JRadioButtons after the user click the "check"
button.
ButtonHandler is implemented with ActionListener only:
public class ButtonHandler implements ActionListener{}
The itemStateChanged(ItemEvent) function belongs to ItemListener. This function is triggered if state of a source component to which this listener is registered gets changed. So implement the ItemListener. However, one more thing to note, that JButton doesn't respond to ItemListener but JRadioButton will. Because this Item events are fired by components that implement the ItemSelectable interface. Some example of such components are: check boxes, check menu items, toggle buttons and combo boxes including Radio Buttons as mentioned above.
What is the right way to check which button was clicked, i feel like
comparing the strings is wrong programming. Maybe using an ID
Well using the event source function: e.getSource(), check whither the type of the source is your expected type and cast it to appropriate type. And then you can use getName(String) function and check the name you were expecting. Of-course you should assign the name using setName(String) after initialization of component. Or using the component reference directly if it is declared in the Class context and you have direct access to the component.
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getSource() instanceof JCheckBox)
{
JCheckBox checkBox = (JCheckBox)e.getSource();
if(checkBox.getName().equals("expectedName"))
; // do my thing
}
}
How should i make a "reset" button(start over), i want to uncheck all
radio buttons and run the constructor once again.
Well you are working with ButtonGroup. And ButtonGroup has a nice function: clearSelection() to help with whatever(I could not understand the part: run the constructor part) you want.
Edit: As you wanted me to see an ItemListener implemented class, Yes i can see that But:
i can not see that you have actually registered an instance of that class(a1.addItemListener(handler);) to any component before performing any action on the component to which ButtonHandler is registered to: checkMe, refresh
In addition to that, in this action performed function, you are checking with
action command, which you haven't even set with JButton.setActionCommand(String) function. You should not assign a (Item)listener depending on event-occurrence of another (Action)listener.
Tutorial:
How to Write an ItemListener
How to Write an ActionListener
How to Use the ButtonGroup Component
i would like to know, how can i add a new item by new panel in Java GUI.
I have class Program
public class Program extends javax.swing.JFrame {
public ArrayList<Contact> contacts = new ArrayList<Contact>();
public int pos;
public Program() {
contacts.add(new Contact("John Tavares", "736426436", "Prague"));
contacts.add(new Contact("John Doe", "725847896", "NY"));
contacts.add(new Contact("Damien Smith", "725589963", "London"));
pos = 0;
initComponents();
}
and then some labels which show content of ArrayList, it works fine. In class Contact have name, tel and city.
And i have JButton New Contact which opened new Panel NewContact with text fields for name, tel and city and of course OK JButton. This works fine, too.
Can anybody help me, please, how can i get texts from text fields in NewContact and add them to ArrayList?
Thanks for any advices
If I understand right, u waant to add contacts with a button.
At first you have to make a new button:
private JButton mybutton = new JButton("Add");
Then you have to override the actionListener
private void addActionListener() {
mybutton.addActionListener(this);
}
Then you have to sreach what kind of button you pressed:
#Override
public void actionPerformed (ActionEvent e) {
Object source = e.getSource();
if(source == mybutton)
contacts.add(something);
}
I would suggest a JTable should be used to display your data. Read the section from the Swing tutorial on How to Use Tables for more information.
In you new contact form you would then add the data to the TableModel directly. The DefaultTableModel supports an addRow(...) method.
For a more complex solution that lets you add a Contact to the TableModel you will need to create a custom model. You could use a Bean Table Model.
how can i get texts from text fields
You use the getText() method. Read the Swing tutorial. Maybe start with the section on How to Write an Action Listener. An ActionListener gets invoked when you click on a button.
I have a GUI designed in Swing with all of the Components laid out. For example I have a JComboBox with a JList and a JTextField,
When I select a different item from the JComboBox I am trying to use a ListSelectionListener to call a method in a subclass to update the JTextField based on the choice,
How would I go about doing that properly? How do I call the subclass and then from the subclass update the GUI object's value?
public class Parent {
private void init() {
// ...
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object selected = combo.getSelectedItem();
textField.setText(getTextBasedOnSelection(selected));
}
});
// ...
}
/**
* Returns the text to display when the given object is selected.
* Subclasses may override this method to display what they want
*/
protected String getTextBasedOnSelection(Object selected) {
return selected.toString();
}
// ...
}
I hope I get your problem right. You have a View Component with several subviews and you want to update one because of the changes done inside the other one.
Therefore you write an action listener for your combobox in the main View:
comboBox.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
textField.setText(comboBox.getSelectedItem());
}
});
Instead of inter-connecting components directly, I recommend to apply the Mediator pattern:
Create a subclass of JPanel (e.g. XyzPane) where you put all your components in. This class becomes the Mediator. It
listens for events of its components
updates the components as needed
fires its own events, if needed (this allows it to be a part of a parent Mediator: grouping components in Panes and then nesting the Panes)
I am making a Java application where I show a couple of checkboxes with relevant item from a file. Based on the selection I have to modify the original file accordingly. I have done this part.
I now realized that there might be some information that the user wants to add extra. I therefore want to show a checkbox with a JTextField hooked to it. The idea that I am trying to use is that if the value of checkbox is true, the value of JTextField associated with it, is included in the file.
I want to do something like this:
checkBoxes[i] = new Checkbox(new JTextField("enter new member e.g private int newMember"), null, false);
then
if(checkBoxes[i]==true)
{
updatefile(file, checkBoxes[i]);
}
Where updateFile is a function that adds the value of checkBoxes[i] to file
Any idea on how should I work on this?
Just create the JTextField separately, there's no need for them to be the same control.
i.e.
checkBoxes[i] = new JCheckBox("label");
textFields[i] = new JTextField("extra data");
// ...
if (checkBoxes[i].isSelected()) {
updateFile(file, textFields[i]);
}
If you want to enable/disable the textFields based on the selected state of the checkbox, do it using a listener - e.g. an ActionListener:
checkBoxes[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textFields[i].setEnabled(checkBoxes[i].isSelected());
}
You could have the JTextField as a seperate variable and have them both in a JPanel
JTextField textField = new JTextField();
JCheckBox checkBox = new JCheckbox("enter new member e.g private int newMember",false);
JPanel panel = new JPanel();
panel.add(checkBox);
panel.add(textField);
And then access it like that
if(checkBox.isSelected())
{
updatefile(file, textField.getText());
}
Hope it helps.