Iterating through List but it only shows last item - java

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

Related

Java - How to make a form return a value?

Bear in mind I'm a complete (2 weeks) java beginner, and might need things explained as if to a three year old.
I've created a form which is called by the main class. It calls an arrayList of six objects from another class and displays the first four values on buttons.
The sixth item is a string 'qText' displayed on a text pane, while the fifth isn't displayed. So far so good.
pressing the a button should assign a value of 0, 1, 2, or 3 to variable 'qans'.
I would like to be able to check whether 'qans' has the same value as variable 'ans' and return either an int or bool to the main class.
package lp2;
import java.util.ArrayList;
/**
*
* #author david
*/
public class form extends javax.swing.JFrame {
ArrayList set = methods.getquestion();
int a = (int) set.get(0);
int b = (int) set.get(1);
int c = (int) set.get(2);
int d = (int) set.get(3);
int ans = (int) set.get(4);
int qans;
int check = (int) set.get(qans);
String qText = (String) set.get(5);
String stringA = String.valueOf(a);
String stringB = String.valueOf(b);
String stringC = String.valueOf(c);
String stringD = String.valueOf(d);
String stringAns = String.valueOf(ans);
/**
* Creates new form form
*/
public form() {
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() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
btnA = new javax.swing.JButton();
btnB = new javax.swing.JButton();
btnC = new javax.swing.JButton();
btnD = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setEditable(false);
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
jTextArea1.setRows(5);
jTextArea1.setText(qText);
jScrollPane1.setViewportView(jTextArea1);
btnA.setText(stringA);
btnA.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAActionPerformed(evt);
}
});
btnB.setText(stringB);
btnB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBActionPerformed(evt);
}
});
btnC.setText(stringC);
btnC.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCActionPerformed(evt);
}
});
btnD.setText(stringD);
btnD.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnA, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnB, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnC, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnD, javax.swing.GroupLayout.PREFERRED_SIZE, 350, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(28, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnA, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnB, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnC, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnD, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 54, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnAActionPerformed(java.awt.event.ActionEvent evt) {
int qans =0;
}
private void btnBActionPerformed(java.awt.event.ActionEvent evt) {
int qans = 1; // TODO add your handling code here:
}
private void btnCActionPerformed(java.awt.event.ActionEvent evt) {
int qans = 2; // TODO add your handling code here:
}
private void btnDActionPerformed(java.awt.event.ActionEvent evt) {
int qans = 3; // 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(form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(form.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 form().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnA;
private javax.swing.JButton btnB;
private javax.swing.JButton btnC;
private javax.swing.JButton btnD;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}
Suggestions:
If you want a window, one that does not represent the main application (here your "main class" whatever that is) to return a value, then don't use a JFrame which can never be used in a modal fashion but rather use a modal dialog such as via a modal JDialog.
For this and many other reasons, you should avoid have your GUI classes extend top-level windows such as JFrame (or JDialog for that matter). Instead have your GUI classes produce JPanes, and these can be placed into the top level window that is most appropriate for your need.
You're shadowing your qans variable, so that the field will never change, no matter what button is pushed, meaning you're re-declaring the variable within a method or constructor, and thus creating and setting the state (assigning a value to ) a local variable, and doing this will not change the state of the class instance field. The solution is not to re-declare the variable. So in the action performed methods, change int qans = 1; to qans = 1;, and likewise for all the other similar bits of code.
Take a look at both JFileChooser and JOptionPane, which are both 'forms' ('windows' in java terminology) but return their value in different ways.
JOptionPane has a static method that shows the dialog, waits until it's done, and returns the result immediately.
JFileChooser works by creating an instance (like you do), making it visible (like you do), waits until its done, and after its done you can interrogate the object by invoking 'getter' methods (ask different types of results)
You can mimic either of these but the second is more powerful.
The waiting-until-done part is handled automatically for you if you use a JDialog instead of JFrame.
Some terminology to get you up to speed:
Window - every separate GUI you can make
Frame - a window with title bar, close button, etc
Dialog - a frame which is 'modal'
Modal - means it blocks execution of whatever made it visible, until it is made invisible
getter - a method that returns a field: like public int getQans() { return qans; }
field - a variable defined in the class (your qans, set, etc.)

How to sort item in java combobox [duplicate]

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.

Swing: JFormattedTextField set to numbers only using Netbeans

I've got a little problem with JFormattedTextField:
I want to set the formatted text fields to numbers only. I've created one with Swing interface on NetBeans.
My code is as follows:
package SerasApp;
import static java.lang.System.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFormattedTextField;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
import javax.swing.text.NumberFormatter;
/**
* #author adam
*/
public class Main extends javax.swing.JFrame {
/**
* Creates new form Main
*/
public Main() {
initComponents();
}
//set position of label to be the center of the frame
public void PositionHiSera()
{
//find position of jpanel
int FrameHeight = this.Intro.getHeight();
int FrameWidth = this.Intro.getWidth();
int LabelSize[] = new int[2];
LabelSize[0] = HiSera.getWidth();
LabelSize[1] = HiSera.getHeight();
out.println(LabelSize[0]);
out.println(LabelSize[1]);
int Origin[] = new int[2];
Origin[1] = (FrameHeight/2)-(LabelSize[0]/2);
Origin[0] = (FrameWidth/2)-(LabelSize[1]/2);
//set label origin
HiSera.setLocation(Origin[1], Origin[0]);
}
public void HumidityLevel()
{
NumberFormat a = NumberFormat.getNumberInstance();
NumberFormatter b = new NumberFormatter(a);
DefaultFormatterFactory c = new DefaultFormatterFactory(b);
humidityLevel.setFormatterFactory(c);
}
/**
* 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() {
MainDisplayFrame = new javax.swing.JPanel();
Intro = new javax.swing.JPanel();
HiSera = new javax.swing.JLabel();
MainMenu = new javax.swing.JPanel();
WeatherOptions = new javax.swing.JPanel();
sunny = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
humidityLevel = new javax.swing.JFormattedTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowFocusListener(new java.awt.event.WindowFocusListener() {
public void windowGainedFocus(java.awt.event.WindowEvent evt) {
formWindowGainedFocus(evt);
}
public void windowLostFocus(java.awt.event.WindowEvent evt) {
}
});
MainDisplayFrame.setLayout(new java.awt.CardLayout());
Intro.setMaximumSize(new java.awt.Dimension(30000, 30000));
HiSera.setText("Hi Sera");
javax.swing.GroupLayout IntroLayout = new javax.swing.GroupLayout(Intro);
Intro.setLayout(IntroLayout);
IntroLayout.setHorizontalGroup(
IntroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(IntroLayout.createSequentialGroup()
.addGap(209, 209, 209)
.addComponent(HiSera)
.addContainerGap(243, Short.MAX_VALUE))
);
IntroLayout.setVerticalGroup(
IntroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(IntroLayout.createSequentialGroup()
.addGap(225, 225, 225)
.addComponent(HiSera)
.addContainerGap(258, Short.MAX_VALUE))
);
MainDisplayFrame.add(Intro, "card2");
javax.swing.GroupLayout MainMenuLayout = new javax.swing.GroupLayout(MainMenu);
MainMenu.setLayout(MainMenuLayout);
MainMenuLayout.setHorizontalGroup(
MainMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, Short.MAX_VALUE, Short.MAX_VALUE)
);
MainMenuLayout.setVerticalGroup(
MainMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
);
MainDisplayFrame.add(MainMenu, "card2");
WeatherOptions.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
WeatherOptionsFocusGained(evt);
}
});
sunny.setText("Sunny");
sunny.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sunnyActionPerformed(evt);
}
});
jButton2.setText("Overcast");
jButton3.setText("Rainy");
jLabel1.setText("Humidity Level");
javax.swing.GroupLayout WeatherOptionsLayout = new javax.swing.GroupLayout(WeatherOptions);
WeatherOptions.setLayout(WeatherOptionsLayout);
WeatherOptionsLayout.setHorizontalGroup(
WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(WeatherOptionsLayout.createSequentialGroup()
.addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(WeatherOptionsLayout.createSequentialGroup()
.addGap(81, 81, 81)
.addComponent(sunny)
.addGap(75, 75, 75))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, WeatherOptionsLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(36, 36, 36)))
.addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(humidityLevel, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(WeatherOptionsLayout.createSequentialGroup()
.addComponent(jButton2)
.addGap(69, 69, 69)
.addComponent(jButton3)))
.addContainerGap(99, Short.MAX_VALUE))
);
WeatherOptionsLayout.setVerticalGroup(
WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(WeatherOptionsLayout.createSequentialGroup()
.addGap(225, 225, 225)
.addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sunny)
.addComponent(jButton2)
.addComponent(jButton3))
.addGap(87, 87, 87)
.addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(humidityLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(132, Short.MAX_VALUE))
);
MainDisplayFrame.add(WeatherOptions, "card2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(MainDisplayFrame, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(MainDisplayFrame, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
PositionHiSera();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//make Intro Disappear and make Weather Options Appear
WeatherOptions.setVisible(true);
Intro.setVisible(false);
HumidityLevel();
out.println("tests");
}
private void sunnyActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void WeatherOptionsFocusGained(java.awt.event.FocusEvent 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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.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 Main().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel HiSera;
private javax.swing.JPanel Intro;
private javax.swing.JPanel MainDisplayFrame;
private javax.swing.JPanel MainMenu;
private javax.swing.JPanel WeatherOptions;
private javax.swing.JFormattedTextField humidityLevel;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JButton sunny;
// End of variables declaration
}
I've tried also to set a humidityLevel to new formatted text field to no avail.
Mainly it's this bit of code:
public void HumidityLevel()
{
NumberFormat a = NumberFormat.getNumberInstance();
NumberFormatter b = new NumberFormatter(a);
DefaultFormatterFactory c = new DefaultFormatterFactory(b);
humidityLevel.setFormatterFactory(c);
}
and this bit:
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
PositionHiSera();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//make Intro Disappear and make Weather Options Appear
WeatherOptions.setVisible(true);
Intro.setVisible(false);
HumidityLevel();
out.println("tests");
}
I also don't want to use a JTextField because I want to learn how to use JFormattedTextField.
I want to set the formatted text fields to numbers only.
Using the Design view, right click over the formatted text field and choose Properties option. Then look for formatterFactory property:
If you try to edit this property, the following dialog will show up. Choose integer default option under number category:
That's it, your text field will be initialized using NumberFormat.getIntegerInstance(). If you inspect the generated source code you'll see something like this:
jFormattedTextField1 = new javax.swing.JFormattedTextField();
jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(java.text.NumberFormat.getIntegerInstance())));
Off-topic
As #mKorbel pointed out, using Thread.sleep() is a bad idea and will block the Event Dispatch Thread (EDT) which is a single and special thread where Swing components creation / update should be performed and event handling is processed. If this thread is blocked then your GUI won't be able to repaint itself and will "freeze". In this case you should consider use a Swing Timer instead. See Concurrency in Swing for further details.

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