How to sort item in java combobox [duplicate] - java

This question already has answers here:
How to sort the jComboBox elements in java swing?
(3 answers)
Closed 6 years ago.
I have a java form using JCombobox. There is a "text field", "combobox" and "add" button. When I enter text in the text field, then click Add button, the text in the text field will fill into combobox, but it doesn't sort by a-z.
form screenshot
Below is my code in Add button.
private void cmdAddActionPerformed(java.awt.event.ActionEvent evt) {
if(MyInput.checkText(txtField)){ //MyInput is my own method code to check if the text is entered.
String st=txtField.getText();
combox.addItem(st);
String st1="";
String st2="";
int com=st1.compareTo(st2);
if(com<0){ //I create this string comparison
//I need to add the "sort" code here
}else{
}
}else
JOptionPane.showMessageDialog(this, "Please enter text."); //When no text is entered, this message appears.
}
Full source code:
import PlugIn.MyInput;
import javax.swing.JOptionPane;
public class JCombo extends javax.swing.JFrame {
/**
* Creates new form JCombo
*/
public JCombo() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
txt = new javax.swing.JTextField();
combo = new javax.swing.JComboBox();
cmdAdd = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
txt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtActionPerformed(evt);
}
});
combo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
comboActionPerformed(evt);
}
});
cmdAdd.setText("Add");
cmdAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdAddActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(88, 88, 88)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txt)
.addComponent(combo, 0, 188, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cmdAdd)
.addContainerGap(63, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(40, 40, 40)
.addComponent(txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(combo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cmdAdd))
.addContainerGap(206, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void txtActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void cmdAddActionPerformed(java.awt.event.ActionEvent evt) {
if(MyInput.checkText(txtField)){ //MyInput is my own method code to check if the text is entered.
String st=txtField.getText();
combox.addItem(st);
String st1="";
String st2="";
int com=st1.compareTo(st2);
if(com<0){ //I create this string comparison
//I need to add the "sort" code here
}else{
}
}else
JOptionPane.showMessageDialog(this, "Please enter text."); //When no text is entered, this message appears.
}
private void comboActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JCombo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JCombo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton cmdAdd;
private javax.swing.JComboBox combo;
private javax.swing.JTextField txt;
// End of variables declaration
}

Use a SortedComboBoxModel: (How to sort the jComboBox elements in java swing?)
String[] items = { "one", "two", "three" };
SortedComboBoxModel<String> model = new SortedComboBoxModel<String>(items);
JComboBox<String> comboBox = new JComboBox<String>(model);
comboBox.addItem("four");
comboBox.addItem("five");
comboBox.setSelectedItem("one");

You have to take care of the order yourself.
Use getModel() for getting the current list
Figure out where the item should go
Use insertItemAt(E item, int index) to place the item int the correct position.

Related

How to restore InputVerifier mechanism while using cancel button?

I have an InputVerifier on a JFormattedTextField. It is called when field looses focus perfectly. I added a cancel button (JButton), but do not want to call then InputVerifier when this button is clicked.
MyVerifier is called when the focus is lost on the field without any problem. However, after I click the clearButton the InputVerifier won´t be called again, as if the button where clicked even if it´s not.
The complete code is:
public class DemoFrame extends javax.swing.JFrame {
/** Creates new form DemoFrame */
public DemoFrame() {
initComponents();
name.setValue("");
name.setInputVerifier(new MyVerifier());
clear.setVerifyInputWhenFocusTarget(false);
}
private class MyVerifier extends javax.swing.InputVerifier {
public boolean verify(javax.swing.JComponent input) {
System.out.println("Field is being verified");
return true;
}
public boolean shouldYieldFocus(javax.swing.JComponent input) {
return verify(input);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
name = new javax.swing.JFormattedTextField();
clear = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
name.setText(" ");
clear.setText("clear");
clear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(231, Short.MAX_VALUE)
.addComponent(clear)
.addGap(112, 112, 112))
.addGroup(layout.createSequentialGroup()
.addGap(116, 116, 116)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(156, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 90, Short.MAX_VALUE)
.addComponent(clear)
.addGap(73, 73, 73))
);
pack();
}// </editor-fold>
private void clearActionPerformed(java.awt.event.ActionEvent evt) {
name.setValue(null);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DemoFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton clear;
private javax.swing.JFormattedTextField name;
// End of variables declaration
}
Why isn't the InputVerifier been invoked if the field looses focus without the button being clicked?
Well. I found the solution.
clear.setFocusable(false);
That solves the problem.

Iterating through List but it only shows last item

What I am trying to achieve is have one JLabel to display multiple items from a List.
I have defined the list as below but when I test the code my method to iterate through the list, after a button click, only shows the last item in the list which is "DONE!".
I am trying to accomplish displaying only the next item in the list after each button click on one JLabel.
public class ScoutGUI extends javax.swing.JFrame {
/**
* Creates new form ScoutGUI
*/
List<String> strings = Arrays.asList("Do you mind Clutter in Room?", "Do you mind alarm clocks?","Do you mind loud visitors?","Can you sleep with lights on?","Do you mind noise past Midnight?",
"Do you consider yourself as an introvert?", "Do you consider yourself as an extrovert?","Do you like to go to parties?","Do you drink alcoholic beverages?(21+)", "DONE!");
ArrayList<Student> obj = new ArrayList<>();
String name , email , gender , major , year , language , building ;
int id , i;
public ScoutGUI() {
initComponents();
}
public ScoutGUI(int a) {
i = a;
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
panel1 = new java.awt.Panel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setFont(new java.awt.Font("Courier", 0, 13)); // NOI18N
jButton1.setText("NO");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setFont(new java.awt.Font("Courier", 0, 13)); // NOI18N
jButton2.setText("YES");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N
jLabel1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(204, 255, 153)));
javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addGap(71, 71, 71)
.addComponent(jButton1)
.addGap(94, 94, 94)
.addComponent(jButton2)
.addContainerGap(129, Short.MAX_VALUE))
.addGroup(panel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel1Layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap(68, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//skip and never
buttonpressActionPerformed();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//match and update
buttonpressActionPerformed();
}
private void buttonpressActionPerformed() {
// int i = 0;
Iterator<String> iterator = strings.iterator();
//for (String strin : strings)
while (iterator.hasNext())
{
//if (jButton2.isSelected() || jButton1.isSelected())
//{
jLabel1.setText(iterator.next());
//}
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ScoutGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ScoutGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ScoutGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ScoutGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ScoutGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private java.awt.Panel panel1;
// End of variables declaration
}
Your current code always overrides the current text in the JPanel, and it does that so fast, that you don't see it. Instead of using the Iterator, get the next item in the list by defining an int variable that gets incremented every press.
The index variable is a public int in this example:
jLabel1.setText(strings.get(index));
if (index < strings.size()-1)
index++;
No loops, that's everything needed in your method.
In order to locate next string from collection, you need somehow know about current item.
One approach is to store index (or iterator) in a field:
List<String> strings=<...>
// 1. store index
int sentenceIndex = 0;
// 2. store iterator. You could get ConcurrentModificationException if change list and then use iterator.
Iterator<String> iterator = strings.getIterator();
private void buttonpressActionPerformed() {
// 1. use index.
if (sentenceIndex < strings.size()-1) { // avoid IndexOutOfBoundException
String nextSentence = strings.get(sentenceIndex++);
}
// 2. use iterator
if (iterator.hasNext()) {
String nextSentence = iterator.next();
}
But in fact you don't need to store something:
// 3. calculate current index
String currentSentence = jLabel1.getText();
int currentIndex = strings.indexOf(currentSentence);
int nextIndex = incrementIndex(currentIndex);
String nextSentence = strings.get(nextIndex );
Note that I suggest new method incrementIndex. In it you could add not only lenght check but also jumping from last element to the first or just random selecting.
Each method has pro and contras:
index require boundary checks
iterator limits list updating
index calcucaliton also require boundary checks and label1 should have correct initial value
I would prefer storing index but it's your choice

Why can't a field name and a variable have same name?

I changed the variable name of a text field to name, then I wrote this in Netbeans IDE
`
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
name = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
name.setText("jTextField1");
name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nameActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(127, 127, 127)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(200, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(95, 95, 95)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(144, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String name=name.getText();
System.out.println(name);// TODO add your handling code here:
}
private void nameActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ss.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ss.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ss.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ss.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ss().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JTextField name;
// End of variables declaration
}`
There is an error when I declared String name=name.getText();
The error was "Cannot find symbol: Method getText"
Why did this happen and what are the ways to correct it?
You are calling the method getText() from the variable t1, which is of type String. String class doesn't have that method defined.
You can have a local variable with the same name as a field. But once the variable is declared, it shadows the field and you need to use this to reference it:
String Name = this.Name.getText();
Note: Java convention is for all variable names (besides constants) to begin with a lowercase character.
This is how the computer sees it.
Create a String variable called t1 and save into it the text value of a different variable also called t1.
You cannot assign the variable itself because the program hasn't fully executed that line of code yet. It does't know what t1 is.
I think this is what you were looking to do, but it will not work still because String has no method for .getText()
String t1 = "Hello";
String t2 = t2.getText(); // t2 will now have whatever t1 was saved with.

I would like to implement a "Find Menu" in my simple notepad application in java

I would like to implement a "Find Menu" in my simple notepad application in java but when I find a certain word,It just jumps up to the second similar word in the JTextArea, can anyone point out where I am wrong and how to furnish it? and I dont want to use Highlighter, just the select() method .. I would appreciate any help you can do. Im just new to programming.
/**
*
* #author aLwAyz
*/
public class FindDemo extends javax.swing.JDialog {
/**
* Creates new form FindDemo
*/
public FindDemo(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
dlgFind = new javax.swing.JDialog();
btnFind = new javax.swing.JButton();
txtInput = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
txaField = new javax.swing.JTextArea();
btnOpenFindDialog = new javax.swing.JButton();
dlgFind.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
btnFind.setText("Find");
btnFind.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFindActionPerformed(evt);
}
});
txtInput.setMinimumSize(new java.awt.Dimension(400, 100));
javax.swing.GroupLayout dlgFindLayout = new javax.swing.GroupLayout(dlgFind.getContentPane());
dlgFind.getContentPane().setLayout(dlgFindLayout);
dlgFindLayout.setHorizontalGroup(
dlgFindLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, dlgFindLayout.createSequentialGroup()
.addContainerGap(77, Short.MAX_VALUE)
.addComponent(txtInput, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(63, 63, 63)
.addComponent(btnFind)
.addGap(96, 96, 96))
);
dlgFindLayout.setVerticalGroup(
dlgFindLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(dlgFindLayout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(dlgFindLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnFind)
.addComponent(txtInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(28, Short.MAX_VALUE))
);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setModalExclusionType(null);
setModalityType(null);
txaField.setColumns(20);
txaField.setRows(5);
jScrollPane1.setViewportView(txaField);
btnOpenFindDialog.setText("Find");
btnOpenFindDialog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOpenFindDialogActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnOpenFindDialog)
.addGap(72, 72, 72))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(btnOpenFindDialog)
.addGap(35, 35, 35)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void btnOpenFindDialogActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
dlgFind.pack();
dlgFind.setLocationRelativeTo(null);
dlgFind.show();
}
private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String text = txtInput.getText();
String txa = txaField.getText();
int length = text.length();
String selected = txaField.getSelectedText();
int selIn = 0;
if (txaField.getSelectedText() != null) selIn = txa.indexOf(selected);
int inSelected = selIn + length;
if (txaField.getSelectedText() == null) inSelected = 0;
int index = txa.indexOf(text, inSelected);
if (txa.contains(text)) {
txaField.select(index, index + length);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(FindDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FindDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FindDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FindDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
FindDemo dialog = new FindDemo(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnFind;
private javax.swing.JButton btnOpenFindDialog;
private javax.swing.JDialog dlgFind;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea txaField;
private javax.swing.JTextField txtInput;
// End of variables declaration
}
That is my code. Im sorry if there are many redundancies because like I've said, im just new to programming. Thank You.
-By the way, I am using NetBeans IDE 8.0
-Sorry if it took me time
when I find a certain word,It just jumps up to the second similar word in the JTextArea,
When I try the code, the first time you press "Find" it selects the first occurrence of the word. Then if you press Find again it selects the second occurrence of the word. If you press "Find" again it stays on the second occurrence of the word.
So as I suggested in my comment you need to get rid of your "selection logic" and get the basic search working properly first.
Normally when you do a search you start the search from the caret position. This will allow you to continually press the "Find" button to move on to the next occurrence of the word. This works because when you "select" the found word, the caret is moved to the end of the word, so when you press "Find" the next time the caret postion is set at the end of the word, ready to search for the next word.

Java:taking result from List selection listenner

i've some problem with my list selection listener that i show you below
1.the result of the listener printing twice that i don't have an idea about it...!??!why it's printing twice?
2.when i pressing the searchBt and the result shows,and i choose one of the result i want to return ChooseIndex from the valueChanged(ListSelectionEvent e) but it can't has a return statement and the selected index of thge j list is useless...what's the problem?
public class SearchPage extends javax.swing.JFrame {
public SearchPage() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
SearchBox = new javax.swing.JTextField();
SearchBt = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
SearchBt.setText("Search");
SearchBt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SearchBtActionPerformed(evt);
}
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
jList1.setToolTipText("");
jList1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jList1.setSelectionBackground(new java.awt.Color(102, 0, 102));
jList1.setValueIsAdjusting(true);
jList1.setVerifyInputWhenFocusTarget(false);
jScrollPane1.setViewportView(jList1);
jList1.getAccessibleContext().setAccessibleName("");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 543, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(SearchBox, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(SearchBt, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(281, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(125, 125, 125)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SearchBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SearchBt))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void SearchBtActionPerformed(java.awt.event.ActionEvent evt) {
String tag = SearchBox.getText().trim();
Vector<String> vector = new Vector<String>();
for (int i = 0; i <Code.CodeSearch(tag).size(); i++) {
String string = Code.FNameExtractor(Code.CodeSearch(tag).get(i).getFileName())+" Uploaded By "+Code.CodeSearch(tag).get(i).getUserdetails().getUsername();
vector.add(string);
}
jList1 = new JList<String>(vector);
ListSelectionModel listSelectionModel = jList1.getSelectionModel();
listSelectionModel.addListSelectionListener(new SharedListSelectionHandler());
listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(jList1);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SearchPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SearchPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SearchPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SearchPage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SearchPage().setVisible(true);
}
});
}
class SharedListSelectionHandler implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
ListSelectionModel lsm = (ListSelectionModel)e.getSource();
int ChooseIndex =lsm.getMaxSelectionIndex();
System.out.println(ChooseIndex);
}
}
// Variables declaration - do not modify
private javax.swing.JTextField SearchBox;
private javax.swing.JButton SearchBt;
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
The selection listener only tells us the index of the selected item. That's normal. The list doesn't care about the content. You have to store the list model (iaw, a list of strings that you actually display) somewhere and use the index value from the listener to lookup the content at the index in your model. That's the common pattern.
For the first question - I'd set a breakpoint on the print statement, debug and look at the stacktrace. Then I'd see why the method was called twice.

Categories