Move JLabel in GridLayout java swing - java

I'm trying to move a Robot represented by a JLabel into a GridLayout.
The move is made but the display of the JLabel is only done for the final finishing square.
I would like to see the move from box to box. How can I do ?
import java.awt.Color;
import java.awt.Component;
import java.awt.LayoutManager;
import java.io.Serializable;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.LayoutStyle;
// Robot
public class Robot extends Case implements Serializable {
private ImageIcon imageRobot;
private Color couleur;
public Robot () {
imageRobot = new ImageIcon("./assets/balle.png");
setIcon(imageRobot);
}
public void seDeplacer (JPanel panel, Vector<Case> listeDeCases) {
for (int i=0; i<5; i++) {
LayoutManager layout = panel.getLayout();
try { Thread.sleep(1000);
panel.remove(panel.getComponent(i));
panel.add(this, i);
panel.doLayout();
}
catch (InterruptedException e) {}
}
}
public void detruire () {
}
public void setCouleur (Color couleur) {
this.couleur=couleur;
}
public Color getCouleur () {
return this.couleur;
}
}

try { Thread.sleep(1000);
Don't do this on the AWT Event Dispatch Thread (EDT). Your GUI can't be repainted because this code is blocking it.
Use javax.swing.Timer (not to be confused with any other Timer) to set an event for the next time robot needs to be moved. You will need to keep track of state outside of local variables.

import java.awt.Color;
import java.awt.Component;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.LayoutStyle;
import javax.swing.Timer;
// Robot
public class Robot extends Case implements Serializable {
private ImageIcon imageRobot;
private Color couleur;
public Robot () {
imageRobot = new ImageIcon("./assets/balle.png");
setIcon(imageRobot);
}
public void seDeplacer (JPanel panel) {
Robot currentRoot = this;
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
for (int i=0; i<5; i++) {
panel.remove(panel.getComponent(i));
panel.add(currentRoot, i);
panel.doLayout();
}
}
};
new Timer(delay, taskPerformer).start();
}
public void detruire () {
}
public void setCouleur (Color couleur) {
this.couleur=couleur;
}
public Color getCouleur () {
return this.couleur;
}
}

Related

How to keep the Auto Clicker running without the program stopping it immediately after running

package com.company.Iguana;
import java.awt.*;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.KeyEvent;
public class Main {
public static boolean Clicking = true;
public static Robot robot;
public static void main(String[] args) throws AWTException {
Robot robot = new Robot();
new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyChar() == 'x')
Clicking = true;
if(e.getKeyChar() == 'v')
Clicking = false;
if(Clicking == true)
while(true){
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(1000);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}
}
#Override
public void keyReleased(KeyEvent e) {
}
};
}
}
I'm trying to make it so whenever I press x the AutoClicker start and Stop it when I press v but once I run the code it just says public static void main(String[] args) but when I put in static it says 23:9
java: non-static variable this cannot be referenced from a static context
Line 23:9 is the this.addKeyListener( new KeyListener() {
..................................................................................................................................................................................................................

hyperlink with JLabel in Java Swing

i have a little problem with my code, meaning that hyperlink not showing under JLabel. I tried to resolve that problem by creating JLabel in different class and run the method in main class, but when i do that, it returning me only white square instead of label. no errors while compiling.
Main class:
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.Desktop;
import java.awt.event.ActionListener;
import java.net.URI;
public class Main extends JFrame
{
static JLabel appicationStatute;
public Main() throws Exception
{
super();
registerWindowFrame = new JFrame("name");
registerWindowFrame.setSize(500,750);
registerWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
registerWindowFrame.setLayout(null);
registerWindowFrame.getContentPane().setBackground(Color.RED);
Statute status = new Statute();
status.setSize(status.getPreferredSize());
status.setLocation(10,450);
registerWindowFrame.getContentPane().add(status);
registerWindowFrame.setVisible(true);
}
public static void main (String [] args) throws Exception
{
new Main();
}
}
Statue class
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.*;
public class Statute extends JPanel {
private String text = "application statute";
private JLabel hyperlink = new JLabel(text);
public Statute() throws HeadlessException {
super();
hyperlink.setForeground(Color.BLUE.darker());
hyperlink.setCursor(new Cursor(Cursor.HAND_CURSOR));
hyperlink.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
Desktop.getDesktop().browse(new URI("http://www.codejava.net"));
} catch (IOException | URISyntaxException e1) {
e1.printStackTrace();
}
}
#Override
public void mouseExited(MouseEvent e) {
hyperlink.setText(text);
}
#Override
public void mouseEntered(MouseEvent e) {
hyperlink.setText("<html><a href=''>" + text + "</a></html>");
}
});
}
}

