I wan to have an inputStream that takes the value of a JTextbox and passes it into the Scanner object.
Scanner scan = new Scanner (System.in);
String input = scan.nextLine();
if (input.equalsIgnoreCase("New Match")) {
try {
newMatch(scan);
} catch (FileNotFoundException e) {
System.out.println("failed to load");
} catch (ArithmeticException e) {
}
}
if (input.equalsIgnoreCase("Load Match 1") || input.matches("1")){
try {
loadMatch(scan, "One");
} catch (FileNotFoundException e) {
System.out.println("failed to load");
} catch (ArithmeticException e) {
}
}
}
You can use a PipedOutputStream (doc) and a PipedInputStream (doc) to create a one-way pipeline which you can then use to route input from a text field into a Scanner. But you'll still have to figure out how to capture all the output that's going to System.out and display it to your GUI, nicely interwoven with the "echoed" input that came from your text field.
For what it's worth, though, I'll share a little proof-of-concept of half the solution. This program reads "commands" from a JTextField through a Scanner and produces simulated "responses" to them; a JTextArea keeps a record of the simulated "conversation". The input "commands" are logged automatically to the JTextArea, much as input from System.in would automatically echo to System.out, and I also explicitly echo them to System.out. However, my simulated "responses" go not to System.out but directly to the JTextArea`.
package test;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Scanner;
import javax.swing.JTextField;
public class PipeTest extends javax.swing.JFrame {
public PipedInputStream pi;
private PipedOutputStream po;
public PipeTest()
{
try {
pi = new PipedInputStream(); // You write data into this end...
po = new PipedOutputStream(pi); // ,,, and read it back out at this end.
} catch (IOException ioe) {
System.out.println("Failed to initialize pipe: " + ioe.toString());
}
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents()
{
jScrollPane1 = new javax.swing.JScrollPane();
historyText = new javax.swing.JTextArea();
jTextField1 = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
historyText.setColumns(20);
historyText.setRows(5);
jScrollPane1.setViewportView(historyText);
jTextField1.setText("jTextField1");
jTextField1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jTextField1ActionPerformed(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(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 369, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt)
{
JTextField tf = (JTextField) evt.getSource();
String text = tf.getText();
byte[] ca = (text + System.getProperty("line.separator")).getBytes();
try {
po.write(ca, 0, ca.length);
} catch (IOException ex) {
System.out.println("Failed to write to pipe: " + ex.toString());
}
historyText.append(text + "\n");
tf.setText("");
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) throws IOException
{
PipeTest pt = new PipeTest();
java.awt.EventQueue.invokeLater(() -> {
pt.setVisible(true);
});
Scanner scn = new Scanner(pt.pi);
while (scn.hasNextLine()) {
String line = scn.nextLine();
System.out.println(line);
java.awt.EventQueue.invokeLater(() ->
{
pt.historyText.append("Response to " + line + "\n");
});
}
}
// Variables declaration - do not modify
private javax.swing.JTextArea historyText;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
The way I interpret your question is that you have some existing code that is built on reading user input through an instance of Scanner. I think you're asking whether you can pull the text from a JTextField and push that into the instance of Scanner that is already used.
If the above understanding is correct and your Scanner instance is reading from System.in as it is in the code sample then my answer is no, you can't do exactly what you want.
However, you can get somewhat close to what you want.
Here is some code that creates a new Scanner each time the actionPerformed method is called and pushes data from a JTextField into that Scanner by simply passing the text from the text field into the scanner's constructor.
public void actionPerformed(java.awt.event.ActionEvent evt) {
scanner.close(); //Don't forget to close your scanner before you reassign it
String data = jTextField1.getText();
scanner = new Scanner(data);
//Just to illustrate the results I added a println here
System.out.println(scanner.nextLine());
}
Related
I'm new to the concept of creating a server and multiple clients using Java, so apologies if this is an obvious fix. I've been trying to code a jframe chat program that has a server and two clients, which currently are all using the same port. Whatever data is sent by client one will be passed to the server, which will display it. So far, the code does this, however, I also want to pass said data to the other client. I'm trying to code the program so that I can specify the client the data is sent to.
The code follows as:
Server Code.
package Chats;
import java.io.*;
import java.net.*;
public class Chat_Server extends javax.swing.JFrame
{
static ServerSocket ss;
static Socket s;
static DataInputStream din;
static DataOutputStream dout;
public Chat_Server()
{
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
Msg_Area = new javax.swing.JTextArea();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Msg_Area.setColumns(20);
Msg_Area.setRows(5);
jScrollPane1.setViewportView(Msg_Area);
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(32, 32, 32)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(36, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(39, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
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(Chat_Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Chat_Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Chat_Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Chat_Server.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new Chat_Server().setVisible(true);
}
});
String msgin = "";
try
{
ss = new ServerSocket(1201); // Server starts at 1201 port number
s = ss.accept(); // Now server will accept the connections.
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
while(!msgin.equals("exit"))
{
msgin = din.readUTF();
Msg_Area.setText(Msg_Area.getText().trim() + "\n Client: \t" + msgin); // Displaying the message from client
}
}
catch(Exception e)
{
}
}
// Variables declaration - do not modify
private static javax.swing.JTextArea Msg_Area;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
Client Code.
package Chats;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
public class Chat_Client extends javax.swing.JFrame
{
static Socket s;
static DataInputStream din;
static DataOutputStream dout;
public Chat_Client()
{
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
Msg_Text = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
Msg_Area = new javax.swing.JTextArea();
Msg_Send = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Msg_Text.setText("jTextField1");
Msg_Area.setColumns(20);
Msg_Area.setRows(5);
jScrollPane1.setViewportView(Msg_Area);
Msg_Send.setText("jButton1");
Msg_Send.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Msg_SendActionPerformed(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(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 332, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(Msg_Text, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addComponent(Msg_Send)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(Msg_Text, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(Msg_Send))
.addGap(23, 23, 23))
);
pack();
}// </editor-fold>
private void Msg_SendActionPerformed(java.awt.event.ActionEvent evt) {
try
{
String msgout = "";
msgout = Msg_Text.getText().trim();
dout.writeUTF(msgout);
}
catch (Exception e)
{
//handle exceptions here.
}
}
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(Chat_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Chat_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Chat_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Chat_Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new Chat_Client().setVisible(true);
}
});
try
{
s = new Socket ("127.0.0.1", 1201); // Here the ip ddress is local address.
din = new DataInputStream(s.getInputStream());
dout = new DataOutputStream(s.getOutputStream());
String msgin = "";
while (!msgin.equals("exit"))
{
msgin = din.readUTF();
Msg_Area.setText(Msg_Area.getText().trim() + "\n Server: \t" + msgin);
}
}
catch(Exception e)
{
//Exception Code
}
}
// Variables declaration - do not modify
private static javax.swing.JTextArea Msg_Area;
private javax.swing.JButton Msg_Send;
private javax.swing.JTextField Msg_Text;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration
}
I have another page set up for the other client but so far the code is a carbon copy of the first client page, so there's no point posting it.
You're only accepting a single client with ss.accept() and that's it. ServerSocket#accept waits for a SINGLE incoming client connection and creates a Socket object. In order to accept multiple connections you need continuously loop ss.accept() to keep listening for other client connections. Once a new connection is made you can add it to a list. (I have not tested the code, it's more just to point you in the direction you need)
public static void main(String []args) throw Exception{
ServerSocket serverSocket = new ServerSocket(1201);
List<Socket> clients = new ArrayList<Socket>();
while(true) {//continuously listening for a new connection
Socket client = serverSocket.accept();
clients.add(client);
}
}
Now the problem with this is that if your server constantly listens for a connection it'll block your thread. So everytime a connection is added, spawn a new thread to handle it.
public static void main(String []args) throw Exception{
ServerSocket serverSocket = new ServerSocket(1201);
List<Socket> clients = new ArrayList<Socket>();
while(true) {
Socket client = serverSocket.accept();
clients.add(client);
new Thread(new Runnable(){
public void run(){
//Handle socket here
}
}).start();
}
}
If you want to avoid creating multiple threads like this, then you're gonna have to use nio socketchannels.
I've got a little problem with JFormattedTextField:
I want to set the formatted text fields to numbers only. I've created one with Swing interface on NetBeans.
My code is as follows:
package SerasApp;
import static java.lang.System.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFormattedTextField;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
import javax.swing.text.NumberFormatter;
/**
* #author adam
*/
public class Main extends javax.swing.JFrame {
/**
* Creates new form Main
*/
public Main() {
initComponents();
}
//set position of label to be the center of the frame
public void PositionHiSera()
{
//find position of jpanel
int FrameHeight = this.Intro.getHeight();
int FrameWidth = this.Intro.getWidth();
int LabelSize[] = new int[2];
LabelSize[0] = HiSera.getWidth();
LabelSize[1] = HiSera.getHeight();
out.println(LabelSize[0]);
out.println(LabelSize[1]);
int Origin[] = new int[2];
Origin[1] = (FrameHeight/2)-(LabelSize[0]/2);
Origin[0] = (FrameWidth/2)-(LabelSize[1]/2);
//set label origin
HiSera.setLocation(Origin[1], Origin[0]);
}
public void HumidityLevel()
{
NumberFormat a = NumberFormat.getNumberInstance();
NumberFormatter b = new NumberFormatter(a);
DefaultFormatterFactory c = new DefaultFormatterFactory(b);
humidityLevel.setFormatterFactory(c);
}
/**
* 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() {
MainDisplayFrame = new javax.swing.JPanel();
Intro = new javax.swing.JPanel();
HiSera = new javax.swing.JLabel();
MainMenu = new javax.swing.JPanel();
WeatherOptions = new javax.swing.JPanel();
sunny = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
humidityLevel = new javax.swing.JFormattedTextField();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowFocusListener(new java.awt.event.WindowFocusListener() {
public void windowGainedFocus(java.awt.event.WindowEvent evt) {
formWindowGainedFocus(evt);
}
public void windowLostFocus(java.awt.event.WindowEvent evt) {
}
});
MainDisplayFrame.setLayout(new java.awt.CardLayout());
Intro.setMaximumSize(new java.awt.Dimension(30000, 30000));
HiSera.setText("Hi Sera");
javax.swing.GroupLayout IntroLayout = new javax.swing.GroupLayout(Intro);
Intro.setLayout(IntroLayout);
IntroLayout.setHorizontalGroup(
IntroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(IntroLayout.createSequentialGroup()
.addGap(209, 209, 209)
.addComponent(HiSera)
.addContainerGap(243, Short.MAX_VALUE))
);
IntroLayout.setVerticalGroup(
IntroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(IntroLayout.createSequentialGroup()
.addGap(225, 225, 225)
.addComponent(HiSera)
.addContainerGap(258, Short.MAX_VALUE))
);
MainDisplayFrame.add(Intro, "card2");
javax.swing.GroupLayout MainMenuLayout = new javax.swing.GroupLayout(MainMenu);
MainMenu.setLayout(MainMenuLayout);
MainMenuLayout.setHorizontalGroup(
MainMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, Short.MAX_VALUE, Short.MAX_VALUE)
);
MainMenuLayout.setVerticalGroup(
MainMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
);
MainDisplayFrame.add(MainMenu, "card2");
WeatherOptions.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
WeatherOptionsFocusGained(evt);
}
});
sunny.setText("Sunny");
sunny.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sunnyActionPerformed(evt);
}
});
jButton2.setText("Overcast");
jButton3.setText("Rainy");
jLabel1.setText("Humidity Level");
javax.swing.GroupLayout WeatherOptionsLayout = new javax.swing.GroupLayout(WeatherOptions);
WeatherOptions.setLayout(WeatherOptionsLayout);
WeatherOptionsLayout.setHorizontalGroup(
WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(WeatherOptionsLayout.createSequentialGroup()
.addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(WeatherOptionsLayout.createSequentialGroup()
.addGap(81, 81, 81)
.addComponent(sunny)
.addGap(75, 75, 75))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, WeatherOptionsLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(36, 36, 36)))
.addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(humidityLevel, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(WeatherOptionsLayout.createSequentialGroup()
.addComponent(jButton2)
.addGap(69, 69, 69)
.addComponent(jButton3)))
.addContainerGap(99, Short.MAX_VALUE))
);
WeatherOptionsLayout.setVerticalGroup(
WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(WeatherOptionsLayout.createSequentialGroup()
.addGap(225, 225, 225)
.addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(sunny)
.addComponent(jButton2)
.addComponent(jButton3))
.addGap(87, 87, 87)
.addGroup(WeatherOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(humidityLevel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(132, Short.MAX_VALUE))
);
MainDisplayFrame.add(WeatherOptions, "card2");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(MainDisplayFrame, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 500, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(MainDisplayFrame, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
PositionHiSera();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//make Intro Disappear and make Weather Options Appear
WeatherOptions.setVisible(true);
Intro.setVisible(false);
HumidityLevel();
out.println("tests");
}
private void sunnyActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void WeatherOptionsFocusGained(java.awt.event.FocusEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Main.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 Main().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel HiSera;
private javax.swing.JPanel Intro;
private javax.swing.JPanel MainDisplayFrame;
private javax.swing.JPanel MainMenu;
private javax.swing.JPanel WeatherOptions;
private javax.swing.JFormattedTextField humidityLevel;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JButton sunny;
// End of variables declaration
}
I've tried also to set a humidityLevel to new formatted text field to no avail.
Mainly it's this bit of code:
public void HumidityLevel()
{
NumberFormat a = NumberFormat.getNumberInstance();
NumberFormatter b = new NumberFormatter(a);
DefaultFormatterFactory c = new DefaultFormatterFactory(b);
humidityLevel.setFormatterFactory(c);
}
and this bit:
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
PositionHiSera();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
//make Intro Disappear and make Weather Options Appear
WeatherOptions.setVisible(true);
Intro.setVisible(false);
HumidityLevel();
out.println("tests");
}
I also don't want to use a JTextField because I want to learn how to use JFormattedTextField.
I want to set the formatted text fields to numbers only.
Using the Design view, right click over the formatted text field and choose Properties option. Then look for formatterFactory property:
If you try to edit this property, the following dialog will show up. Choose integer default option under number category:
That's it, your text field will be initialized using NumberFormat.getIntegerInstance(). If you inspect the generated source code you'll see something like this:
jFormattedTextField1 = new javax.swing.JFormattedTextField();
jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(java.text.NumberFormat.getIntegerInstance())));
Off-topic
As #mKorbel pointed out, using Thread.sleep() is a bad idea and will block the Event Dispatch Thread (EDT) which is a single and special thread where Swing components creation / update should be performed and event handling is processed. If this thread is blocked then your GUI won't be able to repaint itself and will "freeze". In this case you should consider use a Swing Timer instead. See Concurrency in Swing for further details.
I would like to implement a "Find Menu" in my simple notepad application in java but when I find a certain word,It just jumps up to the second similar word in the JTextArea, can anyone point out where I am wrong and how to furnish it? and I dont want to use Highlighter, just the select() method .. I would appreciate any help you can do. Im just new to programming.
/**
*
* #author aLwAyz
*/
public class FindDemo extends javax.swing.JDialog {
/**
* Creates new form FindDemo
*/
public FindDemo(java.awt.Frame parent, boolean modal) {
super(parent, modal);
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() {
dlgFind = new javax.swing.JDialog();
btnFind = new javax.swing.JButton();
txtInput = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
txaField = new javax.swing.JTextArea();
btnOpenFindDialog = new javax.swing.JButton();
dlgFind.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
btnFind.setText("Find");
btnFind.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFindActionPerformed(evt);
}
});
txtInput.setMinimumSize(new java.awt.Dimension(400, 100));
javax.swing.GroupLayout dlgFindLayout = new javax.swing.GroupLayout(dlgFind.getContentPane());
dlgFind.getContentPane().setLayout(dlgFindLayout);
dlgFindLayout.setHorizontalGroup(
dlgFindLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, dlgFindLayout.createSequentialGroup()
.addContainerGap(77, Short.MAX_VALUE)
.addComponent(txtInput, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(63, 63, 63)
.addComponent(btnFind)
.addGap(96, 96, 96))
);
dlgFindLayout.setVerticalGroup(
dlgFindLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(dlgFindLayout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(dlgFindLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnFind)
.addComponent(txtInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(28, Short.MAX_VALUE))
);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setModalExclusionType(null);
setModalityType(null);
txaField.setColumns(20);
txaField.setRows(5);
jScrollPane1.setViewportView(txaField);
btnOpenFindDialog.setText("Find");
btnOpenFindDialog.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnOpenFindDialogActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnOpenFindDialog)
.addGap(72, 72, 72))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(btnOpenFindDialog)
.addGap(35, 35, 35)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void btnOpenFindDialogActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
dlgFind.pack();
dlgFind.setLocationRelativeTo(null);
dlgFind.show();
}
private void btnFindActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String text = txtInput.getText();
String txa = txaField.getText();
int length = text.length();
String selected = txaField.getSelectedText();
int selIn = 0;
if (txaField.getSelectedText() != null) selIn = txa.indexOf(selected);
int inSelected = selIn + length;
if (txaField.getSelectedText() == null) inSelected = 0;
int index = txa.indexOf(text, inSelected);
if (txa.contains(text)) {
txaField.select(index, index + length);
}
}
/**
* #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(FindDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FindDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FindDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FindDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
FindDemo dialog = new FindDemo(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnFind;
private javax.swing.JButton btnOpenFindDialog;
private javax.swing.JDialog dlgFind;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea txaField;
private javax.swing.JTextField txtInput;
// End of variables declaration
}
That is my code. Im sorry if there are many redundancies because like I've said, im just new to programming. Thank You.
-By the way, I am using NetBeans IDE 8.0
-Sorry if it took me time
when I find a certain word,It just jumps up to the second similar word in the JTextArea,
When I try the code, the first time you press "Find" it selects the first occurrence of the word. Then if you press Find again it selects the second occurrence of the word. If you press "Find" again it stays on the second occurrence of the word.
So as I suggested in my comment you need to get rid of your "selection logic" and get the basic search working properly first.
Normally when you do a search you start the search from the caret position. This will allow you to continually press the "Find" button to move on to the next occurrence of the word. This works because when you "select" the found word, the caret is moved to the end of the word, so when you press "Find" the next time the caret postion is set at the end of the word, ready to search for the next word.
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.
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);
}
});