Swing: JFormattedTextField set to numbers only using Netbeans - java

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.

Related

How to restore InputVerifier mechanism while using cancel button?

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

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

JDBC to JTable output query regarding making buttons work in GUI Editor for Netbeans

so, i'm working on a project where I have to use a search button to find user information from a jdbc database, and so far I've got some of the code to work and added fields and data to the database, but once i hit search in the jtextfield it doesn't display any data in the table. So, i'm wondering if someone can take a look at this code and tell me where the mistake is, the jbutton is supposed to connect to the mainframe where the database connection information is stored.
this is the main frame code:
package guestbook;
import java.sql.Connection;
import java.sql.DriverManager;
public class MainFrame extends javax.swing.JFrame {
public static String dbURL = "jdbc:derby://localhost:1527/Coolkidsclub;create=true;user=Vic";
public static Connection conn = null;
/**
* Creates new form MainFrame
*/
public MainFrame() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();//"org.apache.derby.jdbc.ClientDriver" to use derby driver
conn = DriverManager.getConnection(dbURL);
initComponents();
}
catch (Exception e){
}
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();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/guestbook/ckc.PNG"))); // NOI18N
jButton1.setText("Add Kid");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Update Kid");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Remove Kid");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setText("Find Kid");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(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(106, 106, 106)
.addComponent(jLabel1)
.addContainerGap(109, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(126, 126, 126)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4)
.addGap(130, 130, 130))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap(44, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
AddFrame add = new AddFrame();
add.setVisible(true);
this.dispose();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
UpdateFrame update = new UpdateFrame();
update.setVisible(true);
this.dispose();
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
RemoveFrame remove = new RemoveFrame();
remove.setVisible(true);
this.dispose();
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
SearchFrame search = new SearchFrame();
search.setVisible(true);
this.dispose();
}
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(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrame.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 MainFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
and this is the searchframe code:
package guestbook;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
public class SearchFrame extends javax.swing.JFrame {
public SearchFrame() {
initComponents();
}
public static DefaultTableModel buildTableModel(ResultSet rs)
throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
/**
* 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();
jTable1 = new javax.swing.JTable();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/guestbook/fckc.PNG"))); // NOI18N
jTextField1.setText("Type Name Here...");
jButton5.setText("Find Kid");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton6.setText("Go back to Start");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jTable2.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"", "", "", ""
}
));
jTable2.getTableHeader().setReorderingAllowed(false);
jScrollPane2.setViewportView(jTable2);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(113, 113, 113)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 518, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 383, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton5)))))
.addGroup(layout.createSequentialGroup()
.addGap(294, 294, 294)
.addComponent(jButton6)))
.addContainerGap(146, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton6)
.addContainerGap(58, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Statement stmt = MainFrame.conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from COOLKIDS " + jTextField1.getText().toString());
jTable2.setModel(buildTableModel(rs));//to display the table
} catch (Exception except) {
}
}
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
MainFrame main = new MainFrame();
main.setVisible(true);
this.dispose();
}
/**
* #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(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SearchFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SearchFrame.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 SearchFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
any help would be greatly appreciated as I'm relatively new to java.
EDIT: After a day or two I did a stackTrace exception printout and it says something about the statement stmt code being wrong do i just need to add a line in the searchframe to connect to the database and forget the mainframe connection?
So, i'm wondering if someone can take a look at this code and tell me where the mistake is, the jbutton is supposed to connect to the
mainframe where the database connection information is stored.
Well the first thing I can say is it's a lot of code. Now, there are several conceptual mistakes in your code that may lead to the stated problem.
Don't mix View (user interface) with Database connections
Beware that applications are tipically designed using layers or levels to isolate and separate responsibilities. In this case having a static Connection object within a JFrame simply breaks this principle. The first thing to do is separate database connection and logic from the user interface.
Don't ignore exceptions, always give them a correct treatment
This one of the worse things we can do:
try {
...
} catch (Exception e) {}
If an exception has been thrown it means that something unexpected happened. Just ignoring the exception in an empty catch block won't make it be solved but will hide this fact to us. Consequently we won't be able to solve the problem because we don't actually know that something wrong is heppening.
Avoid using static references
If you need to use a static to access a class member then it's probably there's a design problem in our code. While static fields are possible and sometimes useful (i.e.: define constants) from an OOP point of view they are not a good choice because break the encapsulation principle. We can just give access to a class member to the outside by providing getters and setters.
EDIT: After a day or two I did a stackTrace exception printout and it says something about the statement stmt code being wrong do i just
need to add a line in the searchframe to connect to the database and
forget the mainframe connection?
You would have to include the stack trace in your question, but let's take a look to the SQL query sent to the database:
ResultSet rs = stmt.executeQuery("select * from COOLKIDS " + jTextField1.getText().toString());
Most likely there is a WHERE clause missing in your SQL statmement (I don't know the text obtained from jTextField1 so it's just a guess). SQL statments tipically have this minimal structure:
SELECT fields list
FROM tables
WHERE conditions
On the other hand you might consider use PreparedStatement like this:
String sql = "SELECT * FROM coolkids WHERE name = ?";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, jTextField1.getText());
ResultSet rs = pst.executeQuery();
Once again, this code should be isolated from the UI and jTextField1 text should be passed as an argument to an appropriate Controller/Persistence layer class.

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