execute events read from JSON - java

I am reading two things from a JSON file:
actionOnPress:"robot.KeyPress(e)"
(robot being a java.awt.robot instance) and
event:"KeyEvent.VK_4"
I want to execute
robot.KeyPress(KeyEvent.VK_4)
what is the easiest way (best without needing to download libraries) to execute this? This code is supposed to also work with robot.mousePress and robot.mouseMove etc.
I already tried different things with ScriptEngine, but none of it seems to work.
Thank you very much, Kamik423
EDIT: should be universal. The user should be able to specify different events like FOR EXAMPLE robot

Ok, solved it myself. Here is the code:
package test;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class executor extends JFrame {
String import1 = "java.awt.Robot";
String import2 = "java.awt.event.KeyEvent";
String setup1 = "r = new Robot";
String executionType = "r.keyPress(event)";
String event = "KeyEvent.VK_4";
private JTextField textField;
static ScriptEngineManager manager = new ScriptEngineManager();
static ScriptEngine engine = manager.getEngineByName("JavaScript");
public executor() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100,100,100,100);
textField = new JTextField();
textField.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent ev) {
try {
engine.eval("importClass(" + import1 + ")");
engine.eval("importClass(" + import2 + ")");
engine.eval(setup1);
engine.eval(executionType.replaceAll("event", event));
} catch (ScriptException e) {
e.printStackTrace();
}
}
});
getContentPane().add(textField, BorderLayout.CENTER);
textField.setColumns(10);
}
public static void main(String[] args) {
executor ex = new executor();
ex.setVisible(true);
}
}

Related

How To Make An Application Icon Progress Indicator In Java? [duplicate]

