How to transfer outputs of methods to the dialog boxes? - java

try {
project.fireBuildStarted();
project.init();
ProjectHelper projectHelper = ProjectHelper.getProjectHelper();
project.addReference("ant.projectHelper", projectHelper);
projectHelper.parse(project, buildFile);
// If no target specified then default target will be executed.
String targetToExecute = (target != null && target.trim().length() > 0) ? target
.trim() : project.getDefaultTarget();
project.executeTarget(targetToExecute);
project.fireBuildFinished(null);
success = true;
} catch (BuildException buildException) {
project.fireBuildFinished(buildException);
JOptionPane.showMessageDialog(null, buildException, "Warning",
JOptionPane.WARNING_MESSAGE);
throw new RuntimeException(
"!!! Unable to restart the IEHS App !!!", buildException);
}
Above methods are giving some output on the console, but I need them in the dialog boxes. How can I do that ?

I think you are trying to capture the console logs to a UI component, if that is the case, here is the sample which will create output stream and capture console output and show it in UI component. You can try this.
public class Console extends JDialog {
JTextArea textArea = null;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Console dialog = new Console();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
private void updateTextPane(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}
/**
* Create the dialog.
*/
public Console() {
//Creating a stream to move consle output to anything else
OutputStream out = new OutputStream() {
#Override
public void write(final int b) throws IOException {
updateTextPane(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextPane(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
setBounds(100, 100, 450, 300);
getContentPane().setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("hello");
}
});
btnNewButton.setBounds(91, 192, 91, 23);
getContentPane().add(btnNewButton);
textArea = new JTextArea();
textArea.setBounds(30, 11, 241, 136);
getContentPane().add(textArea);
}
}

Maybe you need this snippet:
JOptionPane.showMessageDialog(null, "Your Text");
On the other Hand if project.fireBuildFinished(buildException); gives output to the console then you have to enter a return value of this output and enter this in the "Your Text" spot or enter this MessageDialog into your method.

Related

Java Socket not allowing swing frame to show up

Hey all I am at a loss as to why its doing this. If I just run the server and standalone client it works just fine. However, once I use my code for the client it seems to get stuck...
static JTextField textField = null;
static JTextArea messageArea = null;
static String serverAddress = "localhost";
static UFTtrack window = null;
public static JFrame frame;
public ImageIcon[] images;
static JTable table;
Date lastUpdate;
static Timer timer;
static Scanner in;
static PrintWriter out;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#SuppressWarnings({ "static-access" })
public void run() {
try {
UIManager.setLookAndFeel(new MaterialLookAndFeel());
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
try {
window = new UFTtrack();
placeChatOnScreen();
createTable();
SystemTrayz.createTray();
centreWindow(frame);
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public UFTtrack() {
initialize();
}
private void initialize() {
frame = new JFrame("UFTtrack");
frame.setTitle("UFT Tracker");
frame.setResizable(false);
frame.setLocationByPlatform(true);
frame.setSize(1308, 900);
frame.setBounds(100, 100, 450, 300);
frame.setMinimumSize(new Dimension(1308, 900));
frame.setPreferredSize(new Dimension(1308, 900));
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
#SuppressWarnings({ "resource", "unused" })
private static void placeChatOnScreen() {
try {
textField = new JTextField();
textField.setFont(new Font("Segoe UI", Font.PLAIN, 13));
textField.setDragEnabled(true);
textField.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
textField.setBounds(338, 838, 954, 22);
frame.getContentPane().add(textField);
messageArea = new JTextArea();
messageArea.setEditable(false);
messageArea.setFont(new Font("Segoe UI", Font.PLAIN, 13));
messageArea.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));
messageArea.setDragEnabled(true);
messageArea.setName("chatArea");
messageArea.setWrapStyleWord(true);
messageArea.setBounds(338, 648, 954, 181);
frame.getContentPane().add(messageArea);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
out.println(textField.getText());
textField.setText("");
}
});
Socket socket = new Socket("localhost", 8877);
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
while (in.hasNextLine()) {
String line = in.nextLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
messageArea.append(line.substring(8) + "\n");
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
It does fine until it gets to the "NAMEACCEPTED" else if condition and it just steps out of the while loop and then nothing happens. No error of any kind. It just doesn't how the swing frame!
If I comment out:
/*while (in.hasNextLine()) {
String line = in.nextLine();
if (line.startsWith("SUBMITNAME")) {
out.println(getName());
} else if (line.startsWith("NAMEACCEPTED")) {
textField.setEditable(true);
} else if (line.startsWith("MESSAGE")) {
messageArea.append(line.substring(8) + "\n");
}
}*/
and run it the swing frame loads up just fine. But my Socket (which I am wanting in my swing app) keeps it for some reason passing.
window = new UFTtrack();
placeChatOnScreen();
createTable();
SystemTrayz.createTray();
centreWindow(frame);
window.frame.setVisible(true);
To sum all this up - the above code hits the window = new UFTtrack(); and placeChatOnScreen() but after it exits the While loop in the placeChatOnScreen() it never continues to createTable(); What's the deal???
Also posted here:
http://www.javaprogrammingforums.com/whats-wrong-my-code/41820-java-socket-not-allowing-swing-frame-show-up.html#post165295
https://coderanch.com/t/708072/java/Java-Socket-allowing-swing-frame
https://www.dreamincode.net/forums/topic/415549-java-socket-not-allowing-swing-frame-to-show-up/
Java Socket not allowing swing frame to show up
As mentioned in the comments read and accept operations typically block on a Socket.
You could create an own Thread which is waiting for Message from your Socket and then modify the GUI. Keep in mind that Swing is not Thread safe.
If I need to create an own Thread, I use the Runnable interface. You could achieve it like this:
public class MySocketListener implements Runnable {
private final GUIClass guiClass;
private final ServerSocket serverSocket;
private Socket clientSocket;
public MySocketListener(GUIClass guiClass, ServerSocket serverSocket) {
this.guiClass = guiClass;
this.serverSocket = serverSocket;
}
/* Everything that happens in this method, is done on another Thread. */
#Override
public void run() {
try{
this.clientSocket = this.serverSocket.accept();
Scanner sc = new Scanner(this.clientSocket.getInputStream());
while(true) {
/* Blocking operations */
this.guiClass.doSomething();
}
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
The Thread can then be started easily:
Thread socketListenerThread = new Thread(new MySocketListener(this, serverSocket));
socketListenerThread.start();
For more information have a look at the Thread and Socket documentation.

How can I make my program wait for the user to interact with my JFrame?

I am trying to write a file processing application but the program won't wait for the user to select a file before moving and finishing the function. I've tried to use wait() and notify() to make it stop but the program now freezes and buttons d and e never show up.
import javax.swing.*;
import java.awt.event.*;
import java.io.File;
public class pdfEditor {
static JFrame inter = new JFrame("The Point Updater");
static JLabel reminder = new JLabel("Please select a function:");
static boolean i = false;
JButton a, b, c, d, e;
JFileChooser fc;
public static void main(String[] args) {
//Sets the window
inter.setSize(750, 250);
inter.setLocation(100, 150);
inter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
inter.setLayout(null);
//Label for commands for the user
reminder.setBounds(50, 50, 650, 30);
//add a button
JButton b = new JButton("Update Trainings");
b.setBounds(50, 150, 135, 30);
JButton c = new JButton("Update Employees");
c.setBounds(200, 150, 140, 30);
JButton a = new JButton("Export Points");
a.setBounds(355, 150, 135, 30);
//add them to the frame
inter.add(reminder);
inter.add(a);
inter.add(b);
inter.add(c);
inter.setVisible(true);
//Process selection
//TODO add catches for unformatted spreadsheets
a.addActionListener(new ActionListener() { //If export Points button is selected
#Override
public void actionPerformed(ActionEvent arg0) {
reminder.setText("Kashikomarimashita!");
exportPoints();
}
});
b.addActionListener(new ActionListener() { //If update trainings is selected
#Override
public void actionPerformed(ActionEvent arg0) {
reminder.setText("Make sure the type is Individual Completions and the columns are set to Training, Employee and Date.");
File file = null;
try {
file = requestInputSpreadsheet();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateTraining(file);
}
});
c.addActionListener(new ActionListener() { //If update employees is selected
#Override
public void actionPerformed(ActionEvent arg0) {
reminder.setText("Please import a employee list from iScout or Quickbase.");
File file = null;
try {
file = requestInputSpreadsheet();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateEmployees(file);
}
});
}
//Asks the user for a spreadsheet to be used in processing.
public static File requestInputSpreadsheet() throws InterruptedException{
//makes file chooser
JFileChooser fc = new JFileChooser();
fc.addChoosableFileFilter(new SpreadsheetFilter());
fc.setAcceptAllFileFilterUsed(false);
//makes new buttons and label
JLabel name = new JLabel();
name.setBounds(180, 100, 270, 30);
JButton d = new JButton("Choose File...");
d.setBounds(50, 100, 135, 30);
JButton e = new JButton("Go!");
e.setBounds(450, 100, 50, 30);
inter.add(d);
SwingUtilities.updateComponentTreeUI(inter);
//switch for the file chooser if file was chosen successfully
i = false;
File file = null;
d.addActionListener(new ActionListener() { //begins file choosing process
#Override
public void actionPerformed(ActionEvent arg0) {
int returnVal = fc.showOpenDialog(inter);
if (returnVal == JFileChooser.APPROVE_OPTION) {
//processes file and displays name
File file = fc.getSelectedFile();
name.setName(file.getName());
inter.add(name);
inter.add(e);
SwingUtilities.updateComponentTreeUI(inter);
}
}
});
e.addActionListener(new ActionListener() { //returns the selected file
#Override
public void actionPerformed(ActionEvent arg0) {
i = true;
synchronized (e) {
e.notify();
}
}
});
synchronized(e) {
e.wait();
}
//removes the button!
inter.remove(d);
inter.remove(e);
SwingUtilities.updateComponentTreeUI(inter);
if (i == true) {
return file;
}
return null;
}
//Updates completed training list and awards points based on a spreadsheet exported from the database
public static boolean updateTraining(File file) {
// still working on the processing
if (file == null) {
return false;
} else {
System.out.println("Updated Training!!");
return true;
}
}
//Updates the employee list using an employee list exported from the database
public static boolean updateEmployees(File file) {
if (file == null) {
return false;
} else {
System.out.println("Updated Employees!!");
return true;
}
}
//Creates and exports a spreadsheet with employee names and current points
public static boolean exportPoints() {
System.out.println("Exported Points!");
return true;
}
}
I included all of the code just in case.

Java System.out not Being Redirected

I have a simple task of capturing all System.out output; I am however failing:
public class Main {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
ArrayList<String> history = new ArrayList<>();
StringBuilder output = new StringBuilder();
StringBuilder input = new StringBuilder();
JPanel panel = new JPanel();
JTextArea txt = new JTextArea();
String PROMPT = "> ";
Runnable show = new Runnable() {
public void run() {
txt.setText("");
for (String line: history) txt.append(line + "\n");
txt.append(PROMPT);
txt.append(output.toString());
txt.setCaretPosition(txt.getText().length());
}
};
PrintStream os = new PrintStream(new OutputStream() {
#Override
public void write(int b) throws IOException {
if (b == 13) {
history.add(input.toString());
input = new StringBuilder();
SwingUtilities.invokeLater(show);
} else input.append((char)b);
}
});
void init(String title) {
panel.setLayout(new BorderLayout());
txt.setLineWrap(true);
txt.setFont(new Font("Courier", Font.PLAIN, 16));
txt.setBackground(Color.BLACK);
txt.setForeground(Color.GREEN);
txt.setCaretColor(Color.GREEN);
txt.setEditable(false);
txt.setText(PROMPT);
txt.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '\n') {
System.setOut(os);
System.setErr(os);
String result = output.toString();
history.add(PROMPT + result);
try {
engine.eval(result);
} catch (ScriptException ex) {
history.add(ex.toString());
}
output = new StringBuilder();
} else {
output.append(e.getKeyChar());
}
SwingUtilities.invokeLater(show);
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
});
panel.add(txt, BorderLayout.CENTER);
JFrame frame = new JFrame(title);
frame.setSize(650, 425);
frame.setContentPane(panel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String args[]) {
new Main().init("javascript");
}
}
I should note the output I am looking for comes from something like:
new ScriptEngineManager().getEngineByName("js").eval("print(\"test\");");
The output is not going anywhere other than normal STDOUT a.k.a. System.out. Why?
ScriptEngine output redirection:
To redirect the output of a script you first have to get its ScriptContext instance, that has a method called setWriter(Writer).
That sets the output of the ScriptEngine.
For that you first need a Writer. This can be simple like this one:
public class CaptureWriter extends Writer
{
private StringBuilder m_build;
public CaptureWriter(StringBuilder build)
{
m_build = build;
}
#Override
public void write(char[] cbuf, int off, int len) throws IOException
{
m_build.insert(m_build.length(), cbuf, off, len);
}
#Override
public void flush() throws IOException
{
}
#Override
public void close() throws IOException
{
}
}
This writes all input into a StringBuilder.
Then you register it into a ScriptContext
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
engine.getContext().setWriter(new CaptureWriter(m_mess));
When running this simple program:
StringBuilder build = new StringBuilder();
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
engine.getContext().setWriter(new CaptureWriter(build));
try
{
engine.eval("print(\"Hello\")");
engine.eval("print(\"World\")");
engine.eval("print(\"You\")");
engine.eval("print(\"There\")");
} catch(ScriptException e)
{
e.printStackTrace();
}
System.out.println(build);
The output is the buffered output of the script:
Hello
World
You
There
You can of course hook anything into the write method of the Writer implementation, this is just an example.
System.out redirection:
To capture the System.out output you have to make your own PrintStream implementation, it can be very simple like:
public class Capture extends PrintStream
{
private StringBuilder m_build;
public Capture(OutputStream out, StringBuilder build)
{
super(out);
m_build = build;
}
public void println(String s)
{
super.println(s);
m_build.append(s + "\n");
}
}
Then you need to register it in the runtime:
StringBuilder build = new StringBuilder();
System.setOut(new Capture(System.out, build));
Then every time System.out.println is called it works like the overriding PrintStream should and the message gets written into the provided StringBuilder.
To capture other messages you'll need to override other methods.
You can capture System.out be providing a PrintStream that you control ... try something like this
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream old = System.out;
System.setOut(ps);
System.out.println("This will be captured :P");
System.out.flush();
System.setOut(old);
System.out.println("He is what was captured : " + baos.toString());

How to print the console output in a notepad file?

I want to know how my console output can be save in a notepad file?
import java.awt.EventQueue;
public class HLS1 {
private JFrame frmHttpsLiveStreaming;
private JTextField textField;
// file is accessed to the whole class
private File file;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HLS1 window = new HLS1();
window.frmHttpsLiveStreaming.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public HLS1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmHttpsLiveStreaming = new JFrame();
frmHttpsLiveStreaming.setTitle("HTTPS Live Streaming");
frmHttpsLiveStreaming.setBounds(100, 100, 494, 112);
frmHttpsLiveStreaming.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHttpsLiveStreaming.getContentPane().setLayout(null);
JButton btnBrowse = new JButton("Open File");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("Argument:" + arg0);
JFileChooser fs = new JFileChooser(new File("c:\\"));
fs.setDialogTitle("Open a file");
fs.setFileFilter(new FileTypeFilter(".m3u8", ""));
fs.setFileFilter(new FileTypeFilter(".m3u", ""));
fs.showOpenDialog(null);
file = fs.getSelectedFile();
textField.setText(file.getAbsolutePath());
}
});
btnBrowse.setBounds(336, 7, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnBrowse);
JButton btnNewButton_1 = new JButton("Clear");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textField.setText("");
}
});
btnNewButton_1.setBounds(237, 39, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnNewButton_1);
JLabel lblUrl = new JLabel("URL");
lblUrl.setBounds(83, 11, 24, 14);
frmHttpsLiveStreaming.getContentPane().add(lblUrl);
textField = new JTextField();
textField.setBounds(116, 11, 210, 19);
frmHttpsLiveStreaming.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("Check");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
List<String> fileArray = new ArrayList<String>();
List<String> errors = new ArrayList<String>();
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&##/%?=~_|!:,.;]*[-a-zA-Z0-9+&##/%=~_|]";
Scanner s = null;
if(textField.getText().matches(regex)){
URL url = new URL(textField.getText());
s= new Scanner(url.openStream());
}else{
s = new Scanner(new BufferedReader(new FileReader(file)));
}
if(s != null){
while(s.hasNextLine()){
String line = s.nextLine();
if(!line.isEmpty()){
fileArray.add(line);
}
System.out.println(line);
}
}
s.close();
errors.addAll(validateEXTM3U(fileArray));
for (String error : errors) {
System.out.println(error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnNewButton.setBounds(126, 39, 89, 23);
frmHttpsLiveStreaming.getContentPane().add(btnNewButton);
}
private List<String> validateEXTM3U(List<String> fileArray){
List<String> errors = new ArrayList<String>();
String tag = fileArray.get(0);
if(!tag.equals("#EXTM3U")){
errors.add("First line in the menifest file is not #EXTM3U");
}
return errors;
}
}
It could be a hacky solution , but if you are running in windows or linux then you can pipe / redirect it.
java HLS1 > notepad.txt
if not what you are looking for , then why not using something called log4j ?
Why don't you write your own utility that has an public static void output(String output) method. Then instead of using System.out.println("...") you call output("...") then in your output(String output) method you can do anything with the output, like first write to the file, then print to the console.
Hope this helps.

JOptionPane.showMessageDialog not showing text

I seem to be having some issues when using the JOptionPane.showMessageDialog() method.
When I use the method the only thing that is set up correctly is the dialogs title. It doesn't want to display the text that I provide.
Here's the code that I'm using to try and create an alert:
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
The code above provides the image below:
If someone could tell me what I'm doing wrong or if there is a different method that I'm supposed to be using, I would much appreciate it.
Edit:
My main class:
This creates a GUI where the user enters information "Host" and "DisplayName". When they click "Connect" a new thread is created (the ClientConnectSocket).
public class Main extends JFrame {
public static JPanel contentPane;
private JTextField hostTxt;
public static JTextField displayNameTxt;
JLabel lblDisplayName = new JLabel("Display Name:");
JButton btnConnect = new JButton("Connect");
JLabel lblHost = new JLabel("Host:");
public static String username = "None :(";
public static String host = "localhost";
public static boolean connected = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setType(Type.UTILITY);
setTitle("Java Chat Client - v0.1");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 390, 200);
contentPane = new JPanel();
this.setResizable(false);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lblHost.setBounds(60, 11, 56, 19);
contentPane.add(lblHost);
hostTxt = new JTextField();
hostTxt.setBounds(165, 10, 103, 20);
contentPane.add(hostTxt);
hostTxt.setColumns(10);
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (hostTxt.getText() == null || displayNameTxt.getText() == null){
}else{
Thread ccs = new ClientConnectSocket(hostTxt.getText(), displayNameTxt.getText());
ccs.start();
while (!connected){
//System.out.println("Not connected yet..");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Yey, connected");
username = displayNameTxt.getText();
host = hostTxt.getText();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Chat frame = new Chat();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
dispose();
}
}
});
btnConnect.setBounds((this.getWidth()/2)- 70, 76, 89, 23);
contentPane.add(btnConnect);
displayNameTxt = new JTextField();
displayNameTxt.setColumns(10);
displayNameTxt.setBounds(165, 45, 103, 20);
contentPane.add(displayNameTxt);
lblDisplayName.setBounds(60, 41, 95, 29);
contentPane.add(lblDisplayName);
this.getRootPane().setDefaultButton(btnConnect);
}
ClientConnectSocket class:
public class ClientConnectSocket extends Thread{
String host;
String name;
public ClientConnectSocket(String host, String displayName){
this.host = host;
this.name = displayName;
}
boolean b = true;
public void run(){
try{
while (b){
Socket server = new Socket(host, 6969);
System.out.println("Sending info to try and connect.");
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
out.write("method=connect:displayName="+ name);
out.flush();
Thread.sleep(500);
InputStream in = server.getInputStream();
StringBuffer sb = new StringBuffer();
byte[] buffer = new byte[1024];
int buf;
while ((buf = in.read(buffer)) != -1){
String line = new String(buffer, 0, buf);
sb.append(line);
}
in.close();
System.out.println(sb.toString() + " || " + sb.toString().equalsIgnoreCase("connect"));
if (sb.toString().equalsIgnoreCase("connect")){
//Allow them to connect
Main.connected = true;
}else if(sb.toString().equalsIgnoreCase("invalid:Username")){
//Tell them they have username already taken;
JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);
b = false;
}
server.close();
out.close();
in.close();
b = false;
}
}catch (Exception e){
System.exit(2);
e.printStackTrace();
}
}
Your posted code snippet suggests that you're running into a Swing threading issue. If your program is a Swing GUI, then most of the above code needs to be called off of the Swing EDT or Event Dispatch Thread, while any Swing calls, including displaying the JOptionPane should be called on the EDT. For more specific help, consider telling and showing more about your code and your use of background threading.
Edit
OK, so that code is in a background thread. So now you must take care to show your JOptionPane on the EDT. Consider making these changes:
} else if(sb.toString().equalsIgnoreCase("invalid:Username")) {
b = false;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JOptionPane.showMessageDialog(null, "alert", "alert",
JOptionPane.ERROR_MESSAGE);
}
});
}
Note: code not tested by compiling or by running. Please be wary of typos.
Edit 2
As an aside, you've got other issues including that the connected variable should not be static. You also have threading issues:
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (hostTxt.getText() == null || displayNameTxt.getText() == null) {
} else {
// .........
// ********** you should not have this type of code on the EDT
while (!connected) {
// ........
}
// ...............
}
}
});

Categories