Using JComboBox as a search box - java

Im using a JComboBox to search a query from a sql database. Here is my code.
private void srKeyTyped(java.awt.event.KeyEvent evt){
sr.removeAllItems();
String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
String schh = "SELECT * FROM tbl WHERE name LIKE '" + sch + "%';";
search = conn.getQuery(schh);
try {
while (search.next()) {
String item = search.getString("name");
sr.addItem(item);
}
} catch (SQLException ex) {
Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
sr.setSelectedItem(null);
sr.setPopupVisible(true);
System.out.println(sch);
}
sr = JComboBox
But when i type a letter in combobox, it adds all the items in database. I came to know that System.out.println(sch); always gives an empty string. And as soon as i type a letter, the text field of combo box becomes empty(i cant type a word with two letters). How to fix this? Thank you.

The reasons for your problems are the following:
sch is always empty is because you are calling sr.removeAllItems(); before you call String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();. This means that the contents of the JComboBox is cleared (along with the selection) before you get what is selected.
Solution: Call sr.removeAllItems();AFTER you have got the selected item.
The combo box becomes empty because you call sr.setSelectedItem(null); at the end after you have repopulated it.
Solution: If you want the entered text then sr.getEditor().setItem(scr);
Only and idea but try to enclose the contents of the method in an if statement and check if the Enter key is pressed. That way the method contents will only execute after the desired string is input and not EVERY time a key is pressed.

Use an ActionListener instead of the looking for the key press. When a combobox's selection is edited it will fire an ActionEvent when the editing is done.
When you get this part working, you should move this logic off to another thread and populate the combobox's items when it returns. Otherwise your UI will hang while the SQL query occurs.

Got the solution. This code works fine.
private void srKeyTyped(java.awt.event.KeyEvent evt){
String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
String schh = "SELECT * FROM tbl WHERE name LIKE '" + sch + "%';";
search = conn.getQuery(schh);
sr.removeAllItems();
try {
while (search.next()) {
String item = search.getString("name");
sr.addItem(item);
}
} catch (SQLException ex) {
Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sch);
sr.setSelectedItem(null);
sr.setPopupVisible(true);
((JTextField)sr.getEditor().getEditorComponent()).setText(sch);
}
Thanks to Skepi,Kleopatra, Guillaume Polet

Related

Update data in JTable when data from a file used in the JTable is updated

So my JTable's data is from a text file. I have code in place to update that text file's information which works. However, I do not see additional rows in the JTable.
The way information is added to the text file is:
Clicking the Make appointment button and a dialog will appear.
The user will enter in relevant information.
Once information is entered the user presses ok which triggers the onOk function (in ScheduleAppointment.java) and writes information to the file.
private void onOK() {
// https://www.baeldung.com/java-string-to-date
String time = appointmentTimeField.getText();
String appointmentDate = appointmentDateField.getText() + " " + time;
String line = String.format("%s,%s,%s,%s,0\n", this.fname, this.lname, this.telephone, appointmentDate);
CSVReader reader = new CSVReader("./appointments.txt");
reader.writeAppointmentFile(line);
dispose();
}
Since I am using IntelliJ IDEA's form builder I have tried calling createUIComponent when the function that updates the text file is ran, it didn't work. So, I added a call to that function at the end of onOk
private void onOK() {
// https://www.baeldung.com/java-string-to-date
String time = appointmentTimeField.getText();
String appointmentDate = appointmentDateField.getText() + " " + time;
String line = String.format("%s,%s,%s,%s,0\n", this.fname, this.lname, this.telephone, appointmentDate);
CSVReader reader = new CSVReader("./appointments.txt");
reader.writeAppointmentFile(line);
createUIComponents(); // <-- Add this call to redraw the tables.
dispose();
}
Inside that function is a call to another function. createStaffAppointment(). This is what createStaffAppointment() looks like.
public void createStaffAppointment() {
CSVReader appointments = new CSVReader("./appointments.txt");
Vector<Vector<String>> columns = appointments.parseAppointmentFile(false);
Vector<String> names = new Vector<>();
names.add("Name");
names.add("Telephone");
names.add("Date");
staffTimetable = new JTable(columns, names);
}
I've also tried to use fireUpdateTableChanged on the table model. But, it didn't work as the table model didn't change. Only the text file where the data is taken from has changed.
The minimal reproducible example can be downloaded in dropbox here.

How to Handle NoSuchElementException for empty element.and still execute next line of code?

i am trying to get text of dynamic web table to excel sheet , sometimes text is present in rows of column and sometime it is not.. when text is present in the table row , i want to get text of that cell..using getText Method, But when Text is not present i want to write empty text and keep cell blank.. But it is giving NoSuchElementException.. how to handle that..?? any help would be appreciated.. thanks in advance..
String actualXpath_SL = beforeXpath_SL + j + afterXpath_SL;
String SL = driver.findElements(By.xpath(actualXpath_SL)).getText()
currentRow.createCell(0).setCellValue(SL);
To continue your programme when selenium doesn't find an element you can do two things.
Put the code inside a try block and handle the NoSuchElementException in the catch block.
String OneA = "";
try{
//find element
OneA = driver.findElement(By.xpath(actualXpath_1A)).getText();
}catch (NoSuchElementException e){
//stacktrace and other code after catching the exception
e.printStackTrace();
}
Or, you can use findElements and check the returned list is empty or not.
List<WebElement> elements = driver.findElements(By.xpath(actualXpath_1A));
String OneA = "";
if(!elements.isEmpty()){
OneA = elements.get(0).getText();
} else {
//Handle if no element present
}
the second solution avoids the exception and it is faster than waiting for the exception.
You should use .size()>0 rather isEmpty()
String actualXpath_2S = beforeXpath_2S + j + afterXpath_2S;
List<WebElement> eight = driver.findElements(By.xpath(actualXpath_2S));
String TwoS="";
if(eight.size()>0){
TwoS = eight.get(0).getText();
}
You have to update the logic for all if conditions that are using isEmpty.

Reading the Data of a Highlighted Jtable Row

I have a JTable with rows of Data
I have this event that listen every time a row got mouse clicked
private void tablePOMouseClicked(java.awt.event.MouseEvent evt) {
try {
int row1 = tablePO.getSelectedRow();
cellA = tablePO.getValueAt(row1, 0).toString();
cellB = tablePO.getValueAt(row1, 1).toString();
cellC = tablePO.getValueAt(row1, 2).toString();
cellD= tablePO.getValueAt(row1, 3).toString();
cellE = tablePO.getValueAt(row1, 4).toString();
cellF = tablePO.getValueAt(row1, 5).toString();
cellG = tablePO.getValueAt(row1, 6).toString();
cellH = tablePO.getValueAt(row1, 7).toString();
} catch (Exception e) {
}
}
variable cellA-H are all Strings.
its working good, but now I want to change it, I dont want the user to have the need to use the mouse, so instead, I want the user just select the row with using either UP/DOWN arrow to navigate the rows and put the selected row under the highlight, but I have no Idea how I am able to achieve it, reading the data from highlighted/selected row by using the UP/DOWN Keys (Not by pointing the row with mouse click).
Add a ListSelectionListener to the table.
An event will be generated whenever the row selection changes whether you use the mouse or the keyboard.
Read the section from the Swing tutorial on How to Write a ListSelectionListener for more information and working examples.

Oracle MAF : ListView displaying all data when setEntity sets empty ResultList?

I am displaying list of data based on the query result in MAF along with A-Team persistence accelerator, below is the sample code which i'm using when some action button has been clicked,
ClassMappingDescriptor descriptor = ClassMappingDescriptor.getInstance(PojoClass.class);
DBPersistenceManager pm= getLocalPersistenceManager();
try {
StringBuffer sql = pm.getSqlSelectFromPart(descriptor);
sql.append(" WHERE ACTIVE_FLAG='YES'");
sql = pm.constructOrderByClause(sql, descriptor);
ResultSet set = pm.executeSqlSelect(sql.toString(), new ArrayList());
List ResultList = pm.createEntitiesFromResultSet(set, (List) descriptor.getAttributeMappingsDirect());
System.out.println("ResultList size : " +ResultList.size())
setEntityList(ResultList);
} catch (Exception exp) {
System.out.println("Exception : " + exp);
}
If ResultList size returns any value then it is working as expected, But when ever ResultList size returns 0 then listView showing all data of the particular associated pojo class table. In this case, actually non of the record should be displayed.
Any help would be appreciated, please comment below if you need any more details regarding this.

Force JOptionPane to Stay Open

My application is constructed as follows:
Main window allows user to select CSV file to be parsed
JOptionPane appears after a CSV file is selected and the JOptionPane contains a drop-down menu with various choices; each of which generates a separate window
Currently, the JOptionPane closes after a selection is made from the menu and the "OK" button is clicked
I am looking for a way to force the JOptionPane to remain open so that the user can select something different if they want. I would like the JOptionPane to be closed only by clicking the "X" in the upper right corner. I am also open to other possibilities to achieve a similar result if using a JOptionPane isn't the best way to go on this.
Here is the relevant block of code I'm working on:
try
{
CSVReader reader = new CSVReader(new FileReader(filePath), ',');
// Reads the complete file into list of tokens.
List<String[]> rowsAsTokens = null;
try
{
rowsAsTokens = reader.readAll();
}
catch (IOException e1)
{
e1.printStackTrace();
}
String[] menuChoices = { "option 1", "option 2", "option 3" };
String graphSelection = (String) JOptionPane.showInputDialog(null,
"Choose from the following options...", "Choose From DropDown",
JOptionPane.QUESTION_MESSAGE, null,
menuChoices, // Array of menuChoices
menuChoices[0]); // Initial choice
String menuSelection = graphSelection;
// Condition if first item in drop-down is selected
if (menuSelection == menuChoices[0] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option1();
}
if (menuSelection == menuChoices[1] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option2();
}
if (menuSelection == menuChoices[2] && graphSelection != null)
{
log.append("Generating graph: " + graphSelection + newline);
option3();
}
else if (graphSelection == null)
{
log.append("Cancelled." + newline);
}
}
I would like for the window with the choices to remain open even after
the user has selected an option so that they can select another option
if they wish. How do I get the JOptionPane to remain open instead of
its default behavior where it closes once a drop-down value is
selected?
this is basic property, by default JOptionPane is disposed, this isn't possible without dirty hacks, don't do that
use JDialog (could, may be undecorated) with proper value for ModalityType
you can to use some of variations for Java & Ribbon
you can to put desired choices to the JComboBox or JMenu with JMenuItems (very nice of ways) to the JLayer or GlassPane
I think that this is standard job for JMenu or JToolBar
In either of these option panes, I can change my choice as many times as I like before closing it. The 3rd option pane will show (default to) the value selected earlier in the 1st - the current value.
import java.awt.*;
import javax.swing.*;
class Options {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
Object[] options = {
"Option 1",
"Option 2",
"Option 3",
"None of the above"
};
JComboBox optionControl = new JComboBox(options);
optionControl.setSelectedIndex(3);
JOptionPane.showMessageDialog(null, optionControl, "Option",
JOptionPane.QUESTION_MESSAGE);
System.out.println(optionControl.getSelectedItem());
String graphSelection = (String) JOptionPane.showInputDialog(
null,
"Choose from the following options...",
"Choose From DropDown",
JOptionPane.QUESTION_MESSAGE, null,
options, // Array of menuChoices
options[3]); // Initial choice
System.out.println(graphSelection);
// show the combo with current value!
JOptionPane.showMessageDialog(null, optionControl, "Option",
JOptionPane.QUESTION_MESSAGE);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
I think Michael guessed right with a JList. Here is a comparison between list & combo.
Note that both JList & JComboBox can use a renderer as seen in the combo. The important difference is that a list is an embedded component that supports multiple selection.
The following solution won't give you a drop-down menu but it will allow you to select multiple values.
You can use a JList to store your choices and to use JOptionPane.showInputMessage like this:
JList listOfChoices = new JList(new String[] {"First", "Second", "Third"});
JOptionPane.showInputDialog(null, listOfChoices, "Select Multiple Values...", JOptionPane.QUESTION_MESSAGE);
Using the method getSelectedIndices() on listOfChoices after the JOptionPane.showInputDialog() will return an array of integers that contains the indexes that were selected from the JList and you can use a ListModel to get their values:
int[] ans = listOfChoices.getSelectedIndices();
ListModel listOfChoicesModel = listOfChoices.getModel();
for (int i : ans) {
System.out.println(listOfChoicesModel.getElementAt(i));
}

Categories

Resources