I'd like to know if it is possible to make a progress bar displayed on the taskbar like Windows Explorer does when there's a file operation going on?
I saw many examples, but they all involved C#.
SWT won't cut it.
I found out that this feature is included in Java 9. It is part of AWT and it is quity simple too use.
Here is short example:
import java.awt.Taskbar;
import java.awt.Taskbar.State;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
/**
* #author fxl
*/
public class TaskbarSample {
public static void main(String[] args) {
// JavaDoc:
// https://docs.oracle.com/javase/9/docs/api/java/awt/Taskbar.html
// MSDNDoc:
// https://msdn.microsoft.com/en-us/library/dd391692(VS.85).aspx
if (Taskbar.isTaskbarSupported() == false) {
return;
}
JFrame dialog = new JFrame("Test - 50%");
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
Taskbar taskbar = Taskbar.getTaskbar();
taskbar.setWindowProgressState(dialog, State.ERROR);
taskbar.setWindowProgressValue(dialog, 50);
}
}
this is now possible using SWT please review the code example:
org.eclipse.swt.snippets.Snippet336
This example will do the job:
Task bar:
Code:
import org.bridj.Platform;
import org.bridj.Pointer;
import org.bridj.cpp.com.COMRuntime;
import org.bridj.cpp.com.shell.ITaskbarList3;
import org.bridj.jawt.JAWTUtils;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TaskBarListDemo extends JFrame implements ActionListener, ChangeListener
{
private ITaskbarList3 list;
private JSlider slider;
private Pointer<?> hwnd;
private TaskBarListDemo() throws ClassNotFoundException
{
super("TaskbarList Demo (" + (Platform.is64Bits() ? "64 bits" : "32 bits") + ")");
list = COMRuntime.newInstance(ITaskbarList3.class);
getContentPane().add("Center", new JLabel("Hello Native Windows 7 World !"));
Box box = Box.createVerticalBox();
int min = 0;
int max = 300;
int val = (min + max / 2);
slider = new JSlider(min, max, val);
slider.addChangeListener(this);
box.add(slider);
ButtonGroup group = new ButtonGroup();
for (ITaskbarList3.TbpFlag state : ITaskbarList3.TbpFlag.values())
{
JRadioButton cb = new JRadioButton(state.name());
group.add(cb);
cb.putClientProperty(ITaskbarList3.TbpFlag.class, state);
cb.setSelected(state == ITaskbarList3.TbpFlag.TBPF_NORMAL);
cb.addActionListener(this);
box.add(cb);
}
getContentPane().add("South", box);
}
#Override
protected void finalize() throws Throwable
{
super.finalize();
list.Release();
}
public void setVisible(boolean visible)
{
super.setVisible(visible);
long hwndVal = JAWTUtils.getNativePeerHandle(this);
hwnd = Pointer.pointerToAddress(hwndVal);
list.SetProgressValue((Pointer) hwnd, slider.getValue(), slider.getMaximum());
}
#Override
public void stateChanged(ChangeEvent actionEvent)
{
list.SetProgressValue((Pointer) hwnd, slider.getValue(), slider.getMaximum());
}
#Override
public void actionPerformed(ActionEvent actionEvent)
{
JRadioButton button = ((JRadioButton) actionEvent.getSource());
if (button.isSelected())
{
ITaskbarList3.TbpFlag flag = (ITaskbarList3.TbpFlag) button.getClientProperty(ITaskbarList3.TbpFlag.class);
list.SetProgressValue((Pointer) hwnd, slider.getValue(), slider.getMaximum());
list.SetProgressState((Pointer) hwnd, flag);
}
}
public static void main(String[] arguments) throws Exception
{
TaskBarListDemo f = new TaskBarListDemo();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}
Maven dependencies:
<dependencies>
<dependency>
<groupId>com.nativelibs4java</groupId>
<artifactId>bridj</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>LATEST</version>
</dependency>
</dependencies>
There is no standard facility in Java for doing so, yet.
Hence you need to talk to Windows directly to do that. So you need to locate the correct Windows routine, and use JNA (probably the easiest) to invoke that routine. I do not know of a vendor or a project who has done this already.
Edit: It appears that the http://code.google.com/p/nativelibs4java/ project may do what you want.
As Java9's java.awt.Taskbar only works for old swing frames (they somehow forgot to implement this for javafx.stage.Stage) and com.nativelibs4java bridj isn't working (anymore) (see https://github.com/nativelibs4java/BridJ/issues/94) I implemented a solution using JNA 4.1.0.
Please note:
Relies on calling internal javafx api (com.sun.javafx.stage.WindowHelper) - so it might break with the next java update
It only sets the "indeterminate" progress state - but normal progress state should be possible too with some adjustments
Hope this helps.
ITaskbarList3.java
package example;
import com.sun.jna.platform.win32.Guid.IID;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinNT.HRESULT;
public interface ITaskbarList3 {
IID IID_ITASKBARLIST3 = new IID("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf"); // from ShObjIdl.h
int TBPF_NOPROGRESS = 0;
int TBPF_INDETERMINATE = 0x1;
int TBPF_NORMAL = 0x2;
int TBPF_ERROR = 0x4;
int TBPF_PAUSED = 0x8;
HRESULT SetProgressState(HWND hwnd, int tbpFlags);
}
TaskbarList3.java
package example;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinNT.HRESULT;
import com.sun.jna.platform.win32.COM.COMInvoker;
public final class TaskbarList3 extends COMInvoker implements ITaskbarList3 {
public TaskbarList3(Pointer pointer) {
setPointer(pointer);
}
#Override
public HRESULT SetProgressState(HWND hwnd, int tbpFlags) {
return (HRESULT) this._invokeNativeObject(
10, // magic number (gathered by trial and error)
new Object[] { this.getPointer(), hwnd, tbpFlags },
HRESULT.class);
}
}
TaskbarPeer.java
package example;
import com.sun.javafx.stage.WindowHelper;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Guid.CLSID;
import com.sun.jna.platform.win32.Ole32;
import com.sun.jna.platform.win32.W32Errors;
import com.sun.jna.platform.win32.WTypes;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.ptr.PointerByReference;
import javafx.stage.Stage;
public final class TaskbarPeer {
public static void setIndeterminateProgress(Stage stage, boolean indeterminate) {
final var peer = WindowHelper.getPeer(stage);
final long windowHandle = peer.getRawHandle();
final var clsid = new CLSID("56FDF344-FD6D-11d0-958A-006097C9A090"); // from ShObjIdl.h
final var taskbarListPointerRef = new PointerByReference();
var hr = Ole32.INSTANCE.CoCreateInstance(clsid, null, WTypes.CLSCTX_SERVER,
ITaskbarList3.IID_ITASKBARLIST3, taskbarListPointerRef);
if (W32Errors.FAILED(hr)) {
throw new RuntimeException("failed with code: " + hr.intValue());
}
final TaskbarList3 taskbarList = new TaskbarList3(taskbarListPointerRef.getValue());
final var hwnd = new HWND(new Pointer(windowHandle));
final int progressState = indeterminate ? ITaskbarList3.TBPF_INDETERMINATE : ITaskbarList3.TBPF_NOPROGRESS;
hr = taskbarList.SetProgressState(hwnd, progressState);
if (W32Errors.FAILED(hr)) {
throw new RuntimeException("failed with code: " + hr.intValue());
}
}
}
Sample.java
package example;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public final class Sample extends Application {
private boolean indeterminateProgressState = false;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
final Button btn = new Button("Click me!");
primaryStage.setScene(new Scene(btn));
primaryStage.sizeToScene();
primaryStage.show();
btn.setOnAction(evt -> {
indeterminateProgressState = !indeterminateProgressState;
TaskbarPeer.setIndeterminateProgress(primaryStage, indeterminateProgressState);
});
}
}
Windows exposes this through COM. I am sure a "flat DLL" call would be easier for you, but if you can get to COM you can do this. The COM interface is ITaskbarList3 (there is also an ITaskbarList4 you can use that inherits from it.) http://msdn.microsoft.com/en-us/library/dd391692(VS.85).aspx documents it. SetProgressState and SetProgressValue are the methods you will want to invoke. State is normal (green), paused (yellow), error (red), indeterminate (swooshing green) and none. On the MSDN page some community people have added details of calling this COM component from VB and C# - that might help you figure out the setup and tear down required from Java.

Playing sound in Java using java.applet class

I am building a simple program with one button. I want to play the "zvuk.wav" file after I click on the button. It's not working though and I cant solve why. When I click the button, nothing happens. The zvuk.wav file is in the src file with the classes.
Here is my first class which imports java.applet:
package Music;
import java.net.MalformedURLException;
import java.net.URL;
import java.applet.*;
public class Music {
private URL soubor;
public Music(String cesta){
try {
soubor = new URL("file:"+cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button:
package Music;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame{
public static final int WIDTH = 480;
public static final int HEIGHT = 600;
private String file;
public MainFrame(){
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
JButton bPlay = new JButton("PLAY");
jPanel.setLayout(null);
add(jPanel);
jPanel.add(bPlay);
bPlay.setBounds(200, 250, 100, 50);
bPlay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Music music = new Music("zvuk.wav");
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
Please note that Applet.newAudioClip(url).play() does not throw an error if it fails for whatever reason (for example nothing will happen if the project cannot find the wav file).
Try this stand alone test app. Does it work?
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class MainClass {
public static void main(String[] args) {
try {
URL url = new URL("file:zvuk.wav" );
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
System.in.read();
ac.stop();
} catch (Exception e) {
System.out.println(e);
}
}
}
If this small sample works, then it should be a small matter to modify it for your purposes.
However if it doesn't work then we almost certainly know that you project is unable to find the wav file.
Try add this to the code above:
//existing line
URL url = new URL("file:zvuk.wav" );
//new lines to debug wav file location
File myMusicFile = new File(url.getPath());
if(myMusicFile.exists() && !myMusicFile.isDirectory()) {
System.out.println("File exists and is not a directory");
}
If the file does not exist then that's your problem, and you need to point your URL to the correct location.
However if the file does exist and it still doesn't work then we have another possible issue outside of code.
It is possible that .play() is completing too quickly, see below for an example of how to keep it alive.
It is possible that your wav file is not a type that can be played, or it requires an unsupported codec. This is a far bigger topic and needs a new question, and a little bit of research on your part.
Here is the example to keep it alive from the sample code:
//load and start audio
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
//keep thread alive until a key is pressed
System.in.read();
ac.stop();
Sources:
http://www.java2s.com/Code/JavaAPI/java.applet/AppletnewAudioClipURLaudioFileURL.htm
http://docs.oracle.com/javase/7/docs/api/java/applet/AudioClip.html#play%28%29
I do this using NetBeans. This is the code.
Music.java file
package sound.play;
import java.applet.Applet;
import java.net.MalformedURLException;
import java.net.URL;
public class Music {
private URL soubor;
public Music(String cesta) {
try {
soubor = new URL("file:" + cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MainFrame extends javax.swing.JFrame {
public static final int WIDTH = 200;
public static final int HEIGHT = 200;
private String file;
public MainFrame() {
initComponents();
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
jPanel.setLayout(null);
add(jPanel);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Music music = new Music("zvuk.wav");
String filename = "zvuk.wav";
URL url = this.getClass().getResource(filename);
File myMusicFile = new File(url.getPath());
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}

if statement returning false for unknown reason

I posted a question a few minutes ago and it was requested that I post an "SSCCE" to demonstrate my issue. I have heavily condensed my program so if a few constructs make no sense or seem even more ineffcient than a novice's work ought to be that's simply a product of that operation.
Now, my program essentially serves to copy an array of Russian verbs conjugations to a centralized array, oneRay. In the setup here, a prompt is shown above a blank line, and in that blank line one is to type the appropriate conjugation. Pressing the "Submit" button is supposed to check the answers against those of the array, but by my own fault or lack of understanding I see the message "FAIL" even when directly copying what I know to be the correct answer. With this line I get the input:
build1 = new StringBuilder(ssfield1.getText());
and with this I check it against the element:
if(build1.equals(oneRay[pick][1].toLowerCase().replaceAll("\\s","")))ssfield1.setText("CORRECT");
else{ssfield1.setText("FAIL");}
I feel that this may be a simple issue of checking the wrong element against the wrong input textfield, however it mayn't be, so here is all the code of my condensed "SSCCE":
Not to long I hope, and certainly self-contained (and quite simple too):
Let me know if you need anything else, or if it's too late for these questions!
package wbh;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class SwingImplementation_RUS extends JFrame{
String [] [] oneRay;Random random = new Random();
JPanel panel; JTextField field,sfield1,sfield2,ssfield1,ssfield2; JButton buton;
int pick, hold;StringBuilder build1,build2;
public SwingImplementation_RUS(final int subj){
super("To be updated");
final String RUS_1[][]={
{"знать","знаю","знаешь","знает","знает","знает","знаем","знаете","знают",}};
new Thread(new Runnable() {
public void run() {
buton = new JButton("Submit");
setLayout(new GridLayout(3,1,3,3));
panel = new JPanel();panel.setLayout(new GridLayout(5,2,3,3));
field = new JTextField();
sfield1 = new JTextField("Я");sfield2 = new JTextField("Ты");
ssfield1 = new JTextField("");ssfield2 = new JTextField("");
buton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent m) {
System.out.println("CHECKED");
build1 = new StringBuilder(ssfield1.getText());
build2 = new StringBuilder(ssfield2.getText());
called2();}});
Font f = new Font("Arial", Font.BOLD, 75);
field.setFont(f);
add(field);
add(panel);
panel.add(sfield1);panel.add(ssfield1);
panel.add(sfield2);panel.add(ssfield2);
add(buton);
setLocation(500,0);setSize(865, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setVisible(true);
}}).start();
oneRay = new String[RUS_1.length][9];
for(int i = 0; (RUS_1.length) > i; i++){
oneRay[i][0] = RUS_1[i][0];oneRay[i][1] = RUS_1[i][1];
oneRay[i][2] = RUS_1[i][2];}
try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}
hold = oneRay.length;pick = random.nextInt(hold);
field.setText(" "+oneRay[pick][0]);
}
private void called2(){
if(build1.equals(oneRay[pick][1].toLowerCase().replaceAll("\\s","")))ssfield1.setText("CORRECT");
else{ssfield1.setText("FAIL");}
if(build2.equals(oneRay[pick][2].toLowerCase().replaceAll("\\s","")))ssfield2.setText("CORRECT");
else{ssfield2.setText("FAIL");}
}
public static void main (String [] args){
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new SwingImplementation_RUS(1);
}
});
}
}
I think the problem is that you are using StringBuilder#equals and expected it to work like String#equals.
The implementation of equals for StringBuilder looks like...
public boolean equals(Object obj) {
return (this == obj);
}
Which is just comparing the object references, not there contents.
Instead, try using something like...
if (build1.toString().equals(oneRay[pick][1].toLowerCase().replaceAll("\\s", ""))) ...
As a recommendation, you should also use {} around your if-else conditions, for example
if (build1.toString().equals(oneRay[pick][1].toLowerCase().replaceAll("\\s", ""))) {
ssfield1.setText("CORRECT");
} else {
ssfield1.setText("FAIL");
}
if (build2.toString().equals(oneRay[pick][2].toLowerCase().replaceAll("\\s", ""))) {
ssfield2.setText("CORRECT");
} else {
ssfield2.setText("FAIL");
}
Which will make it easier to read (generally) and ensure that you are not accidently executing functionality you didn't expect for a condition...

Different behavior of JDialog when is created by program and by user action

I have 3 clasess : Loader, MyDialog and TEST(with main method). (for code see below)
Everything I want to achieve is create simple dialog with JLabel and JProgressBar, which will notify user about how much time remains to show MyDialog. MyDialog is Jdialog with time consuming operation in constructor (loading data from database etc.).
In code below is model situation. When "MyDialog" is created by main (constant BY_USER is false), everything working exactly i want to. But when i make dialog with button , and instance of MyDialog is created after button press (constant BY_USER is true), Loader is blank white form. It looks like is not completed.
Loader is extending Thread, so i suppose that problem will be in threading (event dispatch thread)? I dont know, what is wrong and how fix it. Please help.
Thanks and sorry for my English.
CLASS TEST :
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class TEST {
public static final boolean BY_USER = false;
public static void main(String[] args) {
if (BY_USER) {
JFrame mainDialog = new JFrame("Main");
JButton show = new JButton("Show MyDialog");
show.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
MyDialog dialog = new MyDialog();
}
});
mainDialog.add(show);
mainDialog.setLocationRelativeTo(null);
mainDialog.setMinimumSize(new Dimension(160, 80));
mainDialog.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainDialog.setVisible(true);
} else {
MyDialog dialog = new MyDialog();
}
}
}
CLASS MyDialog :
package test;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class MyDialog extends JFrame{
public MyDialog() {
super();
// making loader with title, first message and count of steps of operation
Loader loader = new Loader("Loader", "First showed message", 100);
loader.ShowLoader();
// time-consuming operation (loading data from database etc.).
// for clarity replaced with for statement
int j=0;
for(int i=0; i<Integer.MAX_VALUE; i++)
{
j++;
if(j==Integer.MAX_VALUE/100){
// updating loader message and progress bar value
loader.NewAction(Integer.MAX_VALUE - i+"");
j=0;
}
}
// closing loader
loader.DestroyLoader();
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(300, 300);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
CLASS Loader:
package test;
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Dimension;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
public class Loader extends Thread{
private JDialog dialog;
private JLabel message = new JLabel("", SwingConstants.CENTER);
private JProgressBar progressBar = new JProgressBar(0, 100);
private String newMessage;
private double percentForStep;
private int remainingSteps;
public Loader(String taskName, String firstMessage, int steps) {
this.remainingSteps = steps-1;
dialog = new JDialog((Dialog) null, taskName);
dialog.setLayout(new BorderLayout(15, 15));
dialog.add(message, BorderLayout.CENTER);
dialog.add(progressBar, BorderLayout.SOUTH);
message.setText(firstMessage);
percentForStep = 100 / steps;
}
public void ShowLoader()
{
dialog.setMinimumSize(new Dimension(400,120));
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
this.start();
}
public void DestroyLoader(){
dialog.dispose();
this.interrupt();
}
public void NewAction(String newMessage){
this.newMessage = newMessage;
this.remainingSteps--;
Lock.changed = true;
}
public int RemainingStepsCount()
{
return remainingSteps;
}
#Override
#SuppressWarnings({"CallToThreadYield", "SleepWhileInLoop"})
public void run() {
do{
synchronized (Lock.class) {
if (Lock.changed) {
Lock.changed = false;
this.message.setText(newMessage);
this.progressBar.setValue((int)(100-(remainingSteps*percentForStep)));
dialog.repaint();
}
dialog.repaint();
}
}while(true);
}
}
class Lock{
static boolean changed = false;
}
Look to SwingWorker and his use; I think it can help you to solve the problem.

Delayed text color change in Swing text field

Is it possible to change the color of a text in a text field?I am trying to build an interpreter, so I was wondering on how would you change the color of the text in real time.
For example the word I enter in the text field is:
printf("hi");
The word printf becomes green after a few seconds.
Is it possible?
package test;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class BlinkColorTextField {
BlinkColorTextField() {
final JTextField blinkingText = new JTextField("Red & Blue");
ActionListener blinker = new ActionListener() {
boolean isRed = true;
public void actionPerformed(ActionEvent ae) {
if (isRed) {
blinkingText.setForeground(Color.BLUE);
} else {
blinkingText.setForeground(Color.RED);
}
isRed = !isRed;
}
};
Timer timer = new Timer(1000, blinker);
timer.start();
JOptionPane.showMessageDialog(null, blinkingText);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new BlinkColorTextField();
}
});
}
}
Try this:
HighlightPainter greenPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.GREEN);
//in a thread...
Highlighter h = tf.getHighlighter();
h.addHighlight(offset, offset+length, greenPainter);
You have to use JEditorPane / JTextPane instead of JTextField and also you can draw the text/string by overriding the paintComponent method.

Categories