Java task not updating jlabel

Question I have is I am trying to update my gui with a timer(this works and changes the image for mypic but, it will not update mytext label for some weird reason any help would be very much appreciated!
*I should add that mytext isn't showing up at all on my gui since introducing the timer...but mypic does????
package widget;
import com.sun.awt.AWTUtilities;
import com.sun.xml.internal.ws.client.sei.ResponseBuilder;
import javafx.geometry.HorizontalDirection;
import javafx.scene.shape.Ellipse;
import javax.swing.*;
import javax.swing.Timer;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.xml.sax.SAXException;
import widget.weather;
import static java.awt.Color.*;
/**
* Created by xxxxxxzz on 10/19/2016.
*/
public class Widget extends JFrame {
String icon_image = null;
String temp = null;
JLabel myText = null;
JLabel mypic = null;
Timer SimpleTimer = new Timer(5000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
icon_image = weather.weather_pic();
temp = weather.temp();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText = new JLabel(temp);
//Tried setting it like this and still doesn't work
// myText = new JLabel("HOT");
mypic = new JLabel();
myText.setText(temp);
mypic.setIcon(img);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
public Widget() throws IOException, URISyntaxException {
setUndecorated(true);
setSize(150,150);
temp = weather.temp();
icon_image = weather.weather_pic();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText = new JLabel(temp);
mypic = new JLabel();
myText.setText(temp);
mypic.setIcon(img);
myText.setHorizontalAlignment(JLabel.CENTER);
mypic.setHorizontalAlignment(JLabel.CENTER);
add(myText);
add(mypic);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
Shape shape = new Ellipse2D.Float(0,0,150,150);
AWTUtilities.setWindowShape(this, shape);
SimpleTimer.start();
}
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, URISyntaxException {
new Widget();
}
}
UPDATE with suggestions still isn't working..
package widget;
import com.sun.awt.AWTUtilities;
import com.sun.xml.internal.ws.client.sei.ResponseBuilder;
import javafx.geometry.HorizontalDirection;
import javafx.scene.shape.Ellipse;
import javax.swing.*;
import javax.swing.Timer;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.xml.sax.SAXException;
import widget.weather;
import static java.awt.Color.*;
/**
* Created by jsnow on 10/19/2016.
*/
public class Widget extends JFrame {
String icon_image = null;
String temp = null;
JLabel myText = new JLabel();
JLabel mypic = new JLabel();
Timer SimpleTimer = new Timer(5000, new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
icon_image = weather.weather_pic();
temp = weather.temp();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText.setText(temp);
mypic.setIcon(img);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
public Widget() throws IOException, URISyntaxException {
setUndecorated(true);
setSize(150,150);
temp = weather.temp();
icon_image = weather.weather_pic();
URL url = new URL(icon_image);
ImageIcon img = new ImageIcon(url);
myText.setText(temp);
mypic.setIcon(img);
myText.setHorizontalAlignment(JLabel.CENTER);
mypic.setHorizontalAlignment(JLabel.CENTER);
add(myText);
add(mypic);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
Shape shape = new Ellipse2D.Float(0,0,150,150);
AWTUtilities.setWindowShape(this, shape);
SimpleTimer.start();
}
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException, URISyntaxException {
new Widget();
}
}
Here's a working solution which you can tailor to your use. The cause seemed to be the way you had tried to display the Components rather than the code in your action listener.
Your approach was just replacing myText with myPic when you initially set up the JFrame. Instead you need to use a layout manager. The example I've given is with overlaying using JLayeredPane. You may wish to use a layout manager instead if this is not the desired outcome, see the Oracle Tutorial on using layout managers.
Widget class
package widget;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Widget extends JFrame {
private static final int UPDATE_TICK = 5_000;
private static final int WIDGET_WIDTH = 150;
private static final int WIDGET_HEIGHT = 150;
private JLabel myText = new JLabel();
private JLabel myPic = new JLabel();
private Weather weather = new Weather();
private Timer simpleTimer;
public void createAndShow() {
setUndecorated(true);
setSize(WIDGET_WIDTH, WIDGET_HEIGHT);
Shape shape = new Ellipse2D.Float(0, 0, WIDGET_WIDTH, WIDGET_HEIGHT);
// AWTUtilities.setWindowShape(this, shape);
setShape(shape); // do this instead
myText.setHorizontalAlignment(JLabel.CENTER);
myPic.setHorizontalAlignment(JLabel.CENTER);
JLayeredPane layered = new JLayeredPane();
myText.setBounds(0, 0, WIDGET_WIDTH, WIDGET_HEIGHT);
myPic.setBounds(0, 0, WIDGET_WIDTH, WIDGET_HEIGHT);
layered.add(myPic, 1, 0);
layered.add(myText, 2, 0);
add(layered);
simpleTimer = new Timer(UPDATE_TICK, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
update();
}
});
update();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
simpleTimer.start();
}
private void update() {
myText.setText(weather.getTemp());
myPic.setIcon(new ImageIcon(weather.getImage(WIDGET_WIDTH, WIDGET_HEIGHT)));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Widget w = new Widget();
w.createAndShow();;
}
});
}
}
Weather class for demonstration purposes
package widget;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.Random;
public class Weather {
private static final Random rand = new Random();
private static final Color[] randColors = {Color.YELLOW,
Color.GREEN,
Color.WHITE};
public String getTemp() {
return Integer.toString(rand.nextInt(100));
}
public BufferedImage getImage(int width, int height) {
int colorIndex = rand.nextInt(randColors.length);
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < img.getWidth(); x++) {
for (int y = 0; y < img.getHeight(); y++) {
img.setRGB(x, y, randColors[colorIndex].getRGB());
}
}
return img;
}
}

