How to read file text to JList - java

I have a question, how can I import existed array string to jlist for each element in array, I know a lot of you guy asked it before, but mostly, I saw that how to do it with a jButton, I also heard about
DefaultListModel but it did't work
private void JListAction(java.awt.event.ActionEvent evt) {
DefaultListModel listModel = new DefaultListModel();
for (int i = 0; i < dm.getSize(); i++) {
listModel.addElement(dic.newWord.get(i).getWordExplain());
}
jList2.setModel(listModel);
}
Here is my code from GUI only
[import java.awt.Color;
import java.awt.Font;
import javax.swing.JTextArea;
import javax.swing.DefaultListModel;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JList;
import javax.swing.JScrollPane;
/*
* 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 Quốc Khánh
*/
public class GUI extends javax.swing.JFrame {
DictionaryCommandline dcl = new DictionaryCommandline();
DictionaryManagement dm = new DictionaryManagement();
Dictionary dic = new Dictionary();
DictionaryApplication dicA = new DictionaryApplication();
private Object textArea;
Font font = new Font("consolas", Font.BOLD, 18);
/**
* Creates new form GUI
*/
public GUI() {
setTitle("từ điển Anh Việt v1.0");
dm.insertFromFile(dic);
initComponents();
jTextPane1.setFont(font);
jTextArea1.setFont(font);
jTextArea1.setLineWrap(true);
jTextArea1.setForeground(Color.BLACK);
jButton1.setFont(font);
JScrollPane pane=new JScrollPane(jList2);
}
/**
* 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();
jTextPane1 = new javax.swing.JTextPane();
jButton1 = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jScrollPane4 = new javax.swing.JScrollPane();
jList2 = new javax.swing.JList<>();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setViewportView(jTextPane1);
jButton1.setText("translate");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane3.setViewportView(jTextArea1);
jScrollPane4.setViewportView(jList2);
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(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE))
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(54, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(37, 37, 37)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE))
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane3)
.addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE))
.addContainerGap(67, Short.MAX_VALUE))
);
jButton1.getAccessibleContext().setAccessibleName("translate");
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String word = jTextPane1.getText();
String mean = dicA.getWord(dic, dm.getSize(), dm, word);
jTextArea1.setText(dicA.getWordEx(dic, dm.getSize(), dm, mean));
}
private void JListAction(java.awt.event.ActionEvent evt) {
DefaultListModel listModel = new DefaultListModel();
for (int i = 0; i < dm.getSize(); i++) {
listModel.addElement(dic.newWord.get(i).getWordExplain());
}
jList2.setModel(listModel);
}
/**
* #param args the command line arguments
*/
public static void main(String\[\] args) {
java.awt.EventQueue.invokeLater(() -> {
new GUI().setVisible(true);
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JList<String> jList2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane4;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration
/**
*
*/
}

Is your Array of Strings already available, when the GUI is generated? If so, you can insert it directly into your JList by using it as a parameter.
Instead of using JList jList2 = new javax.swing.JList<>(); (as it is done in line 5 of your initComponent() method) you'd put your String[] into the brackets:
String[] data = {"a","b","c"};
JList jList2 = new javax.swing.JList<>(data);
JScrollPane pane=new JScrollPane(jList2);
In this case your ScrollPane would look something like this

Related

Java : JTextArea can not append()

package my.test;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JScrollPane;
public class ChatP2P extends javax.swing.JFrame {
ObjectOutputStream out = null;
ObjectInputStream in = null;
String name = LoginInterface.id;
private final static String newline = "\n";
String message = null;
/**
* Creates new form ChatP2P
*/
public ChatP2P(Socket socket) throws IOException, ClassNotFoundException {
initComponents();
JScrollPane scrollPane = new JScrollPane(text);
text.setLineWrap(true);
chat.setLineWrap(true);
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
new Thread(new receiveThread(message, in, text)).start();
}
/**
* 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() {
jScrollPane2 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jMenuItem1 = new javax.swing.JMenuItem();
jScrollPane1 = new javax.swing.JScrollPane();
text = new javax.swing.JTextArea();
nameField = new javax.swing.JTextField();
jScrollPane3 = new javax.swing.JScrollPane();
chat = new javax.swing.JTextArea();
sendButton = new javax.swing.JButton();
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane2.setViewportView(jTextArea1);
jMenuItem1.setText("jMenuItem1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
text.setEditable(false);
text.setColumns(20);
text.setRows(5);
jScrollPane1.setViewportView(text);
nameField.setEditable(false);
chat.setColumns(20);
chat.setRows(5);
jScrollPane3.setViewportView(chat);
sendButton.setText("SEND");
sendButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(nameField)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, 63, Short.MAX_VALUE)
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
);
pack();
}// </editor-fold>
private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {
if (!chat.getText().equals("")){
try {
String temp = name + " : " + chat.getText();
out.writeObject(temp);
text.append(temp + newline);
chat.setText("");
} catch (IOException ex) {
Logger.getLogger(ChatP2P.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* #param args the command line arguments
*/
// Variables declaration - do not modify
private javax.swing.JTextArea chat;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextArea jTextArea1;
public javax.swing.JTextField nameField;
private javax.swing.JButton sendButton;
public javax.swing.JTextArea text;
// End of variables declaration
}
So I have a SEND button, a CHAT TextArea for user to input the message and a TEXT TextArea to display the message
but when I typed a messsage and clicked on the SEND button,the TEXT didn't append that new message,but it cleared the message in CHAT. That means the code walks through the line :
text.append(temp + newline);
in the
sendButtonActionPerformed
but nothing is displayed. So what's wrong here ?
Move statement JScrollPane scrollPane = new JScrollPane(text); before pack() and it will be ok. Like this:
jScrollPane1 = new javax.swing.JScrollPane();
text = new javax.swing.JTextArea();
JScrollPane scrollPane = new JScrollPane(text);

Accessing elements from a jFrame that is within a running instance of a thread

I am trying to make an app for communicating between different running instances of a thread. I have a jFrame that has a jTextField and a jButton. In the jTextField I type the number of threads that I want to run and after I press the jButton the threads run. Each thread contains a jFrame with a jButton. So if I type 3 in the jTextField and then press OK, three different jFrames pop out that have an own jButton. If I press the jButton in one of the jFrames of the threads, the jButton is set to disabled (setEnabled(false)). This should happen to each jButton of the jFrames from within the threads when pressed but the one from the last jFrame that is still not pressed.
This is the window class for the thread:
public class Window extends JFrame implements Runnable {
JFrame jr;
JButton bt;
public void run() {
jr=new JFrame();
bt=new jButton();
bt.setTitle("Press Me");
jr.setLayout(new FlowLayout());
jr.add(bt);
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
bt.setEnabled(false);
}
});
jr.setVisible(true);
}
}
Now this is how I run multiple instances of this thread. i is the number of the thread instances that is taken from the jTextField:
( int i=Integer.parseInt(jTextField1.gettext()) )
for (int a=0;a<i;a++) {
Runnable thr=new Window(a);
executor.execute(thr);
}
This is what I want to do: After I press the jButton on every jFrame that is within the thread instances and it is set to setEnabled(false) I get to the last jFrame that is popped up whose jButton is still unpressed. When I press this last JButton I want that all the JButtons on every jFrame to be set back to setEnabled(true). How can I do that?
This is the main class it works 100 % now!
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* #author oliver
*/
public class Hauptklasse extends javax.swing.JFrame {
static int i = 0;
static Random r;
static boolean OkApasat=false;
static int c;
public static Fereastra[] thread;
public Hauptklasse() throws IOException {
initComponents();
Image logo;
logo = ImageIO.read(getClass().getResource("resurse/logo.png"));
jLabel4.setIcon(new ImageIcon(logo));
jLabel4.setVisible(true);
setLocation(200,100);
jPanel1.setBackground(Color.cyan);
jTextField1.setEditable(false);
jButton2.setEnabled(false);
r=new Random();
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setPreferredSize(new java.awt.Dimension(549, 448));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton1.setText("Pornire");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Andale Mono", 0, 11)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Numar maxim de ferestre");
jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton2.setText("OK");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2)))
.addContainerGap(31, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addGroup(jPanel1Layout.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(jButton2))
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setEditable(true);
jButton1.setEnabled(false);
jButton2.setEnabled(true);
jTextArea1.append("\n Welcome! :)");
jTextArea1.append("\n The following app tests the communication between threads");
jTextArea1.append("\n Please enter maximum number of windows to be opened");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
OkApasat=true;
}
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
final Hauptklasse main1 = new Hauptklasse();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
main1.setVisible(true);
}
});
while (true){
if (OkApasat==true){
if (Integer.parseInt(jTextField1.getText())>=3){
i= (Integer.parseInt(jTextField1.getText()));
main1.jTextArea1.append("\n"+i+" windows opened");
Fereastra[] thr=new Fereastra[i];
for (c = 0; c < i; c++) {
thr[c]=new Fereastra(thr);
thr[c].run();
}
OkApasat=false;
main1.jButton2.setEnabled(false);
main1.jTextField1.setEditable(false);
}
else jTextArea1.append("\n Wrong maximum number of windows-must be at least 3");
OkApasat=false;
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(Hauptklasse.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
public static javax.swing.JTextField jTextField1;
// End of variables declaration
}
THIS IS THE WINDOW CLASS, WORKS 100 %:
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* #author oliver
*/
public class Fereastra extends JFrame implements Runnable {
public JFrame jr;
public JButton bt;
public JLabel l;
public JLabel l2;
public Fereastra[] thread;
public boolean deblocat = true;
public Fereastra(Fereastra[] thread) {
this.thread = thread;
jr = new JFrame();
jr.setSize(250, 250);
jr.setLayout(new FlowLayout());
bt = new JButton();
jr.add(bt);
bt.setText("OK");
bt.setBackground(Color.cyan);
l2 = new JLabel();
l2.setText("Buton activ");
jr.add(l2);
jr.setVisible(true);
}
public void run() {
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bt.setEnabled(false);
deblocat = true;
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null && thread[c].bt.isEnabled()) {
deblocat = false;
break;
}
}
if (deblocat == true) {
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null) {
thread[c].bt.setEnabled(true);
}
}
}
}
});
}
}
My classes:
1) The Window class (Fereastra means window, deblocat means unlocked, buton activ means Button is enabled)
package concurenta;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
*
* #author oliver
*/
public class Fereastra extends JFrame implements Runnable {
public static JFrame jr;
public static JButton bt;
public static JLabel l;
public static JLabel l2;
public static Fereastra[] thread;
public boolean deblocat = true;
public Fereastra(Fereastra[] thread) {
this.thread = thread;
jr = new JFrame();
jr.setSize(250, 250);
jr.setLayout(new FlowLayout());
bt = new JButton();
jr.add(bt);
bt.setText("OK");
bt.setBackground(Color.cyan);
l2 = new JLabel();
l2.setText("Buton activ");
jr.add(l2);
jr.setVisible(true);
}
public void run() {
bt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bt.setEnabled(false);
deblocat = true;
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null && thread[c].bt.isEnabled()) {
deblocat = false;
break;
}
}
if (deblocat == true) {
for (int c = 0; c < Hauptklasse.i; c++) {
if (thread[c] != null) {
thread[c].bt.setEnabled(true);
}
}
}
}
});
}
}
2) The Main Class(a.k.a Hauptklasse, okApasat means ok is pressed):
/*
* 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 concurenta;
import java.awt.Color;
import java.awt.Image;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
*
* #author oliver
*/
public class Hauptklasse extends javax.swing.JFrame {
static int i = 0;
static Random r;
static boolean OkApasat=false;
static int c;
public static Fereastra[] thread;
public Hauptklasse() throws IOException {
initComponents();
Image logo;
logo = ImageIO.read(getClass().getResource("resurse/logo.png"));
jLabel4.setIcon(new ImageIcon(logo));
jLabel4.setVisible(true);
setLocation(200,100);
jPanel1.setBackground(Color.cyan);
jTextField1.setEditable(false);
jButton2.setEnabled(false);
r=new Random();
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setPreferredSize(new java.awt.Dimension(549, 448));
jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton1.setText("Pornire");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextArea1.setBackground(new java.awt.Color(0, 0, 0));
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Andale Mono", 0, 11)); // NOI18N
jTextArea1.setForeground(new java.awt.Color(255, 255, 255));
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel1.setText("Numar maxim de ferestre");
jButton2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
jButton2.setText("OK");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(44, 44, 44)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 486, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton2)))
.addContainerGap(31, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addGroup(jPanel1Layout.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(jButton2))
.addGap(22, 22, 22)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 561, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setEditable(true);
jButton1.setEnabled(false);
jButton2.setEnabled(true);
jTextArea1.append("\n Welcome! :)");
jTextArea1.append("\n The following app tests the communication between threads");
jTextArea1.append("\n Please enter maximum number of windows to be opened");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
OkApasat=true;
}
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String args[]) throws IOException {
final Hauptklasse main1 = new Hauptklasse();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
main1.setVisible(true);
}
});
while (true){
if (OkApasat==true){
if (Integer.parseInt(jTextField1.getText())>=3){
i= (int) (Math.random() * (Integer.parseInt(jTextField1.getText()) - 3)) + 3;
main1.jTextArea1.append("\n"+i+" windows opened");
Fereastra[] thr=new Fereastra[i];
for (c = 0; c < i; c++) {
thr[c]=new Fereastra(thr);
thr[c].run();
}
OkApasat=false;
main1.jButton2.setEnabled(false);
main1.jTextField1.setEditable(false);
}
else jTextArea1.append("\n Wrong maximum number of windows-must be at least 3");
OkApasat=false;
}
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
Logger.getLogger(Hauptklasse.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea jTextArea1;
public static javax.swing.JTextField jTextField1;
// End of variables declaration
}

How do I pass values between cards in Java CardLayout....this time i have given a good example

This is a simple code to clarify my question:
this is the main class from where I declared the two panels.
/*
* 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 sakib
*/
public class MainPane {
private JPanel contentPane;
private Firstcard1 p1;
private SecondCard1 p2;
public void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
//a=S1;
contentPane.setLayout(new CardLayout());
p1 = new Firstcard1(contentPane);
p2 = new SecondCard1(contentPane);
contentPane.add(p1, "Panel 1");
contentPane.add(p2, "Panel 2");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new MainPane().displayGUI();
}
}
);
}
}
this is the first card:
public class Firstcard1 extends javax.swing.JPanel {
private JPanel contentpane;
/**
* Creates new form Firstcard1
*/
public Firstcard1(JPanel cp) {
this.contentpane=cp;
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();
Login = new javax.swing.JButton();
Login.setText("Login");
Login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoginActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.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(117, 117, 117)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(Login)))
.addContainerGap(145, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(105, 105, 105)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(Login)
.addContainerGap(134, Short.MAX_VALUE))
);
}// </editor-fold>
private void LoginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
CardLayout layout = (CardLayout)contentpane.getLayout();
layout.show(contentpane, "Panel 2");
}
// Variables declaration - do not modify
private javax.swing.JButton Login;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
this is the second card:
public class SecondCard1 extends javax.swing.JPanel {
private JPanel contentpane;
/**
* Creates new form SecondCard1
*/
public SecondCard1(JPanel cp) {
this.contentpane=cp;
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();
back = new javax.swing.JButton();
back.setText("Back");
back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.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(127, 127, 127)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(157, 157, 157)
.addComponent(back)))
.addContainerGap(137, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(121, 121, 121)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(back)
.addContainerGap(102, Short.MAX_VALUE))
);
}// </editor-fold>
private void backActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
CardLayout layout = (CardLayout)contentpane.getLayout();
layout.show(contentpane, "Panel 1");
}
// Variables declaration - do not modify
private javax.swing.JButton back;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
My question is.if I put a value in the textarea of the first card and press the login button.the value will appear in the text area of the second card.how can i do it?
You somehow have to pass a reference of the second panel to the first one:
Main class:
public class MainPane
{
public void displayGUI()
{
....
p1 = new Firstcard1(contentPane);
p2 = new SecondCard1(contentPane);
p1.setSecondCard(p2);
....
}
}
First card:
public class Firstcard1 extends javax.swing.JPanel {
....
private SecondCard secondCard;
void setSecondCard(SecondCard secondCard)
{
this.secondCard = secondCard;
}
....
private void LoginActionPerformed(java.awt.event.ActionEvent evt)
{
CardLayout layout = (CardLayout)contentpane.getLayout();
layout.show(contentpane, "Panel 2");
secondCard.getTextField().setText(jTextField1.getText());
}
}
Second card:
public class SecondCard1 extends javax.swing.JPanel
{
...
JTextField getTextField()
{
return jTextField1;
}
...
}
But when you continue like this, the program will probably become a mess pretty soon. I'd recommend to create these components manually, without using any visual GUI builders.

