Can't animate an Image in a JLabel - java

I would like to animate an Image placed in a JLabel like you can see below.
I have a problem with animation. The code doesn't produce any errors, but it just works in the void indefinitely.
Class Obstacle:
package imageTest;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Obstacle extends JPanel {
//Position
int posX,posY;
public int getPosX(){
return this.posX;
}
public void setPosX(int posX){
this.posX=posX;
}
public int getPosY(){
return this.posY;
}
public void setPosY(int posY){
this.posY=posY;
}
public int fctHasard(int borneInf,int borneSup){
int random = (int)(Math.random() * (borneSup-borneInf)) + borneInf;
return random;
}
//Image Obstacle
Image imgObstacle =new Image("C:\\Users\\antoine\\Desktop\\imgProjetObstacle.JPG");
JLabel labImgObstacle =null;
public void fctDessinerObstacle(JFrame fenPrincipale, JPanel panPrincipale) throws IOException{
int posXDepart=fctHasard(0,fenPrincipale.getWidth()),posYDepart=ImageUtil.getImageHeight(imgObstacle.adresseImg);
posX=posXDepart;
posY=posYDepart;
labImgObstacle=imgObstacle.fctAfficherImg(panPrincipale, posX,posY,ImageUtil.getImageWidth(imgObstacle.adresseImg), ImageUtil.getImageHeight(imgObstacle.adresseImg));
panPrincipale.add(labImgObstacle);
//fctMouvement(fenPrincipale, labImgObstacle ,panPrincipale,posX,posY);
}
public void fctMouvement(JFrame fenPrincipale, JLabel labImgObstacle , JPanel panPrincipale,int posX ,int posY) throws IOException{
boolean continuer=true;
while(continuer){
posY++;
labImgObstacle=imgObstacle.fctAfficherImg(panPrincipale, posX,posY,ImageUtil.getImageWidth(imgObstacle.adresseImg), ImageUtil.getImageHeight(imgObstacle.adresseImg));
panPrincipale.add(labImgObstacle);
panPrincipale.repaint();//remetlefondvierge
if(posY==fenPrincipale.getHeight()){
posX=fctHasard(0,fenPrincipale.getWidth());
posY=-ImageUtil.getImageHeight(imgObstacle.adresseImg);
//remet le fond vierge
labImgObstacle=imgObstacle.fctAfficherImg(panPrincipale, posX,posY,ImageUtil.getImageWidth(imgObstacle.adresseImg), ImageUtil.getImageHeight(imgObstacle.adresseImg));
panPrincipale.add(labImgObstacle);
}
}
}
}
EDIT1:

