I would like to know how to display a string (character by character) with Java, that is to say, a display char in a JTextField and then display another after 2 seconds for example?
Can someone point me how to fix this?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String s = jTextField4.getText (), s1 = "";
String str = "";
int L = s.length();
int x = 1500;
for (int i=0; i< L; i++)
{
char prem = s.charAt(i);
str= str + prem;
x = x + 2000;
final Thread th4 = new Thread (new Runnable() {
public void run() {
try {
Thread.sleep(x);
} catch (InterruptedException ex) {
}
}
});
th4.start();
s1 = s1.concat(str);
jTextField3.setText(s1);
}
}
This should do the job
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Thread thread = new Thread(new DelayedWriter(jTextField3, jTextField4.getText()));
thread.start();
}
class DelayedWriter implements Runnable{
JTextField tf;
String s;
public DelayedWriter(JTextField tf, String s){
this.tf = tf;
this.s=s;
}
public void run(){
for (int i=0; i< s.length(); i++)
{
tf.setText(s.substring(0,i+1));
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
Related
I'm trying to finish my project about searching graphs, where one of the functions is input (vertex and edges) from user.
I already have a method for this in another class, but now I need to put it into GUI.
I've already tried many of tutorials, but nothing worked. Can somebody help me, how to put the method getInputFromCommand to gui?
I've already tried to copy the method into the GUI, but there was problem with the "return g" because of the void result type, I've tried just to call the method, (I know.. stupid) but it didn't work either.
package Process;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
public static FindIslands getInputFromCommand() {
FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return g;
}
}
Where important is the last method "getInputFromCommand()"
and... gui
package Process;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.util.Scanner;
public class Guicko extends JFrame {
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
public Guicko() {
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FindIslands.getInputFromCommand();
}
});
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String str = "asd";
FindIslands g = null;
g.connectedComponents();
textArea1.setText(str);
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
}
I'm sure there are many correct ways this code can be fixed, but in IMHO, your Guicko class needs to have a FindIslands class member, and I think you need to move some stuff from FindIslands.main() into Guicko.main() or some other method.
Then your "Action Listener" inner classes' actionPerformed methods just delegate to the methods in the FindIslands member instance, like this
....
private FindIslands fi;
public Guicko() {
....
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fi = FindIslands.getInputFromCommand();
}
});
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String comps = fi.connectedComponents();// method needs to return a string
textArea1.setText(comps);
}
});
}
The whole idea of seperating GUI from domain is to make changes easily. GUI has knowledge of the domain but domain has no knowledge about the GUI. We can use an interface to seperate them, in that case, Domain says , i don't care who implements this interface but whoever implements this interface will get response and can work with me.
So , If we create a new GUI, we can let it implements that interface and the same domain will work with that GUI.
There are many mistakes but in order to make it work and to show you an example i did few changes.
public class Guicko extends JFrame implements PropertyChangeListener{
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
private FindIslands land;
private JTextField textField;
private JButton button;
public Guicko() {
JPanel panel = new JPanel();
super.getContentPane().setLayout(new GridLayout());
//For each gui, there should be one land.
this.setLand(new FindIslands(100));
//Subscribe to the domain so that you can get update if something change in domain.
this.getLand().subscribe(this);
//Dummy buttons are fields(need too initiate first)
textField2 = new JTextField("",30);
štartButton = new JButton();
textField = new JTextField("",30);
button = new JButton();
button.setPreferredSize(new Dimension(100, 40));
button.setText("Get input from Domain");
štartButton.setPreferredSize(new Dimension(100, 40));
textField.setEditable(false);
štartButton.setText("Start");
panel.add(textField2);
panel.add(štartButton);
panel.add(textField);
panel.add(button);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
//When you type something in , then this function will send it to domain(i mean to function : getInputFromCommand();).
this.addListerToField(štartButton,this.getLand(),textField2);
//Now the second case, suppose you press a button and want something to show up in textfield. In that case , this function will do work.
this.addListerToSecondField(button,this.getLand(),textField);
}
//Here i can catch the events from the domain.
#Override
public void propertyChange(PropertyChangeEvent e) {
if(e.getPropertyName().equals("String changed")) {
this.getTextField().setText((String) e.getNewValue());
}
}
private void addListerToSecondField(JButton button, FindIslands land, JTextField field) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.requireArgumentsForField();
}
});
}
private void addListerToField(JButton štartButton, FindIslands land, JTextField field) {
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.getInputFromCommand(field.getText());
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
public FindIslands getLand() {
return land;
}
public void setLand(FindIslands land) {
this.land = land;
}
public JTextField getTextField() {
return textField;
}
public void setTextField(JTextField textField) {
this.textField = textField;
}
public JButton getButton() {
return button;
}
public void setButton(JButton button) {
this.button = button;
}
Here is the second class. Run it and try to get feeling for it how it works.
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
//initialize the list
this.setListeners(new ArrayList<>());
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
//You need only one main class, not two.----------------------------
/**
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
**/
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
//Static cases are to be avoided.This is the property of object not class.
public void getInputFromCommand(String string) {
//Here you will recieve a string from the GUI and will be printed in command prompt.You can do whatever you want to do with it.
System.out.println("Recieve string is " + string);
//No idea what you are trying to do.
/** FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return line;**/
}
//This function is triggered with second button and you can send data to gui as shown below.
public void requireArgumentsForField() {
//Suppose i want to send following string.
String name = "I don't know";
this.getListeners().stream().forEach(e -> {
// I will catch this in view.
e.propertyChange(new PropertyChangeEvent(this, "String changed", null, name));
});
}
private ArrayList<PropertyChangeListener> listeners;
//Let the objects subscibe. You need this to publish the changes in domain.
public void subscribe(PropertyChangeListener listener) {
this.getListeners().add(listener);
}
public ArrayList<PropertyChangeListener> getListeners() {
return listeners;
}
public void setListeners(ArrayList<PropertyChangeListener> listeners) {
this.listeners = listeners;
}
The task is to write a program that creates and starts two threads ThreadFibonacci and ThreadOutput. ThreadFiobnacci should calculate the fibonacci numbers and put the results in its static public variable. ThreadOutput should output the fibonacci number and ThreadOutput has to be a daemon thread. You have to make the thread write out each fibonacci number only once. I do not know how to do that last part of the task.
You can only use sleep, interrupt, volatile and join.
Here is what I tried:
import java.util.Scanner;
public class Zadatak2{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = reader.nextInt();
Thread threadFibonaci = new Thread(new ThreadFibonaci(n));
Thread threadOutput = new ThreadOutput();
threadFibonaci.start();
threadOutput.start();
}
}
class ThreadFibonaci implements Runnable{
public static volatile long fn;
private int n;
public ThreadFibonaci(int n){
this.n = n;
}
public void run(){
long f0 = 0;
fn = f0;
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
long f1 = 1;
fn = f1;
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
for(int i=0; i<n; i++){
fn = f0 + f1;
f0 = f1;
f1 = fn;
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
class ThreadOutput extends Thread{
public ThreadOutput(){
setDaemon(true);
}
public void run(){
while(true){
System.out.println(ThreadFibonaci.fn);
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
You need top use one more volatile variable to store a flag whether current number was already printed or not
class ThreadFibonaci implements Runnable{
public static volatile long fn;
public static volatile boolean printed = false;
private int n;
public ThreadFibonaci(int n){
this.n = n;
}
public void run(){
long f0 = 0;
fn = f0;
while (!printed) {
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
long f1 = 1;
fn = f1;
printed = false;
while (!printed) {
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
for(int i=0; i<n; i++){
fn = f0 + f1;
f0 = f1;
f1 = fn;
printed = false;
while (!printed) {
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
class ThreadOutput extends Thread{
public ThreadOutput(){
setDaemon(true);
}
public void run(){
while(true){
while (ThreadFibonaci.printed) {
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
System.out.println(ThreadFibonaci.fn);
ThreadFibonaci.printed = true;
}
}
}
This uses a single volatile field to hold the value. when the value is 0 a new value can be published and when the value is negative, it acts as a poison pill, stopping the printing thread.
class A {
static volatile long value = 0;
static void publish(long x) {
while (value > 0) ;
value = x;
}
static long next() {
while (value == 0) ;
long ret = value;
if (ret > 0) value = 0;
return ret;
}
public static void main(String[] args) {
System.out.println("Enter a number: ");
int n = new java.util.Scanner(System.in).nextInt();
new Thread(() -> {
long a = 1; publish(a);
long b = 1; publish(b);
for (int i = 2; i < n; i++) {
long c = a + b; publish(c);
a = b; b = c;
}
publish(-1); // poison pill
}).start();
new Thread(() -> {
for (; ; ) {
long value = next();
if (value < 0) break;
System.out.println(value);
}
}).start();
}
}
I know how to display text from thread in console, but how can I put it in TextArea? Also since my text is chars and numbers, how can I convert them to string since TextArea takes only String if I am right?
I need to append PrintNum, LetterSmall and LetterBig in TextArea.
Does someone know the way? Any help would be appreciated!
public class pracice extends Application {
#Override
public void start(Stage primaryStage) {
TextArea ta = new TextArea();
Button btn = new Button();
btn.setText("Show");
btn.setOnAction(new EventHandler<ActionEvent>() {
Runnable run = new PrintNum(25);
Thread th1 = new Thread(run);
char lett;
char lettUp;
Runnable let = new LetterSmall(lett);
Thread th2 = new Thread(let);
Runnable lUp = new LetterBig(lettUp);
Thread th3 = new Thread(lUp);
#Override
public void handle(ActionEvent event) {
System.out.append("\nBegin\n");
th1.start();
try{
th1.join(2000);
} catch (InterruptedException e){
e.printStackTrace();
}
th2.start();
try{
th2.join();
} catch (InterruptedException e){
e.printStackTrace();
}
th3.start();
}
});
BorderPane root = new BorderPane();
root.setTop(btn);
root.setCenter(ta);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Practice");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class PrintNum implements Runnable {
private int lastNum;
Random r = new Random();
public PrintNum(int n){
lastNum = n;
}
public void run(){
System.out.append("\n");
for(int i = 1; i <= lastNum; i++){
int rN = r.nextInt(25) + 1;
System.out.append((lastNum - rN) + " ");
}
}
}
class LetterSmall implements Runnable {
Random r = new Random();
private char lett;
public LetterSmall(char s){
lett = s;
}
public void run(){
System.out.append("\n");
for(int i = 1; i <= 25; i++){
char c = (char) (r.nextInt(26) + 'a');
lett = c;
System.out.append(lett + " ");
}
}
}
class LetterBig implements Runnable {
Random r = new Random();
private char lettUp;
public LetterBig(char up){
lettUp = up;
}
public void run(){
System.out.append("\n");
for(int i = 1; i <= 25; i++){
char c = (char) (r.nextInt(26) + 'A');
lettUp = c;
System.out.append(lettUp + " ");
}
}
}
So I found a solution for TextArea input. Instead of making three class threads, I moved them inside the primary JavaFX class. Thanks everyone for help.
It looks like this:
new Thread(new Runnable() {
private int lastNum = 25;
private char lett;
private char lettUp;
Random r = new Random();
#Override
public void run() {
Thread th1 = new Thread();
ta.appendText("\n");
for(int i = 1; i <= lastNum; i++){
int rN = r.nextInt(25) + 1;
ta.appendText((lastNum - rN) + " ");
}
Thread th2 = new Thread();
ta.appendText("\n\n");
for(int i = 1; i <= 25; i++){
char c = (char) (r.nextInt(26) + 'a');
lett = c;
ta.appendText(lett + " ");
}
Thread th3 = new Thread();
ta.appendText("\n\n");
for(int i = 1; i <= 25; i++){
char c = (char) (r.nextInt(26) + 'A');
lettUp = c;
ta.appendText(lettUp + " ");
}
th1.start();
try{
th1.join(2000);
} catch (InterruptedException e){
e.printStackTrace();
}
th2.start();
try{
th1.join();
} catch (InterruptedException e){
e.printStackTrace();
}
th3.start();
try{
th1.join();
th2.join();
th3.join();
} catch (InterruptedException e){
e.printStackTrace();
}
}
}).start();
Actually i am using threads to update progress bar inside a block of code ,The run method of the thread is not working,So,could you please help me resolve the problem.I am using SWT toolkit for the UI.
CODE:
//selection listener
tItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e)
{
TableItem[] tableItems =table.getItems();
int c=0;
int inty=table.getSelectionIndex();
for(int i=table.getSelectionIndex();i<tableItems.length;i++)
{
if(c==0)
{
column = new TableColumn(table, SWT.CENTER);
//reading content from the table Stringline=tableItems[i].getText(0)+","+tableItems[i].getText(1)+","+tableItems[i].getText(2)+","+tableItems[i].getText(3)+","+tableItems[i].getText(4)+","+tableItems[i].getText(5)+","+tableItems[i].getText(6);
System.out.println("\n line value is "+line);
String split= ",";
String error=",,,,,,";
if(line.equals(error))
{
break;
}
else {while ((line!= null))
String[]com = line.split(split,20);
String result =null;
//checking whether the value in it is enable or n
if(com[0].contains("ENABLE"))
{ result = "RESULTS";
continue;}
if(com[0].equals("N"))
{result = "No";}
else if(com[2].startsWith("S=") )
{
String O=tableItems[i].getText(7);
String[] part = O.split("=");
String string2 = part[1];
a=Integer.parseInt(string2);
//declaration of the thread
final Thread thread = new Thread()
{public void run()
{for(int i=0; i<=a; i++)
{
final int value = i;
try {
Display.getDefault().asyncExec(newRunnable()
{
public void run()
{
//assigning value to the progress bar
pbar.setSelection(value);
}
});
}
catch (Exception e)
{
System.out.println("Warning");
}
}
}
thread.start();
inty++;
break;
}
}
});
I'm writing a program that constantly pings a server. I wrote the code to check it once and put the ping in a JLabel and put it in a method called setPing().
Here is my code
private void formWindowOpened(java.awt.event.WindowEvent evt) {
setPing();
}
That worked but only did it once, so I did:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
for(;;){
setPing();
}
}
But this doesn't even work for the first time.
I didnt put the setPing method because it was too long so here it is:
public String setPing(){
Runtime runtime = Runtime.getRuntime();
try{
Process process = runtime.exec("ping lol.garena.com");
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
int i = 0;
i = line.indexOf("Average");
if(i > 0){
String finalPing = "";
line.toCharArray();
try
{
finalPing = "";
for(int x = i; x < i + 17; x++)
{
finalPing = finalPing + (line.charAt(x));
}
}catch(IndexOutOfBoundsException e)
{
try
{
finalPing = "";
for(int x = i; x < i + 16; x++)
{
finalPing = finalPing + (line.charAt(x));
}
}catch(IndexOutOfBoundsException f)
{
try
{
finalPing = "";
for(int x = i; x < i + 15; x++)
{
finalPing = finalPing + (line.charAt(x));
}
}catch(IndexOutOfBoundsException g){}
}
}
String final1Ping = finalPing.replaceAll("[^0-9]", "");
return final1Ping;
}
}
}catch(IOException e){
}
return "";
}
UPDATE
Just in case this is important, Im using netbeans. I created a form and put this code in the formWindowOpened evt instead of calling it in main:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
ActionListener timerListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new PingWorker().execute();
}
};
Timer timer = new Timer(1000, timerListener);
timer.start();
jLabel1.setText(label.getText());
timer.stop();
// TODO add your handling code here:
}
class PingWorker extends SwingWorker {
int time;
#Override
protected Object doInBackground() throws Exception {
time = pingTime("lol.garena.com");
return new Integer(time);
}
#Override
protected void done() {
label.setText("" + time);
}
};
public JComponent getUI() {
return label;
}
public static int pingTime(String hostnameOrIP) {
Socket socket = null;
long start = System.currentTimeMillis();
try {
socket = new Socket(hostnameOrIP, 80);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
long end = System.currentTimeMillis();
return (int) (end - start);
}
Use a Swing Timer for repeating tasks & a SwingWorker for long running tasks. E.G. of both below - it uses a Timer to repeatedly perform a 'long running' task (a ping) in a SwingWorker.
See Concurrency in Swing for more details on the Event Dispatch Thread and doing long running or repeating tasks in a GUI.
This code combines a long running task ('pinging' a server) using SwingWorker invoked from a repeating task (updating the JLabel repeatedly with the times) using a Swing based Timer.
import java.awt.event.*;
import javax.swing.*;
import java.net.Socket;
public class LabelUpdateUsingTimer {
static String hostnameOrIP = "stackoverflow.com";
int delay = 5000;
JLabel label = new JLabel("0000");
LabelUpdateUsingTimer() {
label.setFont(label.getFont().deriveFont(120f));
ActionListener timerListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new PingWorker().execute();
}
};
Timer timer = new Timer(delay, timerListener);
timer.start();
JOptionPane.showMessageDialog(
null, label, hostnameOrIP, JOptionPane.INFORMATION_MESSAGE);
timer.stop();
}
class PingWorker extends SwingWorker {
int time;
#Override
protected Object doInBackground() throws Exception {
time = pingTime();
return new Integer(time);
}
#Override
protected void done() {
label.setText("" + time);
}
};
public static int pingTime() {
Socket socket = null;
long start = System.currentTimeMillis();
try {
socket = new Socket(hostnameOrIP, 80);
} catch (Exception weTried) {
} finally {
if (socket != null) {
try {
socket.close();
} catch (Exception weTried) {}
}
}
long end = System.currentTimeMillis();
return (int) (end - start);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new LabelUpdateUsingTimer();
}
};
SwingUtilities.invokeLater(r);
}
}
You could use a Thread. The problem is you are blocking the main thread, thereby blocking your program. To get around this, start a background Thread to update components repeatedly.
(Note: you need to update GUI components on the EDT, so use SwingUtilities.invokeLater)
(new Thread((new Runnable(){
#Override
public void run(){
while(true){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
refToJLabel.setText(Math.random());
}
});
}
}
}))).start();