I have an InputVerifier on a JFormattedTextField. It is called when field looses focus perfectly. I added a cancel button (JButton), but do not want to call then InputVerifier when this button is clicked.
MyVerifier is called when the focus is lost on the field without any problem. However, after I click the clearButton the InputVerifier won´t be called again, as if the button where clicked even if it´s not.
The complete code is:
public class DemoFrame extends javax.swing.JFrame {
/** Creates new form DemoFrame */
public DemoFrame() {
initComponents();
name.setValue("");
name.setInputVerifier(new MyVerifier());
clear.setVerifyInputWhenFocusTarget(false);
}
private class MyVerifier extends javax.swing.InputVerifier {
public boolean verify(javax.swing.JComponent input) {
System.out.println("Field is being verified");
return true;
}
public boolean shouldYieldFocus(javax.swing.JComponent input) {
return verify(input);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
name = new javax.swing.JFormattedTextField();
clear = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
name.setText(" ");
clear.setText("clear");
clear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(231, Short.MAX_VALUE)
.addComponent(clear)
.addGap(112, 112, 112))
.addGroup(layout.createSequentialGroup()
.addGap(116, 116, 116)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(156, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 90, Short.MAX_VALUE)
.addComponent(clear)
.addGap(73, 73, 73))
);
pack();
}// </editor-fold>
private void clearActionPerformed(java.awt.event.ActionEvent evt) {
name.setValue(null);
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DemoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DemoFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton clear;
private javax.swing.JFormattedTextField name;
// End of variables declaration
}
Why isn't the InputVerifier been invoked if the field looses focus without the button being clicked?
Well. I found the solution.
clear.setFocusable(false);
That solves the problem.
Related
I changed the variable name of a text field to name, then I wrote this in Netbeans IDE
`
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
name = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
name.setText("jTextField1");
name.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nameActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(127, 127, 127)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(200, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(95, 95, 95)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(144, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String name=name.getText();
System.out.println(name);// TODO add your handling code here:
}
private void nameActionPerformed(java.awt.event.ActionEvent evt) {
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ss.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ss.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ss.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ss.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ss().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JTextField name;
// End of variables declaration
}`
There is an error when I declared String name=name.getText();
The error was "Cannot find symbol: Method getText"
Why did this happen and what are the ways to correct it?
You are calling the method getText() from the variable t1, which is of type String. String class doesn't have that method defined.
You can have a local variable with the same name as a field. But once the variable is declared, it shadows the field and you need to use this to reference it:
String Name = this.Name.getText();
Note: Java convention is for all variable names (besides constants) to begin with a lowercase character.
This is how the computer sees it.
Create a String variable called t1 and save into it the text value of a different variable also called t1.
You cannot assign the variable itself because the program hasn't fully executed that line of code yet. It does't know what t1 is.
I think this is what you were looking to do, but it will not work still because String has no method for .getText()
String t1 = "Hello";
String t2 = t2.getText(); // t2 will now have whatever t1 was saved with.
I would like to implement a "Find Menu" in my simple notepad application in java 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.
I use NetBeans IDE, as you may know there is a JFrame creator plugin (Its pre-installed) I use it to make JFrames (Because I'm too lazy to do it my self =/). in the event of creating a button within that JFrame it will generate a area for the event code. I was wondering what code i need to type in to generate the Alert Dialog. Heres what is pre-generated upon create a swing/awt component or a JFrame:
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jDialog2 = new javax.swing.JDialog();
jButton1 = new javax.swing.JButton();
javax.swing.GroupLayout jDialog2Layout = new javax.swing.GroupLayout(jDialog2.getContentPane());
jDialog2.getContentPane().setLayout(jDialog2Layout);
jDialog2Layout.setHorizontalGroup(
jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jDialog2Layout.setVerticalGroup(
jDialog2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle(">:D");
setResizable(false);
addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
formAncestorMoved(evt);
}
public void ancestorResized(java.awt.event.HierarchyEvent evt) {
}
});
jButton1.setText("Press Me :D");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//This is the area for the code dialog code
}
private void formAncestorMoved(java.awt.event.HierarchyEvent 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
}
});
}
Did you see the Button1ActionPerformed thing????
that's where the code goes.
I need code that will create a new Alert Dialog (javax.swing.JDialog)
When that is pressed.
Thanks in advance
Sounds like you might want a JOptionPane message dialog...
Try this:
JOptionPane.showMessageDialog(null, "<your message here...>", "Alert", JOptionPane.ERROR_MESSAGE);
So for your case, this is what your action performed method will look like:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JOptionPane.showMessageDialog(null, "<your message here...>", "Alert", JOptionPane.ERROR_MESSAGE);
}
Note there is no "variable" to store the JOptionPane object, it's a static method called on the JOptionPane class. Each time you want an alert/confirm/input/etc. dialog, you generate one on the fly using the static members of the JOptionPane class.
See the reference for more info...
This is what i see
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
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() {
jOptionPane1 = new javax.swing.JOptionPane();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle(">:D");
setResizable(false);
addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
formAncestorMoved(evt);
}
public void ancestorResized(java.awt.event.HierarchyEvent evt) {
}
});
jButton1.setText("Press Me :D");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 45, Short.MAX_VALUE)
.addComponent(jOptionPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 46, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jOptionPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//jOptionPane.showMessageDialog(null, "<your message here...>", "Alert", jOptionPane.ERROR_MESSAGE);
}
private void formAncestorMoved(java.awt.event.HierarchyEvent 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JOptionPane jOptionPane1;
// End of variables declaration
}
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.
I have a jTextField, and when I want to type something in it, I want it to be displayed.
I used the jTextField1KeyTyped event.
but the problem is when I press some text the console shows me the text from the jTextField minus the last char.
for example if I typed "abcde", it will show me only "abcd".
how can I resolve this issue.
EDIT :
this is my project :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Personel;
/**
*
* #author aimad
*/
public class SelectionArticle extends javax.swing.JFrame {
/**
* Creates new form SelectionProduit
*/
public SelectionArticle() {
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() {
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jLabel1.setText("jLabel1");
jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextField1KeyTyped(evt);
}
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextField1KeyPressed(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(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, 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 jTextField1KeyTyped(java.awt.event.KeyEvent evt) {
System.out.println("Key typed : " + jTextField1.getText());
}
/**
* #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(SelectionArticle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SelectionArticle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SelectionArticle.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SelectionArticle.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 SelectionArticle().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
add DocumentListener instead of KeyListener to JTextComponent
then you can to listening for string inserted, removed or replaced whole String in JTextComponent, otherwise all mentioned events aren't possible to catch by KeyListener