Java, select text Exactly in JEditorPane

I'm using jEditorPane to act kinda as some editor, the one who asked for this of me, also needed a find replace search... so I wanted to let him select in find and then do replace on need.
so I provide this simple code:
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
int start = (jEditorPane1.getSelectionStart()>jEditorPane1.getSelectionEnd())?jEditorPane1.getSelectionEnd():jEditorPane1.getSelectionStart();
int max = (start>jEditorPane1.getSelectionStart())?start:jEditorPane1.getSelectionStart();
String searchWord = jTextField3.getText();
int searchIndex = jEditorPane1.getText().indexOf(searchWord, max);
if(searchIndex != -1){
jEditorPane1.select(searchIndex, searchIndex+searchWord.length());
}
else{
jEditorPane1.setSelectionStart(-1);
jEditorPane1.setSelectionEnd(-1);
}
}
fortunatelly the application return good indexes, but unfortunatelly on view windows I see no selection.
I'm also new to java, please help
PS. buttons action are provided by netbeans itself
THe sample you requested
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* test.java
*
* Created on Jun 12, 2013, 8:23:19 PM
*/
package wordchecker;
/**
*
* #author Hassan
*/
public class test extends javax.swing.JFrame {
/** Creates new form test */
public test() {
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();
jTextPane1 = new javax.swing.JTextPane();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jScrollPane1.setViewportView(jTextPane1);
jTextField1.setText("jTextField1");
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()
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 366, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap(14, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int startFrom = jTextPane1.getSelectionStart();
if(jTextPane1.getSelectionStart() == jTextPane1.getSelectionEnd()){
startFrom = -1;
}
String searchWord = jTextField1.getText();
int searchIndex = jTextPane1.getText().indexOf(searchWord, startFrom);
if(searchIndex != -1){
jTextPane1.select(searchIndex, searchIndex+searchWord.length());
}
else{
jTextPane1.setSelectionStart(0);
jTextPane1.setSelectionEnd(0);
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new test().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration
}
The selection of a text component is only displayed when the text component has focus. When you click on the button it gains focus so you don't see the text selection. You could make the button non-focusable or you can add the following to the bottom of your actionPerformed() method:
jTextPane1.requestFocusInWindow();
Also, don't use the getText() method. This will cause problems with offsets.
int searchIndex = jTextPane1.getText().indexOf(searchWord, startFrom);
See Text and New Lines for more information and a solution. The basics of this link is to use:
int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);
The above will only return "\n" as the EOL string so the offsets will match when you do a search and then select the text.
Edit:
I generally use code like the following:
int startFrom = jTextPane1.getCaretPosition();

Exchange variable between two jFrames

I have 3 java files.
DBConn - This Class conencts to the database and execute query.
UserLogin - This jFrame will take username and password and compare with "users" table
if it matches it will display "Login Successfull" in LibSysMain java file
LibSysMain - This is the main file which shows the menu.
This is the jFrame which is displayed first when application is run.
The problem is I am not able to set the "Login Successful" message in LibSysMain.
My Database is MS Access. Table name is "users". Field is "username" and "password". Both of them are of string type.
A help would be highly apprecited.
I am new in Java. I am using NetBeans 6.9.1.
Here is the list:
DBConn:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package LibSystem;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class DBConn {
Connection con;
Statement stmt;
ResultSet rs;
public void DoConnect(String querydb)
{
String SQL;
SQL=querydb;
try
{
// CONNECT TO THE DATABASE
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Database\\libsys\\libsys.mdb";
con = DriverManager.getConnection(url);
System.out.println("\nConnected to the database");
//QUERY THE DATABASE
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
//String SQL ="Select * from Members";
rs=stmt.executeQuery(SQL);
//MOVE CURSOR AT FIRST RECORD AND FETCH DATA
rs.next();
}
catch(ClassNotFoundException e)
{
System.out.println("\nClass not found. Check Path");
e.printStackTrace();
}
catch (SQLException err)
{
JOptionPane.showMessageDialog(null, err.getMessage());
}
}
}
UserLogin:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* UserLogin.java
*
* Created on Apr 23, 2011, 8:46:59 PM
*/
package LibSystem;
import java.sql.*;
import javax.swing.JOptionPane;
import java.lang.*;
/**
*
* #author Administrator
*/
public class UserLogin extends javax.swing.JFrame {
private String user;
private String password;
private String status;
/** Creates new form UserLogin */
public UserLogin() {
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() {
txtUserName = new javax.swing.JTextField();
txtPassword = new javax.swing.JTextField();
btnClose = new javax.swing.JButton();
btnLogin = new javax.swing.JButton();
lbUserName = new javax.swing.JLabel();
lbPassword = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnClose.setText("Close");
btnClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseActionPerformed(evt);
}
});
btnLogin.setText("Login");
btnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoginActionPerformed(evt);
}
});
lbUserName.setText("User Name");
lbPassword.setText("Password");
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(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lbPassword)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lbUserName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnClose)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE)
.addComponent(btnLogin))
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPassword, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE))))
.addGap(35, 35, 35))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(lbUserName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbPassword)
.addGap(5, 5, 5)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnClose)
.addComponent(btnLogin))
.addContainerGap(39, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//CREATE AN INSTANCE OF DBCONN CLASS TO CONNECT TO THE DATABASE
//WE TAKE THE USERNAME FROM THE LOGIN WINDOW AND SEARCH THE USER
//BASED ON THAT USER. IF FOUND, COMPARE IT WITH THE LOGIN WINDOW.
//IF NOT FOUND DISPLAY ERROR MESSAGE.
DBConn dbc = new DBConn();
String qry = "Select * from users where username=" + "'" + txtUserName.getText() + "'";
dbc.DoConnect(qry);
try
{
setUsername(dbc.rs.getString("username"));
setPassword(dbc.rs.getString("password"));
//TEST PRINTOUT OF USERNAME AND PASSWORD FOR DEBUGGING
System.out.println(getUsername());
System.out.println(getPassword());
if (user.equals(txtUserName.getText()) && password.equals(txtPassword.getText()))
{
JOptionPane.showMessageDialog(UserLogin.this, "Login Successfull");
this.setStatus("pass");
dispose();
}
else
{
JOptionPane.showMessageDialog(UserLogin.this, "Login unsuccessful");
setStatus("fail");
}
}
catch (SQLException err)
{
JOptionPane.showMessageDialog(UserLogin.this, err.getMessage());
}
}
private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.dispose();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UserLogin().setVisible(true);
}
});
}
public void setUsername(String u)
{
user = u;
}
public void setPassword(String p)
{
password = p;
}
public String getUsername()
{
return user;
}
public String getPassword()
{
return password;
}
public void setStatus(String stat)
{
status = stat;
}
public String getStatus()
{
return status;
}
// Variables declaration - do not modify
private javax.swing.JButton btnClose;
private javax.swing.JButton btnLogin;
private javax.swing.JLabel lbPassword;
private javax.swing.JLabel lbUserName;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUserName;
// End of variables declaration
}
LibSysMain:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* LibsysMain.java
*
* Created on Apr 23, 2011, 6:48:18 PM
*/
package LibSystem;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class LibsysMain extends javax.swing.JFrame {
String q;
/** Creates new form LibsysMain */
public LibsysMain()
{
initComponents();
//DBConn dbc = new DBConn();
//q="Select * from users";
//dbc.DoConnect(q);
}
// LibsysMain frame1 = new LibsysMain();
// UserLogin frame2 = new UserLogin(frame1);
/** 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() {
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jMenuBar1 = new javax.swing.JMenuBar();
miLogin = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 539, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 328, Short.MAX_VALUE)
);
jLabel1.setText("Status");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addContainerGap(518, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
);
jSeparator1.setAlignmentX(0.0F);
jSeparator1.setMinimumSize(new java.awt.Dimension(10, 10));
miLogin.setText("Connect");
miLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miLoginActionPerformed(evt);
}
});
jMenuItem1.setText("Login");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
miLogin.add(jMenuItem1);
jMenuItem2.setText("Exit");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
miLogin.add(jMenuItem2);
jMenuBar1.add(miLogin);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>
private void miLoginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
UserLogin ul = new UserLogin();
ul.setVisible(true);
//SET THE STATUS IF LOGIN IS SUCCESSFULL
if (ul.getStatus() == "pass")
{
jLabel1.setText("Logged In");
}
else
{
jLabel1.setText("Cannot Log in");
}
}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void formWindowActivated(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LibsysMain().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JMenu miLogin;
// End of variables declaration
}
I have a couple of suggestions:
For one, don't compare Strings with == as you do here if (ul.getStatus() == "pass") as this checks to see if two variables refer to the same String object (which you don't care about) but rather use either the equals or the equalsIgnoreCase method which checks to see if the two Strings contain the same String data (which you do care about). e.g., if (ul.getStatus().equalsIgnoreCase("pass"))
Be sure to do all of your database queries and whatnot in a thread background to the GUI's thread, the EDT such as can be achieved by using a SwingWorker object. This article will tell you what I said but will give you the details: Concurrency in Swing.
Consider using a single JFrame and modal dialogs to act as dialog windows to the main app. This can be achieved by using JOptionPanes or modal JDialogs, in particular for your UserLogin window.
For this reason, I like to gear my GUI's towards creating JPanels rather than top level windows such as JFrames. This way I can place my GUI/JPanel into any type of window I desire depending on the situation be it a JFrame, a JApplet, a JDialog, a JOptionPane, or even nested into another JPanel. This gives you an amazing amount of flexibilty.

Categories

Resources