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.
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))
{
//;
}
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))
{
//;
}
alright.,ive already tried every trick off my sleeves..but couldnt figure out how to update the comboBox w/glazedList..if the input is coming from other class..ive tried passing the value to the methods,declaring it first to a string..and such..but none has work..tho it does work if the new item will just gonna come from same class..via click of a button..
so far ive got this code..
values = GlazedLists.eventListOf(auto);//auto is an array..
AutoCompleteSupport.install(comboSearch,values);//comboSearch is the comboBox
//"x" is the value coming from another class.
public void updateCombo(String x){
List<String> item = new ArrayList<>();
item.add(x)
value.addAll(item);
}
i hope this codes are enough to interpret what im trying to ask..
It's not possible to see how you've created your combobox and your eventlist. Therefore I'll just create a simple example application from scratch that shows you the essentials.
Just in case you're not familiar the general concepts the main take home points are:
Try and avoid using standard Java collections (eg ArrayList, Vector) and use the EventList class as soon as possible. All the goodness that comes with sorting/filtering/auto-complete relies on the EventList foundation so set one up asap and then simply manipulate (add/remove/etc) and then the GlazedLists plumbing will take care of the rest.
Once you've got your collection of objects in an EventList and you want to leverage a swing component then look in the ca.odell.glazedlists.swing module which contains everything you need. In this instance you can use an EventListComboBoxModel - pass in your eventlist, and then set your JComboBox model to use the newly created EventListComboBoxModel and from that point GlazedLists will take care of ensuring your list data structure and combobox stay in sync.
So in my example I create an empty combobox and an button. Clicking the button will add an item per click into the combobox. The magic is simply the creation of the EventList and the use of EventListComboBoxModel to link the list to the combobox.
Please note that the code below was only tested against GlazedLists 1.8. But I'm pretty sure it'll work fine with 1.9 or 1.7 too.
public class UpdateComboBox {
private JFrame mainFrame;
private JComboBox cboItems;
private EventList<String> itemsList = new BasicEventList<String>();
public UpdateComboBox() {
createGUI();
}
private void createGUI() {
mainFrame = new JFrame("GlazedLists Update Combobox Example");
mainFrame.setSize(600, 400);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton addButton = new JButton("Add Item");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
itemsList.add("Item " + (itemsList.size()+1));
}
});
// Use a GlazedLists EventComboBoxModel to connect the JComboBox with an EventList.
EventComboBoxModel<String> model = new EventComboBoxModel<String>(itemsList);
cboItems = new JComboBox(model);
JPanel panel = new JPanel(new BorderLayout());
panel.add(cboItems, BorderLayout.NORTH);
panel.add(addButton, BorderLayout.SOUTH);
mainFrame.getContentPane().add(panel);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new UpdateComboBox();
}
});
}
}
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 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.