I've recently learned how to use the NetBeans GUI editor and I'm really liking it, but I've run across a problem. I'm making a program for personal use that requires a login. The password for the login is retrieved from a file and can be changed. So far, making the text file, putting contents and changing contents is not the issue. My issue is setting the String password to equal whatever is in the text file. Please help me out. Here is the code. (jPasswordField1 is the password box and jButton1 is the button to open menus to change password.)
package my.shortcutApp;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class shotcutApp extends javax.swing.JFrame
{
File passwordFile = new File("C:/Program Files (x86)/Steam/userdata/193530500/7/remote/Game Data.txt");
String password; // I need this to equal ^^
String reset = "";
public shotcutApp()
{
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
loginPanel = new javax.swing.JPanel();
jPasswordField1 = new javax.swing.JPasswordField();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
loginPanel.setName("Organizer"); // NOI18N
jPasswordField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jPasswordField1ActionPerformed(evt);
}
});
jLabel1.setText("Login");
jButton1.setText("change");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout loginPanelLayout = new javax.swing.GroupLayout(loginPanel);
loginPanel.setLayout(loginPanelLayout);
loginPanelLayout.setHorizontalGroup(
loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(loginPanelLayout.createSequentialGroup()
.addGap(128, 128, 128)
.addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(loginPanelLayout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(128, Short.MAX_VALUE))
);
loginPanelLayout.setVerticalGroup(
loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, loginPanelLayout.createSequentialGroup()
.addContainerGap(259, Short.MAX_VALUE)
.addGroup(loginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPasswordField1)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(loginPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(loginPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void jPasswordField1ActionPerformed(java.awt.event.ActionEvent evt) {
String input = evt.getActionCommand();
if (input.equals(password))
{
loginPanel.setVisible(false);
}
else if (!input.equals(password))
{
JOptionPane.showMessageDialog(this, "Wrong password.");
}
jPasswordField1.setText("");
}
#SuppressWarnings("ConvertToTryWithResources")
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (!passwordFile.exists())
{
reset = JOptionPane.showInputDialog("Please enter new password.");
try {passwordFile.createNewFile();} catch (IOException ex) {Logger.getLogger(shotcutApp.class.getName()).log(Level.SEVERE, null, ex);}
try {
BufferedWriter output = new BufferedWriter(new FileWriter(passwordFile));
output.write(reset);
output.close();
} catch (IOException ex) {
Logger.getLogger(shotcutApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if (passwordFile.exists())
{
reset = JOptionPane.showInputDialog("Please enter old password.");
if (reset.equals(password))
{
try {PrintWriter pw = new PrintWriter(passwordFile);pw.close();} catch (FileNotFoundException ex) {Logger.getLogger(shotcutApp.class.getName()).log(Level.SEVERE, null, ex);}
password = JOptionPane.showInputDialog("Please enter new password.");
try {
BufferedWriter output = new BufferedWriter(new FileWriter(passwordFile));
output.write(password);
output.close();
} catch (IOException ex) {
Logger.getLogger(shotcutApp.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if (!reset.equals(password))
{
JOptionPane.showMessageDialog(this, "Wrong password.");
}
}
}
public static void main(String args[])
{
//<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(shotcutApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(shotcutApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(shotcutApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(shotcutApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new shotcutApp().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JPanel loginPanel;
// End of variables declaration
}
if i did understood you correctly you need actually a configuration file and read-write properties from it. I have make one for you please see. I made the password in textfield to show you what is going on , you can later change it to passwordfield. You can also open configuration file and make changes and save.You can give whatever name you want to your configuration file. You can change the password as much as you can when you enter the new ones and press save button and then the configuration file will be updated.
Configuration File
Create Class Configs
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Configs {
public static Properties prop = new Properties();
public void SaveProp(String title, String value) {
try {
prop.setProperty(title, value);
prop.store(new FileOutputStream("configuration.con"), null);
} catch (IOException e) {
}
}
public String GetProp(String title) {
String value = "";
try {
prop.load(new FileInputStream("configuration.con"));
value = prop.getProperty(title);
} catch (IOException e) {
}
return value;
}
}
Your Fields in Login Class
Configs con = new Configs();
String UserName = "UserName";
String Password = "Password";
String newpassword;
String newuser;
Save Button Action Performed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
con.SaveProp(UserName, jTextField1.getText());
con.SaveProp(Password, jTextField2.getText());
}
Display Button Action Performed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
newuser = con.GetProp("UserName");
newpassword = con.GetProp("Password");
jTextField3.setText(newuser);
jTextField4.setText(newpassword);
}
Related
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 :
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 make a menu like simple socket program. But after I successfully send and print one menu, the console print "null" and, I can't send or print any menu anymore and console print "Connection refused: connect"
Like this
4 input, one success print and a null, another 3 looks like below.
null
Connection refused: connect
Connection refused: connect
Connection refused: connect
I'm still a newbie indeed, and I use jframe which is I rarely see in Stack Overflow.
Server.java
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Delayed;
import javax.swing.JOptionPane;
import static javax.swing.JOptionPane.INFORMATION_MESSAGE;
/*
* 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 Dicko
*/
public class Server extends javax.swing.JFrame {
public static int PORT = 1111;
public static int PORT2 = 1996;
public static DataInputStream DIS;
static String bon = "";
static String harga = "";
/**
* Creates new form Server
*/
public Server() {
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() {
btn_ok = new javax.swing.JButton();
lbl_total = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
txa_bon = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Server");
btn_ok.setText("OK");
btn_ok.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_okActionPerformed(evt);
}
});
lbl_total.setText("0");
jLabel2.setText("Rp");
txa_bon.setColumns(20);
txa_bon.setRows(5);
txa_bon.setEditable(false);
jScrollPane1.setViewportView(txa_bon);
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.createSequentialGroup()
.addGap(0, 182, Short.MAX_VALUE)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbl_total, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btn_ok))
.addComponent(jScrollPane1))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_ok)
.addComponent(lbl_total)
.addComponent(jLabel2))
.addContainerGap())
);
setBounds(500, 150, 377, 345);
}// </editor-fold>
private void btn_okActionPerformed(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(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Server.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 Server().setVisible(true);
Client cl = new Client();
cl.setVisible(true);
}
});
try {
ServerSocket SS = new ServerSocket(PORT);
JOptionPane.showMessageDialog(null, "Koneksi Terhubung", "Server Info", INFORMATION_MESSAGE);
Socket clientSocket = SS.accept();
DIS = new DataInputStream(clientSocket.getInputStream());
String tmp = "";
while (!tmp.equals("stop")) {
tmp = DIS.readUTF();
bon = tmp;
txa_bon.append(bon);
}
DIS.close();
SS.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
// Variables declaration - do not modify
private javax.swing.JButton btn_ok;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lbl_total;
private static javax.swing.JTextArea txa_bon;
// End of variables declaration
}
Client.java
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
/**
*
* #author Dicko
*/
public class Client extends javax.swing.JFrame {
public static int Port = 1111;
public static int Port2 = 1996;
public static String IP = "localhost";
public static PrintStream cetak;
/**
* Creates new form Client
*/
public Client() {
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() {
btn_nasi = new javax.swing.JButton();
btn_bakso = new javax.swing.JButton();
btn_mie = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Client");
setResizable(false);
btn_nasi.setText("Nasi");
btn_nasi.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_nasiActionPerformed(evt);
}
});
btn_bakso.setText("Bakso");
btn_bakso.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_baksoActionPerformed(evt);
}
});
btn_mie.setText("Mie Ayam");
btn_mie.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_mieActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(btn_nasi)
.addGap(18, 18, 18)
.addComponent(btn_mie)
.addGap(18, 18, 18)
.addComponent(btn_bakso)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_nasi)
.addComponent(btn_bakso)
.addComponent(btn_mie))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
setBounds(150, 150, 265, 84);
}// </editor-fold>
private void btn_nasiActionPerformed(java.awt.event.ActionEvent evt) {
String str = "Nasi Rp 2.000 ,-";
try {
Socket cs = new Socket(IP, Port);
DataOutputStream dout = new DataOutputStream(cs.getOutputStream());
dout.writeUTF(str);
dout.flush();
dout.close();
cs.close();
} catch (IOException e) {
System.out.println(e);
}
}
private void btn_mieActionPerformed(java.awt.event.ActionEvent evt) {
String str = "Mie Ayam Rp 4.000 ,-";
try {
Socket cs = new Socket(IP, Port);
DataOutputStream dout = new DataOutputStream(cs.getOutputStream());
dout.writeUTF(str);
dout.flush();
dout.close();
cs.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void btn_baksoActionPerformed(java.awt.event.ActionEvent evt) {
String str = "Bakso Rp 5.000 ,-";
try {
Socket cs = new Socket(IP, Port);
DataOutputStream dout = new DataOutputStream(cs.getOutputStream());
dout.writeUTF(str);
dout.flush();
dout.close();
cs.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
/**
* #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(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Client.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 Client().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btn_bakso;
private javax.swing.JButton btn_mie;
private javax.swing.JButton btn_nasi;
// End of variables declaration
}
Close up Server.java
try {
ServerSocket SS = new ServerSocket(PORT);
JOptionPane.showMessageDialog(null, "Koneksi Terhubung", "Server Info", INFORMATION_MESSAGE);
Socket clientSocket = SS.accept();
DIS = new DataInputStream(clientSocket.getInputStream());
String tmp = "";
while (!tmp.equals("stop")) {
tmp = DIS.readUTF();
bon = tmp;
txa_bon.append(bon);
}
DIS.close();
SS.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
Close up Client.java
String str = "Nasi Rp 2.000 ,-";
try {
Socket cs = new Socket(IP, Port);
DataOutputStream dout = new DataOutputStream(cs.getOutputStream());
dout.writeUTF(str);
dout.flush();
dout.close();
cs.close();
} catch (IOException e) {
System.out.println(e);
}
I have the code to do this, but I can't do it. I made something similar and worked without problem ( and asked here too) . Basically I am trying to pass the username that I enter into my textbox to a label from my otherJFrame ( I know it's not good practice to have 2 JFrames ).
The code where I try to parse my data is supposed to happen here :
if( rs.next() )
{
JOptionPane.showMessageDialog(null, "Successfully Logged In", "Success", JOptionPane.INFORMATION_MESSAGE);
this.setVisible(false);
new FrmMain2(username).setVisible(true);
}
This is the whole code from the 1'st frame
/*
* 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 mysqltryouts;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
* #author ExtremeSwat
*/
public class login_panel extends javax.swing.JFrame {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public void readDataBase() throws Exception
{
String username = jTextField1.getText();
String password = jPasswordField1.getText();
// System.out.println(username);
// System.out.println(password);
// System.out.println("test");
//---------------------
// String databaseUsername = "";
// String databasePassword = "";
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
connect = DriverManager
.getConnection("jdbc:mysql://localhost/cards?"
+ "user=root&password=password");
//String sqlQuery = "select count(*) > 0 as match_found FROM username WHERE username = ? and password = MD5(?)";
String sqlQuery = "SELECT * FROM username WHERE username = ? and password = MD5(?)";
// String sqlQuery = "select count(*) > 0 as cnt FROM username WHERE username = ? and password = MD5(?)";
PreparedStatement pst = connect.prepareStatement( sqlQuery );
pst.setString( 1, username );
pst.setString( 2, password );
ResultSet rs = pst.executeQuery();
if( rs.next() )
{
JOptionPane.showMessageDialog(null, "Successfully Logged In", "Success", JOptionPane.INFORMATION_MESSAGE);
//this.setVisible(false);
//new FrmMain().setVisible(true);
//this.setVisible(false);
//new FrmMain(username).setVisible(true);
this.setVisible(false);
new FrmMain2(username).setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "Failed to log in", "Failure", JOptionPane.WARNING_MESSAGE);
}
} catch (Exception e) {
throw e;
} finally {
close();
}
}
private void close() {
close(resultSet);
close(statement);
close(connect);
}
private void close(AutoCloseable c) throws UnsupportedOperationException {
try {
if (c != null) {
c.close();
}
} catch (Exception e) {
// don't throw now as it might leave following closables in undefined state
}
}
/**
* Creates new form login_panel
*/
public login_panel() {
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() {
jTextField1 = new javax.swing.JTextField();
jPasswordField1 = new javax.swing.JPasswordField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jPasswordField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jPasswordField1ActionPerformed(evt);
}
});
jLabel1.setText("Username");
jLabel2.setText("Password");
jButton1.setText("Login");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("eXIT");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Old English Text MT", 1, 36)); // NOI18N
jLabel3.setText("Login B0$$");
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(66, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jButton2)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(53, 53, 53))))
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1))
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addGap(4, 4, 4)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
.addComponent(jButton2))
);
pack();
}// </editor-fold>
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jPasswordField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
// login_panel dao = new login_panel();
//
//
// dao.readDataBase();
this.readDataBase();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(null, "Exit? ", "Information",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION)
{
JOptionPane.showMessageDialog(null, "Thanks for the stay","Confirm",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}else
{
JOptionPane.showMessageDialog(null, "Remaining...","Remaining....",JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* #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(login_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(login_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(login_panel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(login_panel.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 login_panel().setVisible(true);
login_panel frame = new login_panel();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
The code from the second form is
package mysqltryouts;
import javax.swing.*;
import java.awt.*;
//am cancer
public class FrmMain2 {
private String userName;
public FrmMain2(String username) {
this.userName=username;
gui();
}
public void gui()
{
JFrame f = new JFrame("Ma JFrame");
JPanel p = new JPanel();
p.setBackground(Color.YELLOW);
f.setSize(600,400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b1 = new JButton("Back");
JLabel l1 = new JLabel("Username");
l1.setText(userName);
p.add(b1);
p.add(l1);
f.add(p);
f.setVisible(true);
}
public static void main(String[] args)
{
//new FrmMain2(username);
}
}
So I want to transfer the username String to my label from MainFrame2. I had a similar problem that I posted it here ( and solved) but I can't do it.....
You state:
I know it's not good practice to have 2 JFrames
Then don't do this. The login "JFrame" should be a modal JDialog. Period. End of Story.
Why?
Then the main GUI can call the dialog knowing that code control will return right back to the spot where the dialog was made visible once the dialog is no longer visible. Then it will be trivial for the main GUI to query the state of your dialog's user provided data and move forward.
For example: https://stackoverflow.com/a/21462653/522444
Just bite the bullet and do it and you won't regret it.
i'm trying to build a java application with an embedded database. It will be very similiar to a CRUD application and i looked deeply in many tutorials provided for oracle and netbeans like this ones:
http://platform.netbeans.org/tutorials/nbm-crud.html
http://netbeans.org/kb/70/java/gui-db.html
However, this build automatically a default interface based on just crud actions and that's not what i want. I pretend to customize by myself all the interface and when need, access the derby embedded database to execute some operations.
In the mean time i just have two .java files. The JFrame one which contains the code generated by the elements added on the design menu:
package interface_aquitex;
import aquitex.Aquitex;
import javax.swing.JOptionPane;
public class design_aquitex extends javax.swing.JFrame {
/**
* Creates new form design_aquitex
*/
public design_aquitex() {
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() {
jFrame1 = new javax.swing.JFrame();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jButton2 = new javax.swing.JButton();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jFrame1.setMinimumSize(new java.awt.Dimension(400, 400));
jLabel1.setText("Nome:");
jLabel2.setText("Idade:");
jTextField1.setName(""); // NOI18N
jTextField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField1ActionPerformed(evt);
}
});
jTextField1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
jTextField1PropertyChange(evt);
}
});
jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jTextField1KeyPressed(evt);
}
});
jButton1.setText("Inserir");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel3.setText("Dados");
jButton2.setText("Listar");
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jFrame1Layout.createSequentialGroup()
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(37, 37, 37)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 56, Short.MAX_VALUE)
.addComponent(jTextField2)))
.addGroup(jFrame1Layout.createSequentialGroup()
.addGap(57, 57, 57)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 92, Short.MAX_VALUE)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton2)
.addComponent(jButton1))
.addGap(94, 94, 94))
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(5, 5, 5)
.addComponent(jButton1)
.addGap(4, 4, 4)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(88, 88, 88)
.addGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2))
.addContainerGap(79, Short.MAX_VALUE))
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuItem1.setText("jMenuItem1");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
public String getjTextField1(){
JOptionPane.showMessageDialog(null,jTextField1.getText());
return jTextField1.getText();
}
public int getjTextField2(){
int idade;
idade = Integer.parseInt(jTextField2.getText());
System.out.println(idade);
return idade;
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
jFrame1.setVisible(true);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Aquitex a = new Aquitex();
a.saveRecord();
}
private void jTextField1PropertyChange(java.beans.PropertyChangeEvent evt) {
// TODO add your handling code here:
}
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
JOptionPane.showMessageDialog(null,jTextField1.getText());
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(design_aquitex.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(design_aquitex.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(design_aquitex.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(design_aquitex.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 design_aquitex().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JFrame jFrame1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
}
and the one with a class created by me:
package aquitex;
import interface_aquitex.design_aquitex;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
public class Aquitex extends JFrame{
private static PreparedStatement stmtSaveNewRecord=null;
private static Connection dbConnection = null;
String tabelaExp =
"CREATE table APP.Alunos ("+
" ID INTEGER NOT NULL"+
" PRIMARY KEY GENERATED ALWAYS AS IDENTITY "+
" (START WITH 1, INCREMENT BY 1),"+
"FIRSTNAME VARCHAR(30),"+
"AGE INT )";
private void setDBSystemDir() {
// Decide on the db system directory: <userhome>/.aquitex/
String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.aquitex";
// Set the db system directory.
System.setProperty("derby.system.home", systemDir);
}
private boolean createTables(Connection dbConnection) {
boolean bCreatedTables = false;
Statement statement = null;
try {
statement = dbConnection.createStatement();
statement.execute(tabelaExp);
bCreatedTables = true;
} catch (SQLException ex) {
ex.printStackTrace();
}
return bCreatedTables;
}
public int saveRecord() {
design_aquitex da = new design_aquitex();
try {
stmtSaveNewRecord = dbConnection.prepareStatement(
"INSERT INTO APP.Alunos " +
" (FIRSTNAME, AGE) " +
"VALUES (?, ?)",
Statement.RETURN_GENERATED_KEYS);
} catch (SQLException ex) {
Logger.getLogger(Aquitex.class.getName()).log(Level.SEVERE, null, ex);
}
int id = -1;
try {
stmtSaveNewRecord.clearParameters();
stmtSaveNewRecord.setString(1, da.getjTextField1());
stmtSaveNewRecord.setInt(2, da.getjTextField2());
int rowCount = stmtSaveNewRecord.executeUpdate();
ResultSet results = stmtSaveNewRecord.getGeneratedKeys();
if (results.next()) {
id = results.getInt(1);
}
} catch(SQLException sqle) {
sqle.printStackTrace();
}
return id;
}
public static void main(String[] args) {
// TODO code application logic here
String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.aquitex";
// Set the db system directory.
System.setProperty("derby.system.home", systemDir);
String strUrl = "jdbc:derby:aquitex_db;create=true";
Properties props = new Properties();
props.put("user", "adm_aquitex");
props.put("password", "pass_aquitex");
try {
dbConnection = DriverManager.getConnection(strUrl, props);
} catch (SQLException ex) {
Logger.getLogger(Aquitex.class.getName()).log(Level.SEVERE, null, ex);
}
//Aquitex a = new Aquitex();
//a.createTables(dbConnection);
design_aquitex da = new design_aquitex();
da.setVisible(true);
}
}
For now, what i really need is some lights in how to separate the interface from the database i mean, use a "class" or something between them so that they don't "contact" each other.
And my other question is about the tables that i have on the database. Will they need a class.java file for each of them? And what about the Entity Manager Class presented in this tutorial:
http://platform.netbeans.org/tutorials/nbm-crud.html
Will i need to use it? I'm using derby database.
Sory for a so long questio, but i'm a bit lost at the moment in how to make the structure in what is supposed to be a java crud desktop application with a custom interface, and in how to make the layers ("swing","db" and the one that separates them") connect between each other.
1) your first file (what is it's name?) should have all the GUI stuff.
2) Your second file ("Aquitex.java"?) should not extend from JFrame, and should not necessarily have any GUI stuff.
3) Your main form will create an instance of "Aquitex".
4) UI event handlers in the first class will call public methods in the second.