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;
}
}
});
Related
My SwingWorker doesn't stop the background thread from executing when I call .cancel(true); I've tried loads of different things - running the background process on it's own thread, calling the method directly, surrounding the method/process in try catch to force the process to jump out of the for loop and so on....for some reason the process just continues. Basically, there is JButton that when clicked starts the SwingWorker and background process, and when I click that button again, I want the process to stop. There is a fair bit of code, The GUI (PlayAKnit), the method/process which is part of my KnitGraph class and a SoundPlayer object which loops sounds. I will share what I can here:
code in GUI class
button.addActionListener(e -> {
KnitGraph test = new KnitGraph(new KnitSpeakIn("CherryStitch").getKnitFile());
Thread graph = new Thread(test);
SwingWorker startWorker = new SwingWorker() {
#Override
protected Void doInBackground() throws Exception {
test.parseCommands(0, test.getCommands().length);
return null;
}
};
if (button.getText().equals("KNIT")) {
button.setText("UNPICK");
button.setFont(new Font("Helvetica", Font.BOLD, 48));
startWorker.execute();
}
else {
startWorker.cancel(true);
button.setText("KNIT");
button.setFont(new Font("Helvetica", Font.BOLD, 72));
}
});
method that runs in background calls methods that make sounds
void parseCommands(int start, int end) throws InterruptedException {
int asterixStartLocation = 0;
int asterixEndLocation = 0;
for(int i = start; i<end;i++) {
System.out.println(commands[i]);
if (commands[i].contains("co")) {
System.out.println("casting on");
castOn(extractInt(commands[i]));
}
if (commands[i].contains("*")) {
if (!asterixFound) {
System.out.println("I found an asterix");
asterixFound = true;
commands[i] = commands[i].replace('*', ' ');
asterixStartLocation = i;
}
else {
System.out.println("I found another asterix!");
asterixFound = false;
asterixEndLocation = i;
commands[i] = commands[i].replace('*', ' ');
parseCommands(i, i+1);
parseCommands(asterixStartLocation, asterixEndLocation);
}
}
if (commands[i].matches("\\spurl|\\sknit|\\sPurl|\\sKnit")) {
for (int j = 0; j < stitchesInRowBelow; j++) {
knitOrPurl();
}
}
if (commands[i].contains("tog") || commands[i].contains("ssk")) {
if (commands[i].contains("ssk")) {
int count = 0;
for (int k = 0; k < commands[i].length(); k++) {
if ((commands[i]).charAt(k) == 's') {
count++;
}
}
decrease(count - 1);
}
else if (commands[i].contains("psso")) {
decrease(2);
}else {
decrease(extractInt(commands[i])-1);
}
}
if (commands[i].contains("yo")) {
yarnOver();
}
if (commands[i].contains("kfb")) {
increase();
}
if (commands[i].matches("\\sk\\d|\\sp\\d|\\sk\\d\\stbl|\\sp\\d\\stbl|\\s*k\\d|\\s*p\\d")) {
int noOfStitches = extractInt(commands[i]);
for (int n=0;n<noOfStitches;n++) {
knitOrPurl();
}
}
if (commands[i].contains("cast off")) {
castOff();
}
}
}
method in SoundPlayer class just loops random .wav files
public void run() {
File sound = new File(sounds[randomInt]);
try {
String url = sound.toURI().toURL().toString();
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new URL(url)));
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch(Exception e) {
e.printStackTrace();
}
}
}
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;
}
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();
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();
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) {
}
}
}
}