How to correctly update AbstractTableModel with fireTableDataChanged()? - java

I'm still struggling with a JTable that should be automatically updated.
The situation is as follows:
I instantiate MyTable (extends JTable), and set it in my UI class (MyView). The MyTable class takes the UI class and an instance of the class that contains logic as parameters):
...
private JPanel createTablePanel() {
tablePanel = new JPanel();
myTable = new MyTable(this,mymeth);
setMyTable(myTable);
JScrollPane scrollPane = new JScrollPane(getMyTable());
tablePanel.add(scrollPane);
return tablePanel;
}
MyTable itself looks like below. An extension of AbstractTableModel (MyTableModel) is set to it. An extension of TableModelListener is set to the model. And finally an extension of ListSelectionListener is set to the model's SelectionModel.
public class MyTable extends JTable implements TableModelListener
{
public MyTable(MyView myView, MyMethods mymeth)
{
AbstractTableModel tableModel = new MyTableModel(mymeth);
setModel(tableModel);
getModel().addTableModelListener(new MyTableModelListener());
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setCellSelectionEnabled(true);
getColumnModel().getSelectionModel().addListSelectionListener(new MyTableSelectionListener(this, mymeth, myView));
setPreferredScrollableViewportSize(this.getPreferredSize());
}
}
Let's have a quick look at the model's constructor.
public MyTableModel(MyMethods mymeth) {
dataObject = new MyData(mymeth);
myData = dataObject.getMyData();
colTitles = dataObject.getColTitles();
}
MyData compiles the data for the table: A Vector<Vector<Object>>, that consists of three Vector<Object>s (the table data) and a String[] (The column titles). The data itself comes from a graph via mymeth, the logic class' instance.
Whenever a table column is clicked, a popup (i.e. JOptionPane) object is instantiated, which presents a selection of values for the 3rd row in the selected column. The user chooses a value and the value is set to the data model. Note the way the table is updated after that.
public MyOptionPane(int i, MyMethods mymeth, MyView myView) {
this.view = myView;
String sourceString = mymeth.getSourceString(i); // Gets a String from a
String[]. In this Array, the order is the same as in the table.
String tag = null;
tag = (String) JOptionPane.showInputDialog(this, "Choose a tag for \"" + sourceString + "\"", "String tagging" , JOptionPane.PLAIN_MESSAGE, null, myView.getTags().toArray(), myView.getTags().get(0));
mymeth.setTag(i, tag);
// This is where fireTableDataChanged() didn't work, but this did
MyTableModel model = new MyTableModel(mymeth); // New model instance
view.getMyTable().setModel(model); // reset new model to table
}
This works. However, from what I've read I shold be able to simply call fireTableDataChanged() on the model and the table should update itself. However, this doesn't work. User kleopatra has commented to an answer in a previous post:
do not call any of the model's fireXX methods from any code external to the model.
Instead implement the model to do so when anything changed
So: Can I call fireTableDataChanged() within such a structure at all? And if so, where and how?
Thanks in advance for all pieces of enlightenment!

from what I've read I shold be able to simply call fireTableDataChanged() on the model and the table should update itself
Your program doesn't invoke the fireXXX methods on the model. The TableModel itself is responsible for invoking these methods whenever any of the data in the model is changed. Look at the Creating a Table Model example from the Swing tutorial. The setValueAt(...) method shows how to invoke the appropriate fireXXX method.
If you create a completely new TableModel, then you need to use the setModel() method.
Kleopatra's comment was that all fireXXX methods showed be invoked from within the TableModel class itself. If you want to understand how this is done, then take a look at the source code for the DefaultTableModel. If has example of when you would invoke the fireTableDataChanged() method along with the other fireXXX methods.

You shouldn't have to replace the entire model to update a single row. Instead, update the affected cell(s) and let setValueAt() fire the required event, as shown here. Alternatively, this related example uses a DefaultTableModel that handles the events for you, as suggested by #mKorbel & #camickr.
If you stay with AbstractTableModel, consider List<List<MyData>>, unless you need Vector for some other reason.

