java netbeans doesn't work from constructor - java

My code under this text.My goal i have a text like this:
drunk//pepsi
drunk//cola
snacks//chips
tools//key
so on..
Firstly read all row by the readline.Before // ones to JLİST1.After // ones to JList2.When i try to run Program stuck.I think problem from constructor.How can i fix this.Ty for help
/*
* 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.
*/
package finalcalismasi1;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
/**
*
* #author TOSHIBA
*/
class product{
public String Group;
public String Name;
}
public class vizesorusudeneme extends javax.swing.JFrame {
ArrayList<product> productum=new ArrayList<product>();
DefaultListModel model1=new DefaultListModel();
DefaultListModel model2=new DefaultListModel();
public vizesorusudeneme() {
initComponents();
try{
Charset.forName("ISO-8859-9");
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("stok1.txt")));
String line=br.readLine();
while(line!=null){
String[] urun=line.split("//");
product pr=new product();
pr.Group=urun[0];
pr.Name=urun[1];
productum.add(pr);
}
for(int i=0;i<productum.size();i++){
if(model1.indexOf(productum.get(i).Group)==-1){
model1.addElement(productum.get(i).Group);
}
}
jList1.setModel(model1);
}
catch(Exception e){
}
}
/**
* 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();
jList1 = new javax.swing.JList<>();
jScrollPane2 = new javax.swing.JScrollPane();
jList2 = new javax.swing.JList<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
jScrollPane2.setViewportView(jList2);
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(28, 28, 28)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(105, 105, 105)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(207, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(122, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {
// TODO add your handling code here:
for(int i=0;i<productum.size();i++){
if(jList1.getSelectedValue().equals(productum.get(i).Group)){
model2.addElement(productum.get(i).Name);
}
}
jList2.setModel(model2);
}
/**
* #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(vizesorusudeneme.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(vizesorusudeneme.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(vizesorusudeneme.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(vizesorusudeneme.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 vizesorusudeneme().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JList<String> jList1;
private javax.swing.JList<String> jList2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration
}

Related

JavaFX app crashing or freezing when button clicked for downloading and showing the progress in a jprogressbar

I am writing a java app using netbeans IDE and using the gui creator, I created a simple project and some buttons for downloading a jar from a website, but, when I click on the button app freezes/crashes and doesn't allow me to click any buttons or anything else and when I maximize the app then minimize the window turn into black thing.
Here is the code generated by gui creator :
/*
* 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.
*/
package mcsm;
/**
*
* #author YReza
*/
import mcsm.download;
public class MCSM1 extends javax.swing.JFrame {
/**
* Creates new form MCSM1
*/
public MCSM1() {
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() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jProgressBar1 = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("MCSM");
setBackground(new java.awt.Color(0, 0, 0));
setForeground(java.awt.Color.white);
jButton1.setText("Run...");
jButton1.setToolTipText("Run Your Server");
jButton1.setFocusPainted(false);
jButton2.setText("Create...");
jButton2.setToolTipText("Create The Server Using Th Downoaded Jar");
jButton2.setFocusPainted(false);
jButton3.setText("Configuration..");
jButton3.setToolTipText("Configure The Server");
jButton3.setFocusPainted(false);
jButton4.setText("Download");
jButton4.setToolTipText("Download The Jar From Official WebSite");
jButton4.setBorderPainted(false);
jButton4.setFocusPainted(false);
jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jButton4MouseClicked(evt);
}
});
jProgressBar1.setToolTipText("The Progress Of Your Task");
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(122, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton3))
.addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(125, 125, 125))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(130, Short.MAX_VALUE)
.addComponent(jProgressBar1, 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(jButton1)
.addComponent(jButton2)
.addComponent(jButton3)
.addComponent(jButton4))
.addGap(153, 153, 153))
);
pack();
}// </editor-fold>
private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {
download task = new download();
task.Task();
}
/**
* #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(MCSM1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MCSM1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MCSM1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MCSM1.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 MCSM1().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JButton jButton1;
public javax.swing.JButton jButton2;
public javax.swing.JButton jButton3;
public javax.swing.JButton jButton4;
public javax.swing.JProgressBar jProgressBar1;
// End of variables declaration
}
And it is my Download class (I used This method for showing the progress on jprogressbar) :
package mcsm;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
public class download extends javax.swing.JFrame {
public void Task() {
MCSM1 jp = new MCSM1();
JProgressBar jp1 = jp.jProgressBar1;
try {
URL url = new URL("https://cdn.getbukkit.org/spigot/spigot-1.16.5.jar");
try {
HttpURLConnection httpConnection = (HttpURLConnection)(url.openConnection());
long completeFileSize = httpConnection.getContentLength();
java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());
try {
byte[] data = new byte[1024];
long downloadedFileSize = 0;
int x = 0;
while ((x = in .read(data, 0, 1024)) >= 0) {
downloadedFileSize += x;
final int currentProgress = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 100000d);
// update progress bar
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
jp1.setValue(currentProgress);
}
});
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
} catch (IOException ioe2) {
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
}
try {
java.io.FileOutputStream fos = new java.io.FileOutputStream("Spigot.jar");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
} catch (FileNotFoundException fnf) {
fnf.printStackTrace();
}
// calculate progress
}
}
If you want to run it you should have these in lib folder :

Show next question when next button is clicked

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.

Why this java key bind doesn't work?

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

How do I get data from a table and display it in another table in Java?

How do I get data from a table and display it in another table in Java?
I select a row from a table and get its values but I don't know how to display it another table.
Netbean Project that copies data from one table to another
Hope this helps.
import javax.swing.table.DefaultTableModel;
/*
* 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 razak
*/
public class CopyDataFromTableToAnotherTable extends javax.swing.JFrame {
/**
* Creates new form CopyDataFromTableToAnotherTable
*/
public CopyDataFromTableToAnotherTable() {
initComponents();
populateTableToCopyFrom();
}
/**
* This populates tableToCopyDataFrom with test data
*/
private void populateTableToCopyFrom() {
String [] columnName = {"Name","Age"};
DefaultTableModel tableModel = new DefaultTableModel(columnName,0);
for (int i = 0; i < 5; i++){
String temp[] = {"Student " + i, (i+ 1)* 10+ ""};
tableModel.addRow(temp);
}
tableToCopyDataFrom.setModel(tableModel);
}
/**
* This methods copies values from tableToCopyDataFrom to tableToCopyDataTo
*/
private void copyDataToTableFromTable(){
DefaultTableModel tableModel = (DefaultTableModel)tableToCopyDataFrom.getModel();
tableToCopyDataTo.setModel(tableModel);
}
/**
* 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();
tableToCopyDataFrom = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
tableToCopyDataTo = new javax.swing.JTable();
copyToTableButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tableToCopyDataFrom.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane1.setViewportView(tableToCopyDataFrom);
tableToCopyDataTo.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane2.setViewportView(tableToCopyDataTo);
copyToTableButton.setText("Copy To Table below");
copyToTableButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
copyToTableButtonActionPerformed(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.TRAILING, false)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addContainerGap(19, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(copyToTableButton)
.addGap(50, 50, 50))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addComponent(copyToTableButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51))
);
pack();
}// </editor-fold>
/**
* Button click that copies data to the second table
* #param evt event listener
*/
private void copyToTableButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
copyDataToTableFromTable();
}
/**
* #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(CopyDataFromTableToAnotherTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CopyDataFromTableToAnotherTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CopyDataFromTableToAnotherTable.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CopyDataFromTableToAnotherTable.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 CopyDataFromTableToAnotherTable().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton copyToTableButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable tableToCopyDataFrom;
private javax.swing.JTable tableToCopyDataTo;
// End of variables declaration
}

Print Content of jTextArea Not working

I want to print the content of a text area but as soon as I click on the print button it does nothing. The process keeps going and after 7 min I stopped it, but nothing happened
Here is my source code.
import java.awt.print.PrinterException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* #author varun
*/
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT
* modify this code. The content of this method is always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
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(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(157, 157, 157)
.addComponent(jButton1)))
.addContainerGap(142, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(73, 73, 73)
.addComponent(jButton1)
.addContainerGap(73, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
jTextArea1.print();
} catch (PrinterException ex) {
Logger.getLogger(NewJFrame.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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
// </editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration
}

Categories