Reminder using JOptionPane

I am designing one reminder type application using java swing.
In this I am giving two options to user, using JOptionPane YES_NO_OPTION. But what i want is if user not given any input within 10 minutes it should choose YES as default option.
what i have to do for that?
Please check below code...
public void snooze()
{
int action = JOptionPane.showConfirmDialog(null, "Yes = close citrix and Aventail \n No = snooze after 30min", "Close", JOptionPane.YES_NO_OPTION);
if(action == 0){
killcitrix();
endaventail();
}
else{
JOptionPane.showMessageDialog(null, "Will snooze after 30min");
try {
TimeUnit.SECONDS.sleep(30);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
snooze();
}
}
As user1803551 already mentioned, use a Timer. Here is an example:
after 10 seconds of inactivity (if the user didn't press any button), the dialog will automatically dispose and the selected option will be JOptionPane.YES_OPTION
If the user pressed 'No', a new JOptionPane with the same functionalities will appear after 5 seconds.
Preview
Code:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.border.TitledBorder;
public class Example {
private int choice;
private JTextArea log;
public Example() {
log = new JTextArea();
log.setEditable(false);
JFrame frame = new JFrame();
frame.add(log);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
showConfirmDialog(frame);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example();
}
});
}
public void showConfirmDialog(Component parent) {
Timer timer = new Timer(0, null);
Timer timer2 = new Timer(0, null);
log.append("Will automatically press 'Yes' after 10 seconds.\n");
timer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Window window : Window.getWindows()) {
if (window instanceof JDialog) {
JDialog dialog = (JDialog) window;
if (dialog.getContentPane().getComponentCount() == 1
&& dialog.getContentPane().getComponent(0) instanceof JOptionPane
&& dialog.getTitle().equals("Dialog")) {
dialog.dispose();
choice = JOptionPane.YES_OPTION;
log.append("Programmatically pressed 'Yes' on the JOptionPane due to inactivity of user\n");
}
}
}
timer.stop();
timer2.stop();
}
});
timer.setInitialDelay(10 * 1000);
timer.start();
choice = JOptionPane.showConfirmDialog(parent, "", "Dialog", JOptionPane.YES_NO_CANCEL_OPTION);
if (choice == JOptionPane.NO_OPTION) {
log.append("Dialog will reappear in 5 seconds\n");
timer2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
log.append("Dialog reappeared\n");
showConfirmDialog(parent);
timer2.stop();
}
});
timer2.setInitialDelay(5 * 1000);
timer2.start();
}
timer.stop();
}
}

Message box without any buttons at all

I want to create auto-disposing message dialog. Everything works beside that there is still an ok button to click.
I want to get read the button.
Please check out this code -> works perfectly:
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class CloseOptionPane {
#SuppressWarnings("serial")
private static void createAndShowGui() {
final JLabel label = new JLabel();
int timerDelay = 1000;
new Timer(timerDelay, new ActionListener() {
int timeLeft = 3;
#Override
public void actionPerformed(ActionEvent e) {
if(timeLeft > 0) {
label.setText("Human player. It is your move!");
timeLeft--;
} else {
((Timer) e.getSource()).stop();
Window win = SwingUtilities.getWindowAncestor(label);
win.setVisible(false);
}
}
}) {
{
setInitialDelay(0);
}
}.start();
JOptionPane.showMessageDialog(null, label);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Categories