I try to understand you problem, is it to move a image into a JLabel ?
In this case, I try just to put an image as icon into a Jlabel and move while clicking on the JPanel as you can see below :
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.UIManager;
import javax.swing.SwingUtilities;
public class Main extends JPanel {
public JLabel label1 ;
private int x = 100;
private int y = 5;
public Main() {
setLayout(null);
setPreferredSize( new Dimension(640, 480 ) );
addMouseListener(new MouseListener() {
#Override
public void mousePressed(MouseEvent e) {
x = x + 10;
y = y + 10;
label1.setBounds(x + getInsets().left, y + getInsets().top, label1.getPreferredSize().width, label1.getPreferredSize().height);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
ImageIcon icon = createImageIcon("middle.gif", "a pretty but meaningless splat");
label1 = new JLabel("Image and Text",icon, JLabel.CENTER);
add(label1);
label1.setBounds(x + getInsets().left, y + getInsets().top, label1.getPreferredSize().width, label1.getPreferredSize().height);
}
protected static ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = Main.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Main());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
May be that could be the beginning to animate something ?

Related

Mouse Goes behind part of the panel where it has been drawn on

So I am currently making a canvas painter in the style of Microsoft paint in Java. One of the features I was currently working on is the color picker. Now I got it to change the icon cursor but the issue comes with its implementation. I wish to get the color of the pixel that the cursor clicked on (which I already got it working). However, When I try to hover the curser over something I drew on the panel, the mouse goes behind the drawing that I made. To better explain this, I have added a Gif of the aforementioned issue.
Here is the code for my program
Main.java
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new Controller(new View(),new Model());
}
}
View.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.PanelUI;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.net.URL;
import java.nio.channels.NonReadableChannelException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import org.kordamp.ikonli.swing.FontIcon;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.GridBagConstraints;
public class View extends JFrame implements MouseListener{
protected static int imgNum = new File("src//imgs").listFiles().length;
private Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
private double width = screenSize.getWidth(), height = screenSize.getHeight();
protected static JPanel panel = new JPanel();
private JPanel buttonsPanel = new JPanel(), colPre = new JPanel();
private static JLabel[] toolsButtonSetIcons = new JLabel[imgNum];
private JMenuBar menuBar = new JMenuBar();
private ImageIcon[] icons = new ImageIcon[imgNum];
protected static URL[] iconURLs = new URL[imgNum];
private JMenu menu = new JMenu("File"), edit = new JMenu("Edit");
protected JMenuItem picImport = new JMenuItem("Import Picture"), pencilSizeChangeMenu = new JMenuItem("Change Pen Size");
private GridBagConstraints gbc = new GridBagConstraints();
private JSlider redSlider,greenSlider,blueSlider;
URL[] tempURLArr;
private static String[] toolNameStrings = { "Eraser", "Cutter", "Pencil", "Color Chooser", "Color Picker",
"Transform", "Picture", "Color Slider","Move" };
JLabel imgLabel;
public View() {
}
public void setupDisplay() {
this.setSize(new Dimension((int) width - 20, (int) height - 60));
this.setTitle("Canvas Painter");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.add(panel);
this.add(buttonsPanel, BorderLayout.WEST);
this.setJMenuBar(menuBar);
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
menu.add(picImport);
menuBar.add(menu);
menuBar.add(edit);
buttonsPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
setupToolButtonSet();
new Controller().setupPicImportMenuAction(picImport, panel,imgLabel);
System.out.printf("JFrame width: %d and height: %d\n", this.getWidth(), this.getHeight());
this.setVisible(true);
}
private void setupToolButtonSet() {
buttonsPanel.setPreferredSize(new Dimension(150, 100));
System.out.println(imgNum);
for (int i = 0; i < imgNum; i++) {
// buttonsPanel.add(Box.createRigidArea(new Dimension(5, 35)));
iconURLs[i] = getClass().getResource(String.format("./imgs/icon%d.png", i));
System.out.println(String.format("./imgs/icon%d.png", i));
icons[i] = new ImageIcon(
new ImageIcon(iconURLs[i]).getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
toolsButtonSetIcons[i] = new JLabel(icons[i]);
toolsButtonSetIcons[i].setToolTipText(toolNameStrings[i]);
buttonsPanel.add(toolsButtonSetIcons[i]);
}
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
protected static JLabel[] getLabelSet() {
return toolsButtonSetIcons;
}
protected static String[] getLabelNameArray() {
return toolNameStrings;
}
protected static URL[] getURLArray() {return iconURLs;}
protected void displayColorSliderDialogue() {
JPanel colorDialogPanel = new JPanel(), westColorDialoguePanel = new JPanel(), colorPreviewPanel = new JPanel();
JButton colorDialogValidateButton = new JButton("Ok");
JDialog colorDialog = new JDialog(this, "Color Customization");
JSlider rSlider = new JSlider(0, 255), gSlider = new JSlider(0, 255), bSlider = new JSlider(0, 255);
colorDialog.setSize(new Dimension(400, 240));
colorDialog.add(westColorDialoguePanel, BorderLayout.WEST);
colorDialog.add(colorPreviewPanel, BorderLayout.CENTER);
colorDialog.add(colorDialogPanel, BorderLayout.SOUTH);
westColorDialoguePanel.add(Box.createRigidArea(new Dimension(5, 5)));
westColorDialoguePanel.setLayout(new BoxLayout(westColorDialoguePanel, BoxLayout.Y_AXIS));
westColorDialoguePanel.add(new JLabel("R"));
westColorDialoguePanel.add(rSlider);
westColorDialoguePanel.add(Box.createRigidArea(new Dimension(5, 20)));
westColorDialoguePanel.add(new JLabel("G"));
westColorDialoguePanel.add(gSlider);
westColorDialoguePanel.add(Box.createRigidArea(new Dimension(5, 20)));
westColorDialoguePanel.add(new JLabel("B"));
westColorDialoguePanel.add(bSlider);
colorDialogPanel.add(colorDialogValidateButton);
colorPreviewPanel.setBackground(new Color(rSlider.getValue(), gSlider.getValue(), bSlider.getValue()));
new Controller().setupColorChangeDialogAction(rSlider,gSlider,bSlider,colorDialogValidateButton,colorPreviewPanel);
colorDialog.setLocationRelativeTo(null);
colorDialog.setVisible(true);
colorDialog.setResizable(false);
colorDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
}
protected JSlider getRSlider() {return redSlider;}
protected JSlider getGSlider() {return greenSlider;}
protected JSlider getBSlider() {return blueSlider;}
protected JPanel getColPrevLab() {return colPre;}
protected ImageIcon [] getIconArray() {return icons;}
private class Panel extends JPanel {
}
}
Controller.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.TimerTask;
import java.awt.event.MouseListener;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Robot;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.ColorUIResource;
import javax.swing.text.AttributeSet.ColorAttribute;
import java.awt.MouseInfo;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.Toolkit;
/**
*
* #author Malik
*
*/
public class Controller extends View implements MouseListener, MouseMotionListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private Graphics g;
private static Color drawColor;
private JLabel[] buttonLabels = getLabelSet();
private String[] labelNameStrings = getLabelNameArray();
private URL[] urlArray = getURLArray();
private final int ERASER = 0, CUTTER = 1, PENCIL = 2, COLOR_CHOOSER = 3, COLOR_PICKER = 4, TRANSFORM = 5,
PICTURE = 6, COLOR_SLIDER = 7;
private final Color defaultColor = new Color(0, 0, 0);
private static boolean colorChanged = false;
private String currentTool = "pencil";
private JSlider rSlider = super.getRSlider(), gSlider = super.getGSlider(), bSlider = super.getBSlider();
private JPanel colPreview = super.getColPrevLab();
private JLabel imgLb;
private Image image;
public Controller(View v, Model m) {
System.out.println("inside controller");
v.setupDisplay();
setLabelVisibility(buttonLabels);
View.panel.addMouseListener(this);
View.panel.addMouseMotionListener(this);
for (int i = 0; i < buttonLabels.length; i++)
buttonLabels[i].addMouseListener(this);
}
public Controller() {
}
#Override
public void mouseClicked(MouseEvent e) {
for (int i = 0; i < buttonLabels.length; i++) {
if (e.getSource() == buttonLabels[COLOR_CHOOSER]) {
// g.setColor();
System.out.printf("You clicked: %s\n", labelNameStrings[COLOR_CHOOSER]);
drawColor = JColorChooser.showDialog(this, "Select a color", Color.RED);
colorChanged = true;
break;
}
if (e.getSource() == buttonLabels[ERASER]) {
currentTool = "eraser";
System.out.printf("You clicked: %s\n", labelNameStrings[COLOR_CHOOSER]);
break;
}
if (e.getSource() == buttonLabels[PENCIL]) {
currentTool = "pencil";
super.panel.setCursor(null);
System.out.printf("You clicked: %s\n", labelNameStrings[PENCIL]);
break;
}
if (e.getSource() == buttonLabels[COLOR_SLIDER]) {
currentTool = "Color Slider";
super.displayColorSliderDialogue();
System.out.printf("You clicked: %s\n", labelNameStrings[COLOR_SLIDER]);
break;
}
if (e.getSource() == buttonLabels[COLOR_PICKER]) {
currentTool = "Color Picker";
// System.out.println(urlArray[0].toString());
System.out.printf("You clicked: %s", labelNameStrings[COLOR_PICKER]);
changeCursor(super.panel, buttonLabels[COLOR_PICKER], urlArray[COLOR_PICKER]);
super.panel.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
int xValue = MouseInfo.getPointerInfo().getLocation().x;
int yValue = MouseInfo.getPointerInfo().getLocation().y;
Robot robot;
try {
robot = new Robot();
Color color = robot.getPixelColor(xValue, yValue);
System.out.println(color);
panel.revalidate();
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
break;
}
}
// View.panel.repaint();
}
#Override
public void mousePressed(MouseEvent e) {
if (e.getSource() == View.panel && currentTool == "pencil") {
g = View.panel.getGraphics();
if (colorChanged == false)
g.setColor(defaultColor);
else
g.setColor(drawColor);
g.fillOval(e.getX() - 15, e.getY() - 20, 30, 30);
System.out.println("Test");
mouseDragged(e);
}
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
for (int i = 0; i < buttonLabels.length; i++) {
buttonLabels[i].setOpaque(true);
if (e.getSource() == buttonLabels[i]) {
buttonLabels[i].setBackground(Color.GRAY);
}
}
}
#Override
public void mouseExited(MouseEvent e) {
for (int i = 0; i < buttonLabels.length; i++) {
if (e.getSource() == buttonLabels[i] && buttonLabels[i].getBackground() == Color.GRAY)
buttonLabels[i].setBackground(new JButton().getBackground());
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (e.getSource() == View.panel && currentTool == "pencil") {
g = View.panel.getGraphics();
if (colorChanged == false)
g.setColor(defaultColor);
else
g.setColor(drawColor);
g.fillOval(e.getX() - 15, e.getY() - 20, 30, 30);
System.out.println("Test");
}
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
private void setLabelVisibility(JLabel[] labelArray) {
for (int i = 0; i < labelArray.length; i++)
labelArray[i].setOpaque(true);
}
public static void setColor(Color c) {
colorChanged = true;
drawColor = c;
}
public void setupColorChangeDialogAction(JSlider r, JSlider g, JSlider b, JButton confirmBtn, JPanel colPreview) {
r.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
colPreview.setBackground(new Color(r.getValue(), g.getValue(), b.getValue()));
}
});
g.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
colPreview.setBackground(new Color(r.getValue(), g.getValue(), b.getValue()));
}
});
b.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
colPreview.setBackground(new Color(r.getValue(), g.getValue(), b.getValue()));
}
});
confirmBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
colPreview.setBackground(new Color(r.getValue(), g.getValue(), b.getValue()));
Controller.setColor(new Color(r.getValue(), g.getValue(), b.getValue()));
dispose();
}
});
}
public void setupPicImportMenuAction(JMenuItem picImportButton, JPanel panel, JLabel imgLbl) {
picImportButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc = new JFileChooser();
FileNameExtensionFilter pngOnly = new FileNameExtensionFilter(".png", "png");
FileNameExtensionFilter jpegOnly = new FileNameExtensionFilter(".jpg", "jpg");
jfc.addChoosableFileFilter(pngOnly);
jfc.addChoosableFileFilter(jpegOnly);
jfc.setAcceptAllFileFilterUsed(false);
int response = jfc.showOpenDialog(null);
if (response == JFileChooser.APPROVE_OPTION) {
try {
BufferedImage ii = ImageIO.read(new FileInputStream(jfc.getSelectedFile().getAbsolutePath()));
addImageToCanvas(panel, ii, imgLbl);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(jfc.getSelectedFile().getAbsolutePath());
}
}
});
}
protected void addImageToCanvas(JPanel panel, BufferedImage bi, JLabel label) {
label = new JLabel(new ImageIcon(bi));
imgLabel = label;
panel.add(label);
panel.revalidate();
label.setOpaque(true);
}
private void changeCursor(JPanel panel, JLabel newCursorImageLabel, URL iconURL) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
image = toolkit.getImage(iconURL);
System.out.println("\ninside changeCursor " + iconURL.toString());
panel.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "img"));
}
public void getClickedComponentColor() {
}
private class drag {
}
private class drop {
}
}
Model.java
public class Model {
}
I have also provided a zip file containing the entire project. The reason for providing this zip file is because my code requires the images that are located in a folder inside the src folder.
If anyone could help me with the issue regarding the mouse going behind the part of screen that has been drawn on that would be much appreciated
I also believe the cursor is on top but black on black.
Therefore I see two ways out of this:
Surround your shape with a thin line of white pixels so you can see the cursor regardless of a dark or light background
configure your cursor not to be black/transparent on whatever.Instead make the black pixels just 'invert' the background. I guess this is an XOR operation instead of an overwrite

