I have a swing application am working on, my application lets the user enter a first name, last name, and phone number. the the user clicks the add button and it adds the entries into the jlist(so it like a phone book). I have a jTextfield above the JList in which I want to allow the user to search for a specific name or phone number on the Jlist, so its kind like a google search you type a character and it shows names with relevant characters in the JList and such. Am really stuck and lost at this point any help would be appricated??
This is my add button code to add names to my Jlist:
private void btnAddContactActionPerformed(java.awt.event.ActionEvent evt) {
String firstName = txtFirstName.getText();
String lastName = txtLastName.getText();
String phoneNum = (txtPhoneNum.getText());
NumberFormat number = NumberFormat.getNumberInstance();
//Phone Number formatted
StringBuilder sb = new StringBuilder(phoneNum).insert(0, "(")
.insert(4,")").insert(8,"-");
String phoneNumFormatted = sb.toString();
contactsArrayList.add(firstName + "\t " + lastName + "\t " + phoneNumFormatted);
DefaultListModel<String> model = new DefaultListModel<>();
for(int i = 0; i < contactsArrayList.size(); i++)
{
String myArraylst = contactsArrayList.get(i);
model.addElement(myArraylst + "\t");
}
listPhoneBookContacts.setModel(model);
txtFirstName.setText("");
txtLastName.setText("");
txtPhoneNum.setText("");
}
It is possible to implement this kind of stuff in Swing, but it is gnarly and you are unlikely to do a good job of it (because it's hard). You're probably better off leaving it to some other library, like SwingX. They have a bunch of components you can use that might do exactly what you want.
If you don't want to use that, a quick Google search reveals a good tutorial for filtering JLists.
my application lets the user enter a first name, last name, and phone number
I would use a JTable to display all this information.
so its kind like a google search you type a character and it shows names with relevant characters
JTable has built in filtering. See Sorting and Filtering for a working example
Related
I'm starting out on Java and I'm creating a basic phonebook application.
I'd like to implement a "Search Contacts" function that searches through an ArrayList of contacts and returns a count of how many contacts match the user-inputted String using a for each loop and if statement.
Question is, is it possible to receive a count of the contacts that match the user's search input without first defining an int - say, int counter = 0; - and then updating it within the if statement?
Below is an example of the only method I know could work to tally the number of matching contacts:
int counter = 0;
System.out.println("Please enter name of contact: ");
String nameRequest = scanner.nextLine();
for (Contact c: contactList) {
if (nameRequest.equals(c.getName())){
counter++;
System.out.println(counter + " contact(s) found"
System.out.println("Name: " + c.getName());
}
}
Extras: How could I go about so the code also returns contacts that are only a partial match? e.g. User inputs "Michael" but there are no contacts that only contain "Michael". There are however contacts called "Michael B Jordan" and "Michael Schumacher" which I'd like returned for the partial match.
Thanks in advance!
Using the counter variable it is a standard for people in this cases. But if it is for study purposes, you can achieve this with Lambda, where you first select the contacts, get the names and store in a temporary list:
List<String> contactsFound = contactList.stream()
.map(Contact::getName)
.filter(nameRequest::equals)
.collect(Collectors.toList());
System.out.println(contactsFound.size() + " contact(s) found");
contactsFound.forEach(contactName -> System.out.println("Name: " + contactName));
Here is the same basic solution as Brothers answer but with a for loop (as in the question):
List<String> contactsFound = new ArrayList<>();
for (Contact c: contactList) {
if (c.getName().toLowerCase().contains(nameRequest.toLowerCase())){
contactsFound.add(c.getName());
}
}
I'm fairly new to programming, and I can't seem to figure out how to initialize a String on JFrame Form. I do not know what code to put in to initialize the String if the contents of the string is entered later, by the user. This basically means that the String (stringone) is currently a blank text field on my form. The user enters a sentence or string and the label (one) tells how many characters are in the string they just entered. Here is my code so far:
{String stringone = new String ();
int one;
one = Integer.parseInt(txtstringone.getText());
one = (stringone.length());
lblone.setText(String.valueOf(one));}
Currently there is a yellow line under the third line of code, saying it may not have been initialized. It also does not work when I run it. Hope this clears it up!
Thanks so much in advance!
Try this:
String stringone;
Remove new String()
If you want to initialize it, tou must pass it a String value. For example:
String stringone = "value";
The string's length (stringone.length()), will be 5.
So, in order to take the length of a String you must first initialize it. Otherwise, it will be null, and null does not have length.
The user enters a sentence or string and the label (one) tells how many characters are in the string they just entered.
What you need to do is add an event handler for when the user has entered the string. There is no "user entered string" before the user has given the string.
An event handler is code that runs when some "event" occurs. A user writing in a field is a possible event.
Here's how you can add an event listener on your txtstringone text field component. It will be triggered when the user presses the Enter key.
txtstringone = new JTextField();
txtstringone.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
String text = txtstringone.getText();
int one = text.length();
lblone.setText(String.valueOf(one));
}
});
You can find a longer tutorial at https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html and a short working program at https://docs.oracle.com/javase/tutorial/uiswing/examples/components/TextDemoProject/src/components/TextDemo.java
Hi im doing a project for college and after finishing the majority of the code i hit a speedbump i need to register three types of users and one of them uses the department building nick as a basis for the password attribution i have an arraylist for each type, the password for this type of user should composed by the nick of the department and the number of registered users in that department so i wrote the code below which works which kinda works but the first password always gives me an empty field, the code i have is:
public String GivePasswordStaff(String signdept){
int counter = 0;
String password = "";
Iterator<Staff> liststaff = staff.iterator();
while (liststaff.hasNext()) {
Staff lists = liststaff.next();
if(signdept.equals(lists.getSigndept())){
counter++;
password = signdept + counter;
}
}
return password;
}
The thing is i need the first passwords of each department to be nick1 and with this code the first one is always "" and the second it gives the password i want except if i input a password for a different department in which case it always start with nick0 what can i do to solve this
Thanks in advance to all that reply
An ugly but posible solution would be to assign the desired name for the password at the declaration:
String password = signdept+"1";
For the part about nick0, try to write some example, I can't understand what happens. What do you mean by "except if i input a password for a different department"?
I have design the search method. According to my requirement, If a user wants to search a customer’s record, he/she can input the customer’s family name or given name into the name text field and then click the search button. The following two screen shots show an example of the events before and after button click (with input the name to be searched is Lee)
And below is the code for searching. It is working fine but I want to make it better?
private void search()
{
String studentName=CNameTextField.getText();
String record="";
int count=0;
for(int i=0; i<myList.size();i++)
{
String name=myList.get(i).getName();
String [] splitName= name.split(" ");
if(studentName.equals(splitName[0]) || studentName.equals(splitName[1]))
{
count++;
record=record+"\n"+myList.get(i).toString();
}
display.setText("");
display.append(count + " result(s) found for "+ studentName);
display.append("\n "+ record);
}
}
So you've basically got a list of String items, and you're searching through all of them for the value?
My recommendation would be to create Objects for each line in your DisplayArea, rather than Strings. For example, when you read in the input file for your DisplayArea, do the split() for each line and create objects of type Customer that have fields called ID, name, room, etc. This would be better OO programming anyway - Strings don't really have any meaning, whereas a Customer has meaning.
If you do this, in the search you can simply loop over all the Customers in the list, asking whether the name.equals(customer.getName()); This would remove the need to split the line every time you search.
I am working on some project, where a user can fill in student details in a form with textfields and radio buttons etc, and the values shall then be used to create a record in a database.
Now, this is how i started:
String firstName = textField_1.getText();
String surname = textField_2.getText();
String Gender = rdbtnM.getText();
Basically, what it does is, its retrieving values from particular input fields.
Now, my question is, for gender i have two radio buttons. rdbtnM and rdbtnF.
A user can only click on one: Male or Female.
How do i write in String Gender, that it should get the value from M or F ?
Please advise?
I suppose you are using Swing, with two JRadioButton objects inside the same group, but your question is very imprecise. If you want to do it in a simple way, you can do the following:
String gender // make your variable names start lower-case
if (rdbtnM.isSelected()) {
gender = "male";
}
else if (rdbtnF.isSelected()) {
gender = "female";
}
else {
gender = "unknown";
}
You can of course avoid the last case by initializing the button states properly, but you don't provide any initialization code. There is an official tutorial about buttons, which also explains how to deal with radio buttons by the means of ActionListeners, which I avoided here.