private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 148, 120);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
while(chckbxNewCheckBox.isSelected()){
try {
Robot auto = new Robot();
auto.delay(2300);
auto.mouseMove(377, 182);
auto.mousePress(InputEvent.BUTTON3_DOWN_MASK);
auto.mouseRelease(InputEvent.BUTTON3_DOWN_MASK);
//
auto.delay(1000);
auto.mouseMove(466, 293);
auto.mousePress(InputEvent.BUTTON1_DOWN_MASK);
auto.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
//
auto.delay(1000);
auto.mouseMove(1061, 217);
auto.mousePress(InputEvent.BUTTON1_DOWN_MASK);
auto.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
//
auto.delay(8000);
auto.mouseMove(601, 493);
auto.mousePress(InputEvent.BUTTON1_DOWN_MASK);
auto.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
//
auto.delay(60000);
auto.mouseMove(387, 355);
auto.mousePress(InputEvent.BUTTON1_DOWN_MASK);
auto.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
//
auto.delay(8000);
auto.mouseMove(705, 652);
auto.mousePress(InputEvent.BUTTON1_DOWN_MASK);
auto.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
} catch (AWTException e) {
e.printStackTrace();
}
}
} });
btnStart.setBounds(10, 47, 89, 23);
frame.getContentPane().add(btnStart);
JCheckBox chckbxNewCheckBox = new JCheckBox("New check box");
chckbxNewCheckBox.setBounds(2, 7, 97, 23);
frame.getContentPane().add(chckbxNewCheckBox);
}
I'd like some advice on putting the commands for my robot in a loop and the loop only execute when a checkbox is selected. I've tried a few different ways of doing it but none seem to be working. I'm sure I'm missing something simple but I can't seem to find what it was. Although doing it for me would help, explaining it would be great too. I am using eclipse, and the windowbuilder to add items.
Use threads:
You can run your commands in a different thread. The UI will be running in its own thread.
you could write you code in you new thread as ;
Class Robot implements Runnable{
public void run(){
while(programRunning)){
if(checkBox.isSelected())
{
//Perform commands.
}
else {// you may choose to sleep this thread here as well in case of not selected}
}
}
}
programRunning is another variable you can choose so as to keep the loop running even if the checkbox is not selected and the UI is program/application is still running.
You can do something like this:
while(CheckBox.isSelected()) {
// do the stuff
}
Update: I now understand the question. It is good to run long period task in a separate thread, so here you can use SwingWorker to perform the task. If you don't use thread, then the UI became hang by the while loop
Related
I am fairly new to programming of this level and I was wondering if someone could help me with this.
So I am trying to create a currency exchange app using Java, and I have a problem updating the values on the GUI to reflect the new value on the API. Essentially ever so often the values change and it shows on the console, however, the GUI value never updates and stays the same.
I thought ActionListener would help solve this problem but either I have not implemented it properly or I haven't googled and come up with a solution properly.
Thank you in advance for any help :)
Here is my code:
GUI.java
public class GUI extends JFrame {
static Arb arb = new Arb();
private JPanel contentPane;
public static void main(String[] args) throws IOException, InterruptedException {
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
arb.runUpdate_fx("anAPI");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Timer timer = new Timer(100 ,taskPerformer);
timer.setRepeats(true);
timer.start();
Thread.sleep(5000);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI frame = new GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1121, 765);
contentPane = new JPanel();
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JTextPane FXRate = new JTextPane();
FXRate.setForeground(new Color(255, 255, 255));
FXRate.setBackground(new Color(0, 0, 0));
FXRate.setEditable(false);
FXRate.setFont(new Font("Tahoma", Font.BOLD, 11));
panel_1.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
FXRate.setText("FX Rates\r\n\r\nEUR-AUD FX Rate: " + arb.fxEURAUD + "\r\nEUR-USD FX Rate: " + arb.fxEURUSD);
panel_1.add(FXRate);
}
}
Result:
EUR-AUD: 1.646659
after sometime
EUR-AUD: 1.646659
Expected Result:
EUR-AUD: 1.646659
after sometime
EUR-AUD: 1.80102
References are passed by value in Java.
JTextField textField = new JTextField();
String text = "Initial text";
textField.setText(text); // no displays "Initial text";
text = "Updated text"; // doesn't change what the panel displays
// the panel still holds a reference to the old text
textField.setText(text); // updates the reference the panel holds to your new text
In your event listener, you need to call setText with the updated string to actually make the textfield display that.
Your timer and event handler look good, but the update method only fetches new values into the Arb object; nothing takes those values and puts them into the GUI. You can do that explicitly in your event handler.after the update method returns. To enable that, you may want to make FXRate a member variable, so you can access it from the action listener.
I am trying to create an object when the user presses the button.So far, I've come up with the implementation bellow, but it does not seem to work.I haven't been dealing with Swing and Java UI at all so I am guessing it might be an amateur mistake.
The object I am trying to create is from another type called DebitCard.
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GenerateCard window = new GenerateCard();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GenerateCard() {
}
{
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewButton = new JButton("Generate card");
btnNewButton.setBounds(112, 213, 216, 41);
frame.getContentPane().add(btnNewButton);
}
private class buttonEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Generate card")) {
DebitCard a = new DebitCard();
}
}
}
Based on your available code, you seem to have forgotten to register buttonEvent with btnNewButton
btnNewButton.addActionListener(new buttonEvent());
You might want to take a closer look at:
How to Use Buttons, Check Boxes, and Radio Buttons
How to Write an Action Listener
Laying Out Components Within a Container
Code Conventions for the Java TM Programming Language (this will make your code easier to read and it easier for you to read others)
My java program is opening new window when i press one button in first window. Then i need to close first window. When i try to close first window with System.exit(0); it closes second window. I tryed setVisible(false); then first window doesn't close. Please help!
Whole code:
public class NameChooser extends JFrame implements ActionListener {
public NameChooser() {
RunNC();
}
public final void RunNC() {
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter your name that will be shown in game!");
label.setBounds(20, 10, 500, 25);
panel.add(label);
JLabel error = new JLabel("");
error.setForeground(Color.red);
panel.add(error);
JTextField name = new JTextField(30);
name.setBounds(50, 40, 180, 25);
panel.add(name);
JButton playButton = new JButton( new AbstractAction("Play") {
#Override
public void actionPerformed(ActionEvent e) {
String enteredname = name.getText();
if("".equals(enteredname)) {
error.setVisible(true);
error.setText("Invalid name!");
error.setBounds(105, 95, 100, 25);
System.out.println("Invalid name!");
}
else if(enteredname.length() > 10) {
error.setVisible(true);
error.setText("Name cant have more than 10 characters!");
error.setBounds(25, 95, 600, 25);
System.out.println("Name cant have more than 10 characters!");
}
error.setVisible(false);
GameWindow game = new GameWindow();
game.StartGame();
// I need to close window on this line!
}
});
playButton.setBounds(110, 70, 60, 25);
panel.add(playButton);
}
Any help?
Your problem is caused because System.exit() causes the Java VM to terminate completely - and both of your windows are running on the same VM instance.
Use Jframe.dispose() instead on the one you want to close.
System.exit(0);
doesn't "close a window", it terminates the JVM in which your entire application is running, hence, it terminates the entire application.
If we're talking about JFrames, try by using the dispose() method to close your seperate screens.
If you want us to comment on your setVisible(false), show us the code where you call it, it might be you're calling it on the wrong variable.
I am using swing timer to to load different pdf files in swing application
but I am facing a problem when ever I execute a program the screen remains blank for few seconds like 4 to 5 seconds and then the pdf file is rendered so during this time I want to show a message like please wait. Here is my sample code
if (type[i].equalsIgnoreCase("PDF")) {
int k = i;
pdfTimer = new Timer(0, (ActionEvent e) -> {
renderPDF(k);
});
pdfTimer.setDelay(1000*2);
pdfTimer.start();
Run rendering on SwingWorker's background thread (doInBackground) method. That way, your GUI will remain responsive. From done method you can notify user that rendering is done. Keep in mind not to update any Swing GUI from doInBackground method since it runs outside of EDT.
P.S. Swing Timer is for repetitive tasks.
You can display a progress bar and compute the renderding on a second thread.
JLabel lblWait = new JLabel("Please wait...");
lblWait .setBounds(116, 26, 113, 14);
contentPanel.add(lblWait );
final JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setBounds(72, 66, 187, 16);
contentPanel.add(progressBar);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
final JButton btFin = new JButton("Cancel");
btFin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
buttonPane.add(btFin);
}
}
Thread t = new Thread() {
public void run() {
//You launch the thread with your progress bar as an argument
maStructure.setaAfficher(new MgtSimulation(aAfficher, nombreSimulations).jouerSimulations(progressBar));
maStructure.actualiserAffichage();
dispose();
}
};
t.start();
}
And you change your progress bar value in your method
public BeanAffichage jouerSimulations(JProgressBar progressBar){
//Variables
for (int i = 0; i < nombreSimulations; i++) {
//Computing
progressBar.setValue(Whatever you want);
}
return aAfficher;
}
Just an alternative for SwingWorker
By default show some message like Loading... and create a Thread to run in the background which loads the PDF and updates the window
class BackgroundThread implements Runnable {
#Override
public void run() {
// the Swing call below must be queued onto the Swing event thread
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
// OK To make Swing method calls here
loadFile(args..);
repaint();//Or something similar that fits your purpose
}
});
}
}
I'm new to java but want to learn and not be spoon-fed so please keep that in mind :)
I'm working with swing to make a GUI for sending mass messages using a Java API for Skype. I've figured out my methods and have working code for the mass messenger and all and now i'm with swing. I've made a few buttons and worked out the front end of the GUI now I need to implement my method.
Here is my code so far:
private void createContents()
throws SkypeException, InterruptedException {
final Mass objCL = new Mass();
objCL.skype();
shell = new Shell();
shell.setSize(450, 300);
shell.setText("Test");
text = new Text(shell, SWT.BORDER);
text.setToolTipText("Your message to send");
text.setBounds(121, 166, 249, 38);
Button btnSend = new Button(shell, SWT.NONE);
btnSend.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
objCL.skype();
}
});
btnSend.setBounds(203, 210, 83, 29);
btnSend.setText("SEND");
Link link = new Link(shell, SWT.NONE);
link.setBounds(10, 250, 83, 15);
link.setText("<a>Our Website</a>");
}
(Code tag left out a '}' Don't worry it is not the problem)
Now the error I have is swing will not allow me to put a
public void widgetSelected(SelectionEvent e) *InterruptedException* {
objCL.skype();
}
Eclipse outputs the error as
Unhandled exception type InterruptedException
Any ideas guys?
Wrap objCL.skype(); in try-catch clause, it is not handled by the outer methods as they have no contextual relationship to each other (the createContents method would have been called, exited and the program moved on a long time before widgetSelected is called)...
try {
objCL.skype();
} catch (InterruptedException exp) {
exp.printStackTrace();
}
See the section on Catching and Handling Exceptions for more details