I want to open a file without taking any time.When I click on open Button immediately it has been opened.But,In my application It has taken more than two minutes for large files.I try to open a file,It has size 44MB.This file takes more than two minutes time to open.I want to open large size files quickly.Once check my open action code.
The below code shows the working example of my Application.
Sample code:
public class OpenDemo extends javax.swing.JFrame {
JTextPane textPane;
JScrollPane scrollPane;
int i=0;
JTextField status;
public OpenDemo() {
initComponents();
textPane=new JTextPane();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tp = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
open = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
open.setText("Open");
open.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openActionPerformed(evt);
}
});
jMenu1.add(open);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void openActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser=new JFileChooser();
int result = fileChooser.showOpenDialog(this);
if (result==JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
textPane.setPage(file.toURI().toURL());
} catch(Exception e) {
e.printStackTrace();
}
}
scrollPane=new JScrollPane(textPane);
tp.add(scrollPane);
textPane.setCaretPosition(0);
}
public static void main(String args[]) {
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(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OpenDemo().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JTabbedPane tp;
// End of variables declaration
}
The SwingWorker API outlines a suitable approach. Because of the size, I'd update a TableModel, as shown here, rather than a text component. Lines will begin appearing almost immediately, while the GUI remains responsive. The listening JTable will need to render only visible lines, and you may be able to leverage sorting and filtering.
There is some overhead (progress animation) and some things I would not have done, like a AWT event thread blocking actionPerformed.
Go with your code to https://codereview.stackexchange.com/ because a code review might be useful.
What I saw as optimizable:
Give an initial capacity to the StringBuilder.
... = new StringBuilder(1024*64); // (int)file.length()?
Replace the Scanner with a BufferdReader using readLine().
Ideal would be to check the speed of Files.readAllBytes; whether a progress indication is needed.
String s = new String(Files.readAllBytes(file.toPath()));
Second attempt:
First a sanity measure: closing the file.
Then I did less progress animation, which should definitely speed things up.
It will no longer show all text in the text pane, only every hundredth line.
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
final int PROGRESS_EVERY = 100;
while ((line = br.readLine()) != null) {
lineNumber++;
text.append(line);
text.append("\n");
if (linenumber % PROGRESS_EVERY== 0) {
ProgressData data = new ProgressData();
data.number = lineNumber;
data.line = line;
publish(data);
}
}
if (linenumber % PROGRESS_EVERY != 0) {
ProgressData data = new ProgressData();
data.number = lineNumber;
data.line = line;
publish(data);
}
}
And then
private StringBuilder text = new StringBuilder(1024 * 128);
At last:
Change textPane from JTextPane to JTextArea. Considerable gain in speed.
Related
I want to display username in a jLabelon welcome jFrame when user is successfully logged in. I'm doing this project with Netbeans and used DBMS is MySQL. Basically I created two jFrames.
One as login.java and other as welcome.java. The jLabel is placed in welcome.java and variable name initialized as jLabel_UnameDisplay.
Here is picture explanation of my requirement and total codes of the project:
login.java
public class login extends javax.swing.JFrame {
public login() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
jPanel = new javax.swing.JPanel();
jLabel_uname = new javax.swing.JLabel();
jLabel_pass = new javax.swing.JLabel();
txt_uname = new javax.swing.JTextField();
txt_pass = new javax.swing.JPasswordField();
jButton_login = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel_uname.setText("User Name");
jPanel.add(jLabel_uname, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 110, 100, 40));
jLabel_pass.setText("Password");
jPanel.add(jLabel_pass, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 170, 100, 40));
jPanel.add(txt_uname, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 110, 160, 40));
jPanel.add(txt_pass, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 170, 160, 40));
jButton_login.setText("Login");
jButton_login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton_loginActionPerformed(evt);
}
});
jPanel.add(jButton_login, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 230, 90, 40));
getContentPane().add(jPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 300));
pack();
}
private void jButton_loginActionPerformed(java.awt.event.ActionEvent evt) {
if (txt_uname.getText().equals("admin")&&txt_pass.getText().equals("1234")){
new welcome().setVisible(true);
this.dispose();
}else{
try {
Connection c;
Class.forName("com.mysql.jdbc.Driver");
c=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","123");
Statement s=c.createStatement();
ResultSet rs= s.executeQuery("SELECT * FROM user WHERE status='1'");
while (rs.next()) {
String unmae=rs.getString("username");
String pass=rs.getString("password");
if(unmae.equals(txtuname.getText()) && pass.equals(txtpass.getText())){
new welcome().setVisible(true);
this.dispose();
}
}
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(rootPane, "Check Your Username or Password","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String args[]) {
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.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new login().setVisible(true);
}
});
}
private javax.swing.JButton jButton_login;
private javax.swing.JLabel jLabel_pass;
private javax.swing.JLabel jLabel_uname;
private javax.swing.JPanel jPanel;
private javax.swing.JPasswordField txt_pass;
private javax.swing.JTextField txt_uname;
}
welcome.java
public class welcome extends javax.swing.JFrame {
public welcome() {
initComponents();
}
#SuppressWarnings("unchecked")
private void initComponents() {
jPanel = new javax.swing.JPanel();
jLabel_UnameDisplay = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabel_UnameDisplay.setBackground(new java.awt.Color(102, 255, 102));
jLabel_UnameDisplay.setOpaque(true);
jPanel.add(jLabel_UnameDisplay, new org.netbeans.lib.awtextra.AbsoluteConstraints(93, 69, 199, 126));
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)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}
public static void main(String args[]) {
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(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new welcome().setVisible(true);
}
});
}
private javax.swing.JLabel jLabel_UnameDisplay;
private javax.swing.JPanel jPanel;
}
There's a number of ways you might do it, but what you want to aim for is decoupling the login frame from the welcome frame, so that the decision to show one is not made by the other.
You could
Use some kind of observer/delegate/listener that is notified when the user is correctly authenticated, passing the user information to it. It would then be it's responsibility to decide what to do next, in this, show the welcome view, passing it the user information (as an example)
This is common concept in Swing
You could
Use some kind of dialog (instead of a JFrame) which would allow the code to block at the point the dialog is made visible and continuing when it's closed.
In this case, you would need to provide some kind of getter to get the user details (or null if the user cancelled the dialog for some reason), you would then be able to make a decision about what to do based on the result
Have a look at How to use dialogs for more details.
In any case, you will need to be able to pass the information in the login view to the welcome view, the means is generally very common, make use of setters and getters and basic method calling.
The easiest way is to pass the user name to the next frame on creation. So that next fame like welcome-page can use the user name. You can also pass a whole object that can store more user-specific data.
Here is the code samples. Make thin change in welcome page
/**
* Create the frame and pass the parameter during creation
*/
public welcome (Component parent, String logOnUserName) {
this.parent = parent; // This is to send the reference of parent login
// page. This can be useful if you want to
// comeback to loginpage
this.logOnUserName=logOnUserName;
...
And while calling the welcome page from login make this change
new login(this, username).setVisible(true);
Now username is available in the welcome page. Show it in UI.
I have best answer of this question. When you click on Login button then you have to specify there new frame then go to database and choose which column you want to display on after login frame. You can display with using JLable. Also you can provide reference of this video :
https://youtu.be/vlYLzCzZigg
I have a FileFinder.java and a Loading.java class with a GUI. The FileFinder.java allows users to select a directory and search for a file in that directory. Now, with larger directories, the search takes a few moments to complete, and I don't want users to wonder if it's actually searching, so I am trying to display another frame (Loading.java).
Here is my code for when the Search button is clicked:
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String dirName = "";
String username = System.getProperty("user.name");
if(cdriveButton.isSelected()){
dirName = "C:/Users/" + username;
}
else if(pdriveButton.isSelected()){
dirName = "P:";
}
else if(xdriveButton.isSelected()){
dirName = "X:";
}
else if(customButton.isSelected()){
dirName = JOptionPane.showInputDialog(rootPane, "Enter the directory you would like to search in: ", "Enter Directory", HEIGHT);
}
String search = filenameText.getText();
File root = new File(dirName);
resultText.setText("");
Loading show = new Loading();
show.setVisible(true);
displayDirectoryContents(root, search);
show.setVisible(false);
}
Here is the Loading.java:
public class Loading extends javax.swing.JFrame {
/**
* Creates new form Loading
*/
public Loading() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Please wait...");
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(148, 148, 148)
.addComponent(jLabel1)
.addContainerGap(186, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(122, 122, 122)
.addComponent(jLabel1)
.addContainerGap(164, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #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(Loading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Loading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Loading.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Loading.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 Loading().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
Everything works fine, except for one small issue: it is not displaying the GUI properly inside of the Loading frame. It pops up when I press the button as it should, and remains there until the search is finished, and closes properly, but it should be displaying a label that says "Please wait...". It is not showing that label, it just displays a blank white frame.
Edit1: Solution found below. Convert to JDialog pane instead of JFrame and add a SwingWorker:
JDialog jDialog = new JDialog();
jDialog.setLayout(new GridBagLayout());
jDialog.add(new JLabel("Please wait..."));
jDialog.setMinimumSize(new Dimension(150, 50));
jDialog.setResizable(false);
jDialog.setModal(false);
jDialog.setUndecorated(true);
jDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
jDialog.setLocationRelativeTo(null);
jDialog.setVisible(true);
SwingWorker swingWorker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
displayDirectoryContents(root, search);
return null;
}
};
Your problem is here:
displayDirectoryContents(root, search);
You're running this on the Java event thread or EDT (event dispatch thread). When this takes more than a moment to run, it blocks the EDT and prevents it from doing what it needs to do, including showing your loading window (which incidentally should be a dialog window such as a JDialog and not an application window or JFrame).
The solution: run this method call in a background thread such as that given by a SwingWorker. Display your dialog window, and use a call back to notify you when the worker is done and thus when you should no longer display the loading dialog window.
For example, this:
String search = filenameText.getText();
File root = new File(dirName);
resultText.setText("");
Loading show = new Loading();
show.setVisible(true);
displayDirectoryContents(root, search);
show.setVisible(false);
could be changed to something like (note code not tested)
String search = filenameText.getText();
File root = new File(dirName);
resultText.setText("");
Loading show = new Loading();
show.setVisible(true);
// create our worker
new SwingWorker<Void, Void> worker = new SwingWorker<>(){
#Override
protected Void doInBackground() throws Exception {
displayDirectoryContents(root, search);
return null;
}
};
worker.addPropertyChangeListener(evt -> {
if (SwingWorker.StateValue.DONE == evt.getNewValue()) {
// you should also call get() on the worker allowing
// you to capture and handle all exceptions it might throw
show.setVisible(false);
}
});
worker.execute(); // run the worker
For more, please check out: Lesson: Concurrency in Swing
Refer to #Hovercraft of eels answer for the solution to your problem.
As a side answer, it is bad practice to use multiple JFrames, instead I recommend you use a JDialog. See this example:
JDialog jDialog = new JDialog();
jDialog.setLayout(new GridBagLayout());
jDialog.add(new JLabel("Please wait..."));
jDialog.setMinimumSize(new Dimension(150, 50));
jDialog.setResizable(false);
jDialog.setModal(false);
jDialog.setUndecorated(true);
jDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
jDialog.setLocationRelativeTo(null);
jDialog.setVisible(true);
This will display the message "Please wait..." in a small grey box in the centre of the screen, with no close button or title bar.
It is also non-blocking due to the setModal(false) option. So other code can execute while it is displayed.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to display the dot instead of space whenever click on the View-spaces checkbox MenuItem.My problem is when I click the checkbox it is replacing space with dot but,After when I add some extra text to textarea and click on Viewspace JCheckBox menuitem,it had taken the previous text only and replaced.I have Tried this,Please run my code You can easily understand the problem.Please give some suggestions.....Thank you.
Here is my code:
public class VisibleSpaces extends javax.swing.JFrame {
int i=0;
JTextArea tx,lnNum;
JScrollPane scrollpane;
public VisibleSpaces() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
tp = new javax.swing.JTabbedPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
Create = new javax.swing.JMenuItem();
ViewSpace = new javax.swing.JCheckBoxMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
Create.setText("Create");
Create.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CreateActionPerformed(evt);
}
});
jMenu1.add(Create);
ViewSpace.setSelected(true);
ViewSpace.setText("ViewSpaces");
ViewSpace.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ViewSpaceActionPerformed(evt);
}
});
jMenu1.add(ViewSpace);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void ViewSpaceActionPerformed(java.awt.event.ActionEvent evt) {
ViewSpace.addItemListener(new ItemListener() {
String str=tx.getText();
String previous=str;
#Override
public void itemStateChanged(ItemEvent ie) {
if(ViewSpace.getState()){
tx.setText(previous.replace(" ","."));
}
else
tx.setText(str);
}
});
}
private void CreateActionPerformed(java.awt.event.ActionEvent evt) {
final JInternalFrame internalFrame = new JInternalFrame("");
i++;
internalFrame.setName("Document"+i);
internalFrame.setClosable(true);
internalFrame.setAutoscrolls(true);
tx=new JTextArea();
tx.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
scrollpane=new JScrollPane(tx);
internalFrame.add(scrollpane);
tp.add(internalFrame);
internalFrame.setSize(internalFrame.getMaximumSize());
internalFrame.pack();
internalFrame.setVisible(true);
}
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(VisibleSpaces.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(VisibleSpaces.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(VisibleSpaces.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(VisibleSpaces.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new VisibleSpaces().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem Create;
private javax.swing.JCheckBoxMenuItem ViewSpace;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tp;
// End of variables declaration
}
Your code is not proper, its full with bad practice. After a lot of effort I understood your problem. I am just giving the solution of the specific problem, but try to follow the comments given to your question for better understanding of the uses of Java swing components.
Solution:
change this portion of your code
public void itemStateChanged(ItemEvent ie) {
if(ViewSpace.getState()){
tx.setText(previous.replace(" ","."));
}
else
tx.setText(str);
}
with this one
public void itemStateChanged(ItemEvent ie) {
if(ViewSpace.getState()){
tx.setText(tx.getText().replace(" ","."));
}
else
{
String last = tx.getText().substring(tx.getText().length()-1, tx.getText().length());
String rest = tx.getText().substring(0, tx.getText().length()-1);
if(!last.equals("."))
tx.setText(tx.getText().replace("."," "));
else
{
rest=rest.replace("."," ");
tx.setText(rest+".");
}
}
I am new to working with Java GUI, I know this may sound ridiculous but I have been trying for days to pass data between cards on the CardLayout layout. I am using netbeans, the first card displays a list clients. When a client is selected, the choice selection is passed to a variable on that card. The next card queries the database to show more details about the client selected. I can handle the switching between cards but my problem is I can't pass the data stored in the variable on card 1 to card 2.
I have visited several forums and read through similar questions asked but I just cannot get any of the proposed solutions to work. Please help, I'm new at this so please go easy on me, thanks.
Here is the class that holds the panels
public class mainframe extends javax.swing.JFrame {
public mainframe() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
displayScrollPane = new javax.swing.JScrollPane();
displaypanel = new javax.swing.JPanel();
viewclientspanel1 = new viewclientspanel();
addclientpanel1 = new addclientpanel();
clientdetails1 = new clientdetails();
mainmenu = new javax.swing.JMenuBar();
clients = new javax.swing.JMenu();
viewclients = new javax.swing.JMenuItem();
addclient = new javax.swing.JMenuItem();
transactions = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
displaypanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
displaypanel.setLayout(new java.awt.CardLayout());
viewclientspanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
viewclientspanel1MouseClicked(evt);
}
});
displaypanel.add(viewclientspanel1, "viewclientscard");
displaypanel.add(addclientpanel1, "addclientcard");
displaypanel.add(clientdetails1, "clientdetailscard");
displayScrollPane.setViewportView(displaypanel);
clients.setText("Clients");
viewclients.setText("View Clients");
viewclients.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewclientsActionPerformed(evt);
}
});
clients.add(viewclients);
viewclients.getAccessibleContext().setAccessibleParent(mainmenu);
addclient.setText("Add Client");
addclient.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addclientActionPerformed(evt);
}
});
clients.add(addclient);
mainmenu.add(clients);
transactions.setText("Transactions");
mainmenu.add(transactions);
setJMenuBar(mainmenu);
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(displayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 1059, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(99, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(66, Short.MAX_VALUE)
.addComponent(displayScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 570, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33))
);
pack();
}// </editor-fold>
private void addclientActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout card = (CardLayout) displaypanel.getLayout();
card.show(displaypanel, "addclientcard");
}
private void viewclientsActionPerformed(java.awt.event.ActionEvent evt) {
CardLayout card = (CardLayout) displaypanel.getLayout();
card.show(displaypanel, "viewclientscard");
}
private void viewclientspanel1MouseClicked(java.awt.event.MouseEvent evt) {
//viewclientspanel1.getComponentListeners();
}
/**
* #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(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(mainframe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new mainframe().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JMenuItem addclient;
private addclientpanel addclientpanel1;
private clientdetails clientdetails1;
private javax.swing.JMenu clients;
private javax.swing.JScrollPane displayScrollPane;
private javax.swing.JPanel displaypanel;
private javax.swing.JMenuBar mainmenu;
private javax.swing.JMenu transactions;
private javax.swing.JMenuItem viewclients;
private viewclientspanel viewclientspanel1;
// End of variables declaration
}
The class of the card that displays a list of the clients to choose from has a mouse event listener which gets the value of the client selected and switches the the next card
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
CardLayout card = (CardLayout) jPanel1.getParent().getParent().getParent().getParent().getLayout();
card.show(jPanel1.getParent().getParent().getParent().getParent(), "clientdetailscard");
}
Lastly the class that I need to transfer the client selected information to which dsiplays the more details.
public class clientdetails extends javax.swing.JPanel {
public clientdetails() {
initComponents();
}
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(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(addclient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
JFrame f = new JFrame("Window");
f.add(new clientdetails());
f.setSize(500, 700);
f.setVisible(true);
}
private javax.swing.JPanel jPanel1;
}
You could pass the client information from one pane to the other using setters/getters...
clientDetailsPane.setClient(clientListPanel.getClient());
// Switch panels...
I was also thinking that you could use some kind of model or Map, but that is probably overkill for what you want to achieve...
Thanks a lot guys, I ended up using a class container to hold the variables I need transferred.
public class varcontainer {
public String variablename;
private static varcontainer instance = null;
public static varcontainer getInstance(){
if(instance == null){
instance = new varcontainer();
}
return instance;
}
}
I then call the getInstance from another class to get the current instance of the container and access the variables
varcontainer.getInstance().variablename
Thanks again for the feedback, I appreciate it.
I made a small program that listens and sends lines on a tcp socket and appends the received info to a JTextArea. I use this to chat on a Minecraft server without having the game open.
I was working fine last night, but when I got up it wasn't working. When I opened netbeans and ran it, it gave this error:
Exception in thread "main" java.lang.NullPointerException
at com.xxx.mcchat.chat.main(chat.java:333)
Can anyone explain what's wrong?
Here is the code (http://pastebin.com/FPNty0qf):
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.xxx.mcchat;
import java.io.*;
import java.net.*;
import net.sf.json.*;
import org.apache.commons.beanutils.*;
import org.apache.commons.collections.*;
import org.apache.commons.lang.*;
import net.sf.ezmorph.*;
import org.apache.commons.logging.*;
import java.awt.event.*;
import javax.swing.UIManager;
/**
*
* #author xxx
*/
public class chat extends javax.swing.JFrame {
/**
* Creates new form chat
*/
public chat() {
initComponents();
}
public void send(String user, String message){
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("mc.xxx.net", 20060);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
System.exit(1);
}
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
//System.out.println(in.readLine()); //Uncomment to debug
if(username != null){
out.println("/api/call?method=broadcast&args="+"[\"§7[Web] §b"+username+"§7:§f "+message+"\"]"+"&key=f0e2ad47a9a43c783d2c54f396f655c9279829c8c69ae9f52934648098dec993");
chatArea.append(username + ": " + message + "\n\r");
if(autoscrollCheck.isSelected()){
chatArea.setCaretPosition(chatArea.getText().length() - 1);
}
}else{
chatArea.append("You must set your username!!" + "\n\r");
if(autoscrollCheck.isSelected()){
chatArea.setCaretPosition(chatArea.getText().length() - 1);
}
}
}
/**
* 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() {
jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem();
jToggleButton1 = new javax.swing.JToggleButton();
jScrollPane1 = new javax.swing.JScrollPane();
chatArea = new javax.swing.JTextArea();
input = new javax.swing.JTextField();
send = new javax.swing.JButton();
user = new javax.swing.JTextField();
userset = new javax.swing.JButton();
autoscrollCheck = new javax.swing.JCheckBox();
jLabel1 = new javax.swing.JLabel();
jCheckBoxMenuItem1.setSelected(true);
jCheckBoxMenuItem1.setText("jCheckBoxMenuItem1");
jToggleButton1.setText("jToggleButton1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Minecraft Chat");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
chatArea.setEditable(false);
chatArea.setBackground(new java.awt.Color(0, 0, 0));
chatArea.setColumns(20);
chatArea.setFont(new java.awt.Font("Consolas", 0, 14)); // NOI18N
chatArea.setForeground(new java.awt.Color(255, 255, 255));
chatArea.setLineWrap(true);
chatArea.setRows(5);
jScrollPane1.setViewportView(chatArea);
input.setToolTipText("Enter message here");
input.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
inputKeyPressed(evt);
}
});
send.setText("Send");
send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendActionPerformed(evt);
}
});
user.setToolTipText("");
user.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
userActionPerformed(evt);
}
});
user.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
userKeyPressed(evt);
}
});
userset.setText("Set");
userset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
usersetActionPerformed(evt);
}
});
autoscrollCheck.setSelected(true);
autoscrollCheck.setText("Auto Scroll");
autoscrollCheck.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
autoscrollCheckActionPerformed(evt);
}
});
jLabel1.setText("Enter Username:");
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(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(user, javax.swing.GroupLayout.PREFERRED_SIZE, 218, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(userset)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(autoscrollCheck))
.addComponent(jScrollPane1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(input, javax.swing.GroupLayout.PREFERRED_SIZE, 649, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(send)))
.addGap(10, 10, 10))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(user, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1)))
.addComponent(userset)
.addComponent(autoscrollCheck))
.addGap(6, 6, 6)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
.addGap(6, 6, 6)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(send))
.addGap(11, 11, 11))
);
pack();
}// </editor-fold>
String username = null;
private void inputKeyPressed(java.awt.event.KeyEvent evt) {
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
send(username, input.getText());
input.setText("");
}
}
private void sendActionPerformed(java.awt.event.ActionEvent evt) {
send(username, input.getText());
input.setText("");
}
private void usersetActionPerformed(java.awt.event.ActionEvent evt) {
if(username == null){
if(!"".equals(user.getText())){
username = user.getText();
chatArea.append("Username set!"+"\n\r");
if(autoscrollCheck.isSelected()){
chatArea.setCaretPosition(chatArea.getText().length() - 1);
}
}else{
chatArea.append("Username can not be blank."+"\n\r");
if(autoscrollCheck.isSelected()){
chatArea.setCaretPosition(chatArea.getText().length() - 1);
}
}
}else{
send(username, "§7changed name to " + user.getText());
username = user.getText();
}
}
private void userActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void userKeyPressed(java.awt.event.KeyEvent evt) {
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
if(username == null){
if(!"".equals(user.getText())){
username = user.getText();
chatArea.append("Username set!"+"\n\r");
if(autoscrollCheck.isSelected()){
chatArea.setCaretPosition(chatArea.getText().length() - 1);
}
}else{
chatArea.append("Username can not be blank."+"\n\r");
if(autoscrollCheck.isSelected()){
chatArea.setCaretPosition(chatArea.getText().length() - 1);
}
}
}else{
send(username, "§7changed name to " + user.getText());
username = user.getText();
}
}
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
}
private void autoscrollCheckActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) throws IOException {
/* Set the system look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code ">
/* 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 {
javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(chat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new chat().setVisible(true);
}
});
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket("mc.xxx.net", 20060);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
System.exit(1);
}
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
//System.out.println(in.readLine()); //Uncomment to debug
out.println("/api/subscribe?source=chat&key=1e287587f5d1d45255f4708467eeaf8a71085f9ccfd8a354523d233cf5a77be4&show_previous=true");
out.println("/api/subscribe?source=connections&key=e410592b70c0288654e6c1040edb0f21811dcb3f2ee11051163f36be9be00788&show_previous=false");
while(true){
String jsonString = in.readLine();
JSONObject obj = JSONObject.fromObject(jsonString);
JSONObject success = obj.getJSONObject("success");
if(success.get("message") != null){
chatArea.append("<" + success.get("player") + "> " + success.get("message") + "\n\r");
if(autoscrollCheck.isSelected()){
chatArea.setCaretPosition(chatArea.getText().length() - 1);
}
}else if (success.get("action") != null){
chatArea.append(success.get("player") + " " + success.get("action") + "\n\r");
if(autoscrollCheck.isSelected()){
chatArea.setCaretPosition(chatArea.getText().length() - 1);
}
}
}
}
// Variables declaration - do not modify
public static javax.swing.JCheckBox autoscrollCheck;
public static javax.swing.JTextArea chatArea;
private javax.swing.JTextField input;
private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JToggleButton jToggleButton1;
private javax.swing.JButton send;
private javax.swing.JTextField user;
private javax.swing.JButton userset;
// End of variables declaration
}
(P.S Please don't get grumpy because I'm using a GUI generator, this is my first program, I promise I will learn to do it by hand )
The only thing that can be null at line 333 is chatArea. (If success were null, it would've thrown an exception in the if statement at line 332.) As others have suggested, you probably have a race condition where it's not being initialized before line 333 is reached.
The correct way to fix it is to enclose chatArea calls in a call to SwingUtilities.invokeLater:
final JSONObject success = obj.getJSONObject("success");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (success.get("message") != null) {
chatArea.append("<" + success.get("player") + "> " + success.get("message") + "\n\r");
if (autoscrollCheck.isSelected()) {
chatArea.setCaretPosition(chatArea.getText().length() - 1);
}
} else if (success.get("action") != null) {
chatArea.append(success.get("player") + " " + success.get("action") + "\n\r");
if (autoscrollCheck.isSelected()) {
chatArea.setCaretPosition(chatArea.getText().length() - 1);
}
}
}
});
Any time you make a change to a Swing component, you should call it in the event dispatch thread. What's more, since the EDT is single-threaded, queue-based kind of executor, this is guaranteed to wait until the runnable you submitted earlier is done, so chatArea will definitely be set.
One other note: it's generally good practice to wrap UIManager calls in an invokeLater call as well.
Edit: I just want to be a little more clear about what you should always wrap in an invokeLater call:
Constructing Swing components
Changing properties of Swing components
Modifying the data model of a Swing component (not necessarily getting the data, just telling the component that cares that it has changed, such as firing events, needs to happen on the EDT)
Modifying UIManager properties, including setting the look and feel or modifying the values of its keys
Instantiating a look and feel
Instantiating sublcasses of ComponentUI
Adding and removing components to and from a container
Things that don't need to be wrapped:
Changing properties on components that aren't displayed yet According to Robin in the comments, this still needs to happen on the EDT.
Calls to repaint
Calls to validate, or invalidate (I think, I need to find confirmation on this)
Do all this, and any time you switch to a new look and feel, you won't have any problems with things not being called on the EDT.
Long story short, Swing isn't thread-safe, so you should always call Swing component methods from the event dispatch thread.
Also, I welcome any suggestions for my list about things I may have forgotten.
Here's are some resources that describe threading in Swing:
Java SE 6 javax.swing javadocs
Java trail on Swing concurrency
Old blog post about the decision to make Swing single-threaded (in case you're curious)
The problem is that you're readily switching between static and non-static data. Initially, the program runs main() (static). Therein, you reference chatArea (line 333, also static). However, chatArea is only set upon calling initComponents() (non-static), which happens in the constructor (non-static). This will not always be called before the remainder of the function.
Based on your invokeLater methodology, you should move everything related to the chat program, which comes after invokeLater, into the constructor (or some method which is not static).
Basically, the only thing that should be static is your main() method. The rest should not be static. If it helps, separate things into a new class, which you reference from main(); this will help you initialize the program, then run all your chat-related things.
It is probably a race condition which makes it work sometimes. The variable chatArea is not guaranteed to be initialized by the time the main thread gets to line 333. This is due to the deferred initialization of the GUI via invokeLater() some lines before that:
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new chat().setVisible(true);
}
});
You need some synchronization between those threads, or, what also should work, just initialize the GUI in the main thread:
final chat chatObject = new chat();
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
chatObject.setVisible(true);
}
});