key listener not working for some reason

i made this code that when you start it it's suposed to show you an image and then change it between other two images when you press the left or right key, but for some reason it isn't reading the input from the keyboard, i tryed to use a mouseListener and it worked, this is the code:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Implementary extends JFrame
{
private static final long serialVersionUID = 1L;
public Dimension d;
public static ImageIcon Im = new ImageIcon(Implementary.class.getResource("death.png"));
public static ImageIcon Imc = new ImageIcon(Implementary.class.getResource("right.png"));
public static ImageIcon I = new ImageIcon(Implementary.class.getResource("left.png"));
public static Image Img = Im.getImage();
public static int x = 10;
public static int y = 10;
public Implementary()
{
super("hue");
int x1 = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
int y1 = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
d = new Dimension(x1, y1 - 45);
this.setSize(d);
this.setLocationRelativeTo(null);
Panel p = new Panel();
p.addKeyListener(new KeyListener()
{
#Override
public void keyTyped(KeyEvent e)
{
keyPressed(e);
}
#Override
public void keyPressed(KeyEvent e)
{
int k = e.getKeyCode();
if (k == KeyEvent.VK_LEFT)
{
Img = I.getImage();
repaint();
System.out.println(3);
}
else
{
Img = Imc.getImage();
repaint();
System.out.println(2);
}
System.out.println(1);
}
#Override
public void keyReleased(KeyEvent e)
{
keyPressed(e);
}
});
this.add(p);
}
static class Panel extends JPanel
{
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.cyan);
g.drawImage(Img, x, y, null);
}
}
}
and this is the main class:
public class Yo
{
public static void main(String args[])
{
Implementary imp = new Implementary();
imp.setVisible(true);
}
}
Adding the KeyListener to the whole JFrame could do the trick.
As your JPanel cannot be selected/focused it doesn't receive keystrokes.
Changing
p.addKeyListener(new KeyListener()
to
this.addKeyListener(new KeyListener()
works for me.

Java - drawing image with Timer

I'm creating an animation that looks like this.
I'd like the swirly icon on the left (which is an ImageIcon) to display for 3 seconds and disappear. However, the swirly icon does not disappear.
Here's my code.
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame f = new JFrame("random title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
public int x;
public int y;
public int remoteControllerX = 473;
public int remoteControllerY = 340;
public int buttonX = 166;
public int buttonY = 208;
Image img;
Image remoteController;
ImageIcon button = new ImageIcon("graphics/button.gif");
Component buttonTrigger = this;
public MyPanel() {
try {
img = ImageIO.read(new File("graphics/close_0.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
try {
remoteController = ImageIO.read(new File("graphics/pilot.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
setBorder(BorderFactory.createLineBorder(Color.black));
new Timer(3000, paintTimer).start();
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
// Here goes action on background, which is unrelated to this example.
}
});
}
public Dimension getPreferredSize() {
return new Dimension(1048, 484);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
g.drawImage(remoteController, remoteControllerX, remoteControllerY, null);
Toolkit.getDefaultToolkit().sync();
button.paintIcon(buttonTrigger, g, buttonX, buttonY);
}
Action paintTimer = new AbstractAction() {
private static final long serialVersionUID = -2121714427110679013L;
public void actionPerformed(ActionEvent e) {
buttonTrigger = null;
repaint();
}
};
}
You'll also need these 3 images for the code to run:
http://ajks.pl/graveyard/close_0.jpg
http://ajks.pl/graveyard/pilot.png
http://ajks.pl/graveyard/button.gif
They are placed in a graphics folder under the main Java project.
I added a boolean to determine whether or not to paint the swirly image icon.
Here's the corrected code.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame f = new JFrame("random title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
public boolean paintButton = true;
public int x;
public int y;
public int remoteControllerX = 473;
public int remoteControllerY = 340;
public int buttonX = 166;
public int buttonY = 208;
Image img;
Image remoteController;
ImageIcon button = new ImageIcon(
"graphics/button.gif");
Component buttonTrigger = this;
public MyPanel() {
try {
img = ImageIO.read(new File("graphics/close_0.jpg"));
remoteController = ImageIO.read(new File("graphics/pilot.png"));
} catch (IOException e) {
e.printStackTrace();
}
setBorder(BorderFactory.createLineBorder(Color.black));
new Timer(3000, paintTimer).start();
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
// Here goes action on background, which is unrelated to this
// example.
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1048, 484);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
g.drawImage(remoteController, remoteControllerX, remoteControllerY,
null);
Toolkit.getDefaultToolkit().sync();
if (paintButton) {
button.paintIcon(buttonTrigger, g, buttonX, buttonY);
}
}
Action paintTimer = new AbstractAction() {
private static final long serialVersionUID = -2121714427110679013L;
#Override
public void actionPerformed(ActionEvent e) {
paintButton = false;
repaint();
}
};
}

paintComponent () never executes on a JFrame

import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.*;
import java.util.*;
public class test1 extends JFrame implements MouseListener {
private JPanel JP = new JPanel();
public test1() {
JP.setBorder(BorderFactory.createLineBorder(Color.black));
JP.addMouseListener(this);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.add(JP);
this.pack();
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
test1 frame = new test1();
frame.setSize(400,400);
frame.setVisible(true);
}
});
}
public void mouseClicked(MouseEvent e) {
//drawCircle(e.getX(), e.getY());
//repaint();
ballball ball;
ball = new ballball();
//ball.paintComponent(Graphics g);
System.out.println("ballball");
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
//this.mouseX=e.getX();
//this.mouseY=e.getY();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
}
class ballball extends test1 implements Runnable {
private int squareX = 50;
private int squareY = 50;
private int squareW = 100;
private int squareH = 100;
public boolean draw;
private Vector<Object> v = new Vector<Object>();
public ballball() {
/*addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
draw = true;
//Thread thread1 = new Thread(this.moveSquare(50, 50));
repaint();
//moveSquare(e.getX(),e.getY());
}
});*/
/*addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
moveSquare(e.getX(),e.getY());
}
});*/
System.out.println("ball created");
this.repaint();
}
public void run() {
}
private void moveSquare(int x, int y) {
int OFFSET = 1;
if ((squareX!=x) || (squareY!=y)) {
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
squareX=x;
squareY=y;
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
}
}
public void paint(Graphics g) {
g.drawString("abcasdfasffasfas", 10, 10);
}
//#Override
public void paintComponent(Graphics g) {
//if (draw) {
// existing code
System.out.println("paint");
//super.paintComponent(g);
//g.drawString("This is my custom Panel!",10,20);
//g.setColor(Color.RED);
//g.fillRect(squareX,squareY,squareW,squareH);
//g.setColor(Color.BLACK);
//g.drawRect(squareX,squareY,squareW,squareH);
Shape circle = new Ellipse2D.Float(squareX,squareY,100f,100f);
Graphics2D ga = (Graphics2D)g;
ga.draw(circle);
//}
}
}
The aim of the program is to click to create the circle, the ballball class extends the test1, when test1 detect the mouse click, the ballball object created. But the paint/paintComponent method is never be executed. In my program structure, is it possible to paint the circle to the super class JPanel?
JFrame is not a JComponent, it doesn't have a paintComponent method you can override. Instead you could extend a JPanel and add it to the frame.

Change colors for JProgressBar with Nimbus?

does anyone know how to change the colors for JProgressBar when you use Nimbus LookAndFeel?
I have overridden the whole nimbusOrange-Default Value, which change all ProgressBar-Colors and any other nimbusOrange. (InternalFrame - minimize Button)
here with nimbusBase (blue)
UIDefaults defaults = UIManager.getLookAndFeelDefaults();
defaults.put("nimbusOrange",defaults.get("nimbusBase"));
Better is to write a own Painter and set this to the UIManager via
UIManager.put("ProgressBar[Enabled].backgroundPainter", myPainter);
If You want to change the Color for only a single ProgressBar instance, you can use Per-component customization
progress = new JProgressBar();
UIDefaults defaults = new UIDefaults();
defaults.put("ProgressBar[Enabled].backgroundPainter", new MyPainter());
progress.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
progress.putClientProperty("Nimbus.Overrides", defaults);
an example of MyPainter can be as following:
class MyPainter implements Painter<JProgressBar> {
private final Color color;
public MyPainter(Color c1) {
this.color = c1;
}
#Override
public void paint(Graphics2D gd, JProgressBar t, int width, int height) {
gd.setColor(color);
gd.fillRect(0, 0, width, height);
}
}
but my compiler or IDE (eclipse) says that it doesn't know the Painter.
is there anybody to help me!
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class JProgressBarDemo extends JFrame {
protected int minValue = 0;
protected int maxValue = 100;
protected int counter = 0;
protected JProgressBar progressBar;
public JProgressBarDemo() {
super("JProgressBar Demo");
setSize(300, 100);
UIManager.put("ProgressBar.background", Color.BLACK); //colour of the background
UIManager.put("ProgressBar.foreground", Color.RED); //colour of progress bar
UIManager.put("ProgressBar.selectionBackground",Color.YELLOW); //colour of percentage counter on black background
UIManager.put("ProgressBar.selectionForeground",Color.BLUE); //colour of precentage counter on red background
progressBar = new JProgressBar();
progressBar.setMinimum(minValue);
progressBar.setMaximum(maxValue);
progressBar.setStringPainted(true);
JButton start = new JButton("Start");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread runner = new Thread() {
public void run() {
counter = minValue;
while (counter <= maxValue) {
Runnable runme = new Runnable() {
public void run() {
progressBar.setValue(counter);
}
};
SwingUtilities.invokeLater(runme);
counter++;
try {
Thread.sleep(100);
} catch (Exception ex) {
}
}
}
};
runner.start();
}
});
getContentPane().add(progressBar, BorderLayout.CENTER);
getContentPane().add(start, BorderLayout.WEST);
WindowListener wndCloser = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
}
public static void main(String[] args) {
new JProgressBarDemo();
}
}

Categories

Resources