I'm trying to update a JList. I have defined it to use a listModel. In that regard, it works fine because in my main() method I can add elements to the listModel and they will be reflected in the JList. However, I'm trying to force update it with new information by calling a function (below). This code does not work at all. Any help would be appreciated.
public void updateList(List<String> gamelist) {
listModel.removeAllElements();
for (int i=0;i<gamelist.size();i++) {
System.out.println(gamelist.get(i).toString());
listModel.addElement(gamelist.get(i).toString());
}
listGames.setModel(listModel);
}
public class Main extends javax.swing.JFrame {
/**
* Creates new form Main
*/
private javax.swing.JEditorPane editorWeb = new JEditorPane();
private DefaultListModel listModel = new DefaultListModel();
public Main() {
initComponents();
scrollWeb.setViewportView( editorWeb );
editorWeb.setEditable(false);
editorWeb.setSize(scrollWeb.getWidth(), scrollWeb.getHeight());
try {
editorWeb.setPage("http://www.futureretrogaming.tk/news.html");
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
listModel.addElement("test");
}
I think the problem is that I"m making a new main to return the value from my other form.
public class LoginWindow extends javax.swing.JFrame {
/**
* Creates new form LoginWindow
*/
List<String> games = new ArrayList<String>();
Main program = new Main();
public LoginWindow() {
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();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
textUsername = new javax.swing.JTextField();
textPassword = new javax.swing.JPasswordField();
buttonLogin = new javax.swing.JButton();
jLabel1.setText("Please provide your username and password:");
jLabel1.setToolTipText("");
jLabel2.setText("Username:");
jLabel3.setText("Password:");
buttonLogin.setText("Submit");
buttonLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonLoginActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textUsername))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(buttonLogin))
.addContainerGap(84, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(textUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
.addComponent(buttonLogin)
.addContainerGap())
);
pack();
}// </editor-fold>
private void buttonLoginActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
String loginurl = "http://futureretrogaming.tk/scripts/checklogin.php?username="+textUsername.getText()+"&password="+textPassword.getText();
System.out.println(loginurl);
URL checklogin = new URL(loginurl);
URLConnection yc = checklogin.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
URL file2 = new URL(loginurl);
Scanner sc2 = new Scanner(file2.openStream());
String inputLine = "";
int i = 0;
while (/*(inputLine = in.readLine()) != null*/sc2.hasNext()) {
inputLine = inputLine.trim();
String input = sc2.next();
input = input.trim();
if (inputLine.equalsIgnoreCase("false") || input.equalsIgnoreCase("false")) {
JOptionPane.showMessageDialog(this,"Username or Password is incorrect. Please try again.", "Error", JOptionPane.PLAIN_MESSAGE);
break;
}
else if (inputLine.equalsIgnoreCase("empty") || input.equalsIgnoreCase("empty")) {
JOptionPane.showMessageDialog(this,"You must type in a username and a password.", "Error",JOptionPane.PLAIN_MESSAGE);
break;
}
else {
System.out.println(input);
if (games == null)
System.out.print("games is null");
games.add(input);
}
}
in.close();
if (games!=null) {
games.remove(0);
Collections.sort(games);
program.updateList(games);
}
} catch (MalformedURLException ex) {
Logger.getLogger(LoginWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(LoginWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* #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(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LoginWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LoginWindow.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 LoginWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton buttonLogin;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPasswordField textPassword;
private javax.swing.JTextField textUsername;
// End of variables declaration
}
Related
I trying to read file in java. When click next button, how can I show second question when next button is clicked?
My .txt file content is like this
1. What is his name
A.John
B.David
2. How old is him?
A.24
B.27
So far I am able to display the first question in JTextField.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;
import java.io.FileReader;
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() throws IOException {
initComponents();
setLocationRelativeTo(null);
pack();
File file = new File("/home/xxx/Desktop/englishQuestion.txt");
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
if (line.equals("")) {
break;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
String result = sb.toString();
jTextArea1.setText(result);
}
/**
* 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();
textField1 = new java.awt.TextField();
label1 = new java.awt.Label();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Next");
textField1.setName("\"\""); // NOI18N
textField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textField1ActionPerformed(evt);
}
});
label1.setText("Answer:");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
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()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap())
);
label1.getAccessibleContext().setAccessibleName("Answer: ");
pack();
}// </editor-fold>
private void textField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(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() {
try {
new NewJFrame().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private java.awt.Label label1;
private java.awt.TextField textField1;
// End of variables declaration
}
I refactored the file lines to be like this:
q1 = What is his name? | John | David
q2 = How old is him? | 24 | 27
This way, each question information is in a single line and is easier to parse. You just have to load it as a property file and the q1 and q2 would be the keys, and what is after = would be the values. After that, split it by | or whatever you decide to use.
I refactored your code to look like this:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewJFrame extends javax.swing.JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private Properties props = new Properties();
private List<Question> questionList = new ArrayList<>();
private int currentQuestionIndex = -1;
private class Question {
private String question;
private String answer1;
private String answer2;
#Override
public String toString() {
return "Question [question=" + question + ", answer1=" + answer1 + ", answer2=" + answer2 + "]";
}
public Question(String question, String answer1, String answer2) {
this.question = question;
this.answer1 = answer1;
this.answer2 = answer2;
}
public String getQuestion() {
return question;
}
public String getAnswer1() {
return answer1;
}
public String getAnswer2() {
return answer2;
}
}
public void showNextQuestion() {
currentQuestionIndex++;
if (currentQuestionIndex >= questionList.size()) {
jTextArea1.setText("No more questions available.");
return;
}
jTextArea1.setText("");
Question currentQuestion = questionList.get(currentQuestionIndex);
String newLine = "\n";
jTextArea1.append(currentQuestion.getQuestion() + newLine);
jTextArea1.append("A. " + currentQuestion.getAnswer1() + newLine);
jTextArea1.append("B. " + currentQuestion.getAnswer2());
}
public NewJFrame() throws IOException {
initComponents();
setLocationRelativeTo(null);
pack();
Path path = Paths.get("/home/xxx/Desktop/englishQuestion.txt");
props.load(Files.newInputStream(path));
props.forEach((key, value) -> {
String v = (String) value;
System.out.println(v);
String[] token = v.split("\\|");
String question = token[0];
String answer1 = token[1];
String answer2 = token[2];
Question q = new Question(question, answer1, answer2);
questionList.add(q);
});
showNextQuestion();
}
/**
* 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();
textField1 = new java.awt.TextField();
label1 = new java.awt.Label();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Next");
jButton1.addActionListener(e -> {
showNextQuestion();
});
textField1.setName("\"\""); // NOI18N
textField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textField1ActionPerformed(evt);
}
});
label1.setText("Answer:");
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
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().addGap(0, 0, Short.MAX_VALUE)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 53,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 57,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 421,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup().addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 206,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap()));
label1.getAccessibleContext().setAccessibleName("Answer: ");
pack();
}// </editor-fold>
private void textField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args
* the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
// <editor-fold defaultstate="collapsed" desc=" Look and feel setting code
// (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the default
* look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(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() {
try {
new NewJFrame().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private java.awt.Label label1;
private java.awt.TextField textField1;
// End of variables declaration
}
Notice that I used a Properties object to load all the keys, and then for each of those lines, I parsed it and created a Question object and add it to a questionList. Also, notice the jButton1.addActionListener(e -> { showNextQuestion(); });. Call showNextQuestion(); method everytime you want the next question, in this case, every time to click the Next button.
I'm not sure what you want to acomplish with this application, is not clear yet, but I simply answered your question on how to show the next question.
First of all, your questions in the file should be in uniform format, I mean we should be able to distinguish between different question and it's options.
Secondly, then you read each question and it's options and store it in an Java Object. Let's say Question object.
Question object might be something like below:-
class Question {
String questionString;
String[] options;
}
Then, after you read each question/options and form an Object, you store these objects in a DoublyLinkedList, so you can easily navigate back and forth when user clicks Previous button or Next button.
I have a JFrame that simulates a simple celsius to fahrenheit converter.
What I'm trying to do is call the "convert" button action whenever the ENTER key es pressed.
I've tried defining the default button (but it doesn't work).
My code now looks like this:
public class TemperatureConverterGUI extends javax.swing.JFrame {
/**
* Creates new form TemperatureConverterGUI
*/
public TemperatureConverterGUI() {
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() {
button_convert = new javax.swing.JButton();
edittext = new javax.swing.JFormattedTextField();
label = new javax.swing.JLabel();
label_resultat = new javax.swing.JLabel();
resultat = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
button_convert.setText("Converteix");
button_convert.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button_convertActionPerformed(evt);
}
});
edittext.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
edittext.setHorizontalAlignment(javax.swing.JTextField.CENTER);
edittext.setToolTipText("Introdueix un número en Fahrenheit");
label.setText("Introdueix un número en Fahrenheit:");
label_resultat.setText("Resultat: ");
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(49, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(label_resultat)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(resultat))
.addComponent(button_convert)
.addComponent(label)
.addComponent(edittext, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(90, 90, 90))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(65, Short.MAX_VALUE)
.addComponent(label)
.addGap(12, 12, 12)
.addComponent(edittext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(31, 31, 31)
.addComponent(button_convert)
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(label_resultat)
.addComponent(resultat))
.addGap(70, 70, 70))
);
pack();
}// </editor-fold>
private void button_convertActionPerformed(java.awt.event.ActionEvent evt) {
int f = Integer.valueOf(edittext.getText());
int c = VisualTemperatureConverter.FahrenheitToCelsius(f);
resultat.setText(String.valueOf(c));
}
/**
* #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(TemperatureConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(TemperatureConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(TemperatureConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(TemperatureConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
**TemperatureConverterGUI frame = new TemperatureConverterGUI();
frame.button_convert.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0), "enter");
frame.button_convert.getActionMap().put("enter", frame.button_convert.getAction());**
frame.setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JButton button_convert;
private javax.swing.JFormattedTextField edittext;
private javax.swing.JLabel label;
private javax.swing.JLabel label_resultat;
private javax.swing.JLabel resultat;
// End of variables declaration
}
Nothing fancy needed, just add this to your edittext setup.
edittext.addActionListener((ae)-> button_convertActionPerformed(null));
I am developing a restaurant management system in Java Swing. I have displayed a list of checkboxes dynamically from databases which contains the names of mainstock (table names which contains mainstock items).I have added an ItemListener on each checkbox during the loop.
When I click each checkbox, it popups two JFrame. Why? How could I popup only one JFrame and insert required information?
package test;
public class test extends javax.swing.JFrame {
public static ArrayList<mdetails> list = new ArrayList<mdetails>();
public test() {
initComponents();
Connection con = (Connection) dbconnection.makeconnection();
String sql="select * from mainstock";
try{
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
String s2=rs.getString("stock_name");
JCheckBox cb = new JCheckBox("New CheckBox");
cb.setText(s2);
cb.setVisible(true);
cb.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
String name = cb.getActionCommand();
System.out.println(name);
JFrame frame = new JFrame(name);
int stock_id= rmsdao.givestockid(name);
System.out.println(stock_id);
String estimatedplate = JOptionPane.showInputDialog(frame, "Enter the estimated plate of 1 kg"+name);
if(estimatedplate!=null){
list.add(new mdetails(stock_id,estimatedplate));
}
else{
cb.setSelected(false);
}
}
});
jPanel1.add(cb);
jPanel1.validate();
}
con.close();
}
catch(Exception e){
System.out.println("not retrieving"+e);
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jButton1.setText("jButton1");
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)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(65, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(23, 23, 23))
.addGroup(layout.createSequentialGroup()
.addGap(129, 129, 129)
.addComponent(jButton1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(37, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)
.addComponent(jButton1)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
for (int a = 0; a < list.size(); a++) {
mdetails item = list.get(a);
System.out.println(item.getId());
// rmsdao.insert_menu_details(item.getId(),getitemid,item.getEstimate_plate());
}
}
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(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(test.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(test.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 test().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
I'm not sure what the problem with this code is but whenever I run it I get a java.lang.StackOverflowError. How would I fix it? This is what is displayed in the output console of netbeans:
run:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:222) at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:222)
at java.awt.Window.init(Window.java:497)
at java.awt.Window.<init>(Window.java:536)
at java.awt.Frame.<init>(Frame.java:420)
at java.awt.Frame.<init>(Frame.java:385)
at javax.swing.JFrame.<init>(JFrame.java:180)
code
import java.awt.Color;
import java.awt.Font;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Nicholas Ferretti
*/
public class Section2 extends javax.swing.JFrame {
Section2 s2Frame = new Section2();
Section3 s3Frame = new Section3();
ResultSet section2Questions;
DB connection = new DB();
/**
* Creates new form Section2Question1
*/
TimerFrame timerFrame;
int timeRemaining = 60;
int s2QuestionNumber = 1;
public Section2() {
this.timerFrame = new TimerFrame(this);
initComponents();
groupButton();
section2QuestionBox.setEditable(false);
s2QuestionNumberLabel.setText("Question "+s2QuestionNumber+":");
try {
section2Questions=connection.queryTbl("SELECT * FROM tblQuestions WHERE Section = 2");
section2Questions.next();
String firstQuestion = section2Questions.getString("Questions");
System.out.println(firstQuestion);
section2QuestionBox.setText(firstQuestion);
String firstAnswers = section2Questions.getString("AllPossibleAnswers");
Scanner scLine = new Scanner(firstAnswers).useDelimiter(",");
while(scLine.hasNext()){
String answer1 = scLine.next();
S2Answer1.setText(answer1);
System.out.println(answer1);
String answer2 = scLine.next();
S2Answer2.setText(answer2);
System.out.println(answer2);
String answer3 = scLine.next();
S2Answer3.setText(answer3);
System.out.println(answer3);
String answer4 = scLine.next();
S2Answer4.setText(answer4);
System.out.println(answer4);
}
} catch (SQLException ex) {
Logger.getLogger(Section1.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error with SQL firstQuestion");
}
/*boolean t = timerFrame.timer(Section2Timer, timeRemaining);
if(t == false){
JOptionPane.showMessageDialog(null, "Time up for section.");
s2Frame.setVisible(false);
//s3Frame.setVisible(true);
}*/
}
private void groupButton() {
ButtonGroup buttons = new ButtonGroup();
buttons.add(S2Answer2);
buttons.add(S2Answer3);
buttons.add(S2Answer1);
buttons.add(S2Answer4);
}
private void timer() {
try {
Score time = new Score();
int timeRemaining = time.getTime();
while(timeRemaining>0){
Section2Timer.setText(timeRemaining+"");
Section2Timer.setFont(new Font("Serif", Font.BOLD, 32));
Section2Timer.setForeground(Color.RED);
Thread.sleep(1000);
timeRemaining--;
if(timeRemaining==0){
time.setTime(60);
}
time.setTime(timeRemaining);
}
} catch (InterruptedException e) {
e.printStackTrace();
// handle the exception...
// For example consider calling Thread.currentThread().interrupt(); here.
}
}
/**
* 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() {
jLabel7 = new javax.swing.JLabel();
s2QuestionNumberLabel = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
section2QuestionBox = new javax.swing.JTextArea();
S2Answer1 = new javax.swing.JRadioButton();
S2Answer2 = new javax.swing.JRadioButton();
S2Answer3 = new javax.swing.JRadioButton();
S2Answer4 = new javax.swing.JRadioButton();
nextS2Question = new javax.swing.JButton();
Section2Timer = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel7.setFont(new java.awt.Font("Tahoma", 1, 36)); // NOI18N
jLabel7.setText("SECTION 2:");
s2QuestionNumberLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
s2QuestionNumberLabel.setText("QUESTION 1:");
jLabel9.setText("Answers:");
section2QuestionBox.setColumns(20);
section2QuestionBox.setRows(5);
section2QuestionBox.setText("At a conference, 12 memeber shook hands with each other \nbefore & after the meeting. How many total number of\nhand shakes occurred?");
jScrollPane3.setViewportView(section2QuestionBox);
S2Answer1.setText("Monday");
S2Answer1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
S2Answer1ActionPerformed(evt);
}
});
S2Answer2.setText("Tuesday");
S2Answer2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
S2Answer2ActionPerformed(evt);
}
});
S2Answer3.setText("Wednesday");
S2Answer3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
S2Answer3ActionPerformed(evt);
}
});
S2Answer4.setText("Friday");
S2Answer4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
S2Answer4ActionPerformed(evt);
}
});
nextS2Question.setText("Next");
nextS2Question.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextS2QuestionActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(125, 125, 125)
.addComponent(s2QuestionNumberLabel)))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(217, 217, 217)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(S2Answer1)
.addGap(53, 53, 53)
.addComponent(S2Answer2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 56, Short.MAX_VALUE)
.addComponent(S2Answer3)
.addGap(45, 45, 45)
.addComponent(S2Answer4))
.addComponent(nextS2Question, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGap(139, 139, 139)
.addComponent(Section2Timer, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Section2Timer, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, 0)
.addComponent(s2QuestionNumberLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(S2Answer1)
.addComponent(S2Answer2)
.addComponent(S2Answer3)
.addComponent(S2Answer4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 140, Short.MAX_VALUE)
.addComponent(nextS2Question)
.addGap(125, 125, 125))
);
pack();
}// </editor-fold>
String answer = "";
private void S2Answer1ActionPerformed(java.awt.event.ActionEvent evt) {
answer = S2Answer1.getText();
}
private void S2Answer2ActionPerformed(java.awt.event.ActionEvent evt) {
answer = S2Answer2.getText();
}
private void S2Answer3ActionPerformed(java.awt.event.ActionEvent evt) {
answer = S2Answer3.getText();
}
private void S2Answer4ActionPerformed(java.awt.event.ActionEvent evt) {
answer = S2Answer4.getText();
}
private void nextS2QuestionActionPerformed(java.awt.event.ActionEvent evt) {
Score score = new Score();
try {
String actualAnswer = section2Questions.getString("Answer");
int currentScore = score.getS2Score();
if(answer.equalsIgnoreCase(actualAnswer)){
currentScore+=5;
score.setS2Score(currentScore);
}
} catch (SQLException ex) {
Logger.getLogger(Section1.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error in Next Question method");
}
if(s2QuestionNumber ==4){
int timeLeft = score.getTime();
int currentBonusPoints = score.getBonusPoints();
score.setBonusPoints(timeLeft+currentBonusPoints);
s2Frame.setVisible(false);
s3Frame.setVisible(true);
}
try {
section2Questions.next();
String nextQuestion = section2Questions.getString("Questions");
section2QuestionBox.setText(nextQuestion);
s2QuestionNumber++;
s2QuestionNumberLabel.setText("Question "+s2QuestionNumber+":");
} catch (SQLException ex) {
Logger.getLogger(Section1.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error in Next Question method");
}
}
/**
* #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(Section2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Section2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Section2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Section2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Section2().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JRadioButton S2Answer1;
private javax.swing.JRadioButton S2Answer2;
private javax.swing.JRadioButton S2Answer3;
private javax.swing.JRadioButton S2Answer4;
private javax.swing.JLabel Section2Timer;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel9;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JButton nextS2Question;
private javax.swing.JLabel s2QuestionNumberLabel;
private javax.swing.JTextArea section2QuestionBox;
// End of variables declaration
}
The very first line in your class Section2 would cause the problem.
You have, Section2 s2Frame = new Section2();, which means, every time an object is created for Section2 you want to create another object of Section2 (which will create another object... and sooooooooo on...)
Hence the stackoverflow exception...
I have write a code to find a word in JTextPane. Problem here is when I enter a search word and click on search button it was highlight the all the occurrence of the given search word. I want to Highlight the first occurrence of the word then click on search button shows second occurrence of the way like that. Another one is it was not unHighlight the after search complete when click on text pane.
My code:
public class FindAWord extends javax.swing.JFrame {
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(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
// </editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MarkAll().setVisible(true);
}
});
}
Highlighter.HighlightPainter myHighLightPainter = new FindAWord.MyHighightPainter(
Color.LIGHT_GRAY);
// Variables declaration - do not modify
private javax.swing.JScrollPane scrollPane;
private javax.swing.JTextField searchText;
private javax.swing.JTextPane textPane;
private javax.swing.JButton search;
public FindAWord() {
initComponents();
}
public void removeHighLights(JTextComponent component) {
Highlighter hilet = component.getHighlighter();
Highlighter.Highlight[] highLites = hilet.getHighlights();
for (int i = 0; i < highLites.length; i++) {
if (highLites[i].getPainter() instanceof MarkAll.MyHighightPainter) {
hilet.removeHighlight(highLites[i]);
}
}
}
public void highLight(JTextComponent component, String patteren) {
try {
removeHighLights(component);
Highlighter hLite = component.getHighlighter();
Document doc = component.getDocument();
String text = component.getText(0, doc.getLength());
int pos = 0;
while ((pos = text.toUpperCase().indexOf(patteren.toUpperCase(),
pos)) >= 0) {
hLite.addHighlight(pos, pos + patteren.length(),
myHighLightPainter);
pos += patteren.length();
}
} catch (Exception e) {
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
search = new javax.swing.JButton();
searchText = new javax.swing.JTextField();
scrollPane = new javax.swing.JScrollPane();
textPane = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
search.setText("Search");
search.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchActionPerformed(evt);
}
});
scrollPane.setViewportView(textPane);
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(36, 36, 36)
.addComponent(search,
javax.swing.GroupLayout.PREFERRED_SIZE,
91,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(searchText,
javax.swing.GroupLayout.PREFERRED_SIZE,
120,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(114, Short.MAX_VALUE))
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup().addComponent(scrollPane)
.addContainerGap()));
layout.setVerticalGroup(layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(
layout.createParallelGroup(
javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(search)
.addComponent(
searchText,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(
javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scrollPane,
javax.swing.GroupLayout.DEFAULT_SIZE,
235, Short.MAX_VALUE)));
pack();
}// </editor-fold>
private void searchActionPerformed(java.awt.event.ActionEvent evt) {
if (searchText.getText().length() == 0) {
removeHighLights(textPane);
} else
highLight(textPane, searchText.getText());
}
class MyHighightPainter extends DefaultHighlighter.DefaultHighlightPainter {
MyHighightPainter(Color color) {
super(color);
}
}
}
If you need just to highlight one word you don't need all the addHighlight() and removeHighlight() calls.
Just figure out the word's offset (and length) and use setSelectionStart()/setSelectionEnd() method of the JTextPane passing the word start and start + length
UPDATE as requested the working code
import javax.swing.text.*;
import java.awt.*;
public class FindAWord extends javax.swing.JFrame {
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 (Exception ex) {
ex.printStackTrace();
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new FindAWord().setVisible(true);
}
});
}
Highlighter.HighlightPainter myHighLightPainter=new FindAWord.MyHighightPainter(Color.LIGHT_GRAY);
// Variables declaration - do not modify
private javax.swing.JScrollPane scrollPane;
private javax.swing.JTextField searchText;
private javax.swing.JTextPane textPane;
private javax.swing.JButton search;
public FindAWord() {
initComponents();
}
public void highLight(JTextComponent component,String patteren){
try {
Document doc=component.getDocument();
String text=component.getText(0,doc.getLength());
int pos=component.getCaretPosition();
if (pos==doc.getLength()) {
pos=0;
}
int index=text.toUpperCase().indexOf(patteren.toUpperCase(),pos);
if (index>=0) {
component.setSelectionStart(index);
component.setSelectionEnd(index+patteren.length());
component.getCaret().setSelectionVisible(true);
}
}
catch(Exception e){
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
search = new javax.swing.JButton();
searchText = new javax.swing.JTextField();
scrollPane = new javax.swing.JScrollPane();
textPane = new javax.swing.JTextPane();
searchText.setText("test");
textPane.setText("test qweqw test asdasdas test");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
search.setText("Search");
search.setFocusable(false);
search.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
searchActionPerformed(evt);
}
});
scrollPane.setViewportView(textPane);
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(36, 36, 36)
.addComponent(search, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(114, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(scrollPane)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(search)
.addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void searchActionPerformed(java.awt.event.ActionEvent evt) {
highLight(textPane, searchText.getText());
}
class MyHighightPainter extends DefaultHighlighter.DefaultHighlightPainter{
MyHighightPainter(Color color){
super(color);
}
}
}