not to answer to your question, suggestion about using DefaultTableModel
if you don't need to something to restrict for JTable, really good reason, then you couldn't to use AbstractTableModel, best job is still if you'd implement DefaultTableModel, by using DefaultTableModel you'll never to care about that, which of FireXxxXxxChanged() you have to use for each from setXxx() methods,

Here is a simple program that has an ArrayList of Person, populates a table with data from the ArrayList and updates AbstractTableModel with fireTableDataChanged(). Hope this helps
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
/**
*
* #author razak
*/
public class Table extends javax.swing.JFrame {
ArrayList<Person> records; //arrayList of persons
AbstractTable tableModel; //table model --inner class
/**
* Creates new form Table
*/
public Table() {
records = new ArrayList<>();
tableModel = new AbstractTable(records);
addData();
initComponents();
recordTable.setModel(tableModel);
}
/**
* Adds test values to the table
*/
private void addData() {
records.add(new Person("Tester", 21));
records.add(new Person("Kofi", 20));
records.add(new Person("Razak", 251));
records.add(new Person("Joseph", 21));
}
/**
* 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();
recordTable = new javax.swing.JTable();
nameLabel = new javax.swing.JLabel();
ageLabel = new javax.swing.JLabel();
nameTextField = new javax.swing.JTextField();
ageTextField = new javax.swing.JTextField();
addButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
recordTable.setModel(tableModel);
jScrollPane1.setViewportView(recordTable);
nameLabel.setText("Name");
ageLabel.setText("Age");
addButton.setText("Add");
addButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(52, 52, 52)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(nameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(ageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(ageTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(66, 66, 66)
.addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(39, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(16, 16, 16)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(nameLabel)
.addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ageLabel)
.addComponent(ageTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addComponent(addButton)
.addGap(18, 18, 18)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* When add button is clicked
*
* #param evt
*/
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String name = nameTextField.getText();
int age = Integer.parseInt(ageTextField.getText());
records.add(new Person(name, age));
tableModel.fireTableDataChanged();
}
/**
* Inner class
*/
class AbstractTable extends AbstractTableModel {
String col[]; //column names
ArrayList<Person> data; //arrayList to populate table
AbstractTable(ArrayList<Person> record) {
this.col = new String[]{"Name", "Age"};
data = record;
}
//get number of records
#Override
public int getRowCount() {
return data.size();
}
//get number of columns
#Override
public int getColumnCount() {
return col.length;
}
//get a value form the table
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Person person = data.get(rowIndex);
if (columnIndex == 0) {
return person.getName();
} else if (columnIndex == 1) {
return person.getAge();
}
return null;
}
//set value at a particular cell
public void setValueAt(Person person, int row, int column) {
data.add(row, person);
fireTableCellUpdated(row, column);
}
//get column name
public String getColumnName(int column) {
return col[column];
}
}
/**
* #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(Table.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Table.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Table.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Table.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 Table().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton addButton;
private javax.swing.JLabel ageLabel;
private javax.swing.JTextField ageTextField;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel nameLabel;
private javax.swing.JTextField nameTextField;
private javax.swing.JTable recordTable;
// End of variables declaration
}
/**
* Person class
* #author razak
*/
public class Person {
private final String name; //name
private final int age; //age
//constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//return name
public String getName() {
return name;
}
//returns age
public int getAge() {
return age;
}
}

Related

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

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.)

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.

How to save edited JTable data to database?

First of all sorry for my poor English. I'll try my best to understand you my problem.
All I want is to save the new data whichever user has entered in the JTable whenever Save button will clicked.
I am retrieving Student ID, Name in first two columns from database and also i have added current date in third column and Absent/Present as fourth column which is editable. I have following code to retrieve data from database.
**Attendance.java** :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Vector;
/**
*
* #author Admin
*/
public class Attendance{
Connection con = Connectdatabase.ConnecrDb();
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
String d1 = fromUser.format(sqlDate);
String d = d1.toString();
public Vector getEmployee()throws Exception
{
Vector<Vector<String>> employeeVector = new Vector<Vector<String>>();
PreparedStatement pre = con.prepareStatement("select studentid,name from student");
ResultSet rs = pre.executeQuery();
while(rs.next())
{
Vector<String> employee = new Vector<String>();
employee.add(rs.getString(1)); //Empid
employee.add(rs.getString(2));//name
employee.add(d);
employeeVector.add(employee);
}
if(con!=null)
con.close();
rs.close();
pre.close();
return employeeVector;
}
}
**AttendanceGUI.java : **
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package shreesai;
import static java.awt.Frame.MAXIMIZED_BOTH;
import java.sql.Connection;
import java.util.Vector;
import javax.swing.JOptionPane;
/**
*
* #author Admin
*/
public class AttendanceGUI extends javax.swing.JFrame {
/**
* Creates new form AttendanceGUI
*/
Connection con = Connectdatabase.ConnecrDb();
private Vector<Vector<String>> data;
private Vector<String> header;
public AttendanceGUI() throws Exception {
this.setLocationRelativeTo(null);
setExtendedState(MAXIMIZED_BOTH);
Attendance att = new Attendance();
data = att.getEmployee();
header = new Vector<String>();
header.add("Student ID");
header.add("Student Name");
header.add("Date");
header.add("Absent/Present");
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();
AttendanceT = new javax.swing.JTable();
SaveAtt = new javax.swing.JButton();
Exit = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
AttendanceT.setModel(new javax.swing.table.DefaultTableModel(
data,header
)
{public boolean isCellEditable(int row, int column){return true;}}
);
AttendanceT.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(AttendanceT);
tca.adjustColumns();
AttendanceT.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jScrollPane1.setViewportView(AttendanceT);
SaveAtt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/save.png"))); // NOI18N
SaveAtt.setText("Save Attendance");
SaveAtt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveAttActionPerformed(evt);
}
});
Exit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exit.png"))); // NOI18N
Exit.setText("Exit");
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.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(SaveAtt, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(176, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SaveAtt, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void SaveAttActionPerformed(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(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AttendanceGUI.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() {
try{
new AttendanceGUI().setVisible(true);
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JTable AttendanceT;
private javax.swing.JButton Exit;
private javax.swing.JButton SaveAtt;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
This output I get when I run JFrame :
Now, What I want actually is whenever user will edit data into JTable just like in the following Image :
****After clicking Save Attendance button the current JTable values should entered into the database. I am using Sqlite database which is addon in Firefox. I have created attendance table in my database which is having studentid integer, name varchar, date DATETIME, and preab VARCHAR(This to store whether particular student was present or absent) ****
I hope that you get what my problem is. Thanks in advance.
As you are using DefaultTableModel you have to register a listener to that model a TableModelListener listening for changes. How to use TableModelListener
Example:
myTable.getModel().addTableModelListener(new TableModelListener(){
#Override
public void tableChanged(TableModelEvent evt){
//code here
}
});
public void happi(String name, String age, String id){
//this method should be located on a class, then you just instantiate the class in the main form
String query=null;
try{
query = "update tbltest set name = '"+name+"',age = '"+age+"' where id = '"+id+"'";
stmt.executeUpdate(query);
}
catch(Exception ex){JOptionPane.showMessageDialog(null,""+ex);}
finally{
super.closeConnection(connect);
super.closeStatement(stmt);
}
}//end of happi
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//a button with event ActionPerformed (save button)
table.updateUI();
}//end
private void tablePropertyChange(java.beans.PropertyChangeEvent evt) {
// a JTablenamed"table"
try{
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
int c = table.getColumnCount();
DBHandler dbh = new DBHandler();
dbh.happi((table.getModel().getValueAt(row, 0).toString()), (table.getModel().getValueAt(row, 1).toString()), (table.getModel().getValueAt(row, 2).toString()));
}catch(Exception e){}
} '

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