Frame refreshing issue - java

I am trying to create a panel with changing pictures.
This is my panel:
public class AdvertisementPanel extends JPanel {
private BufferedImage image;
private ArrayList<String> pictures;
private int index = 0;
public AdvertisementPanel(String... pics) {
pictures = new ArrayList<String>(Arrays.asList(pics));
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
new Runnable() {
#Override
public void run() {
changeImage();
}
}, 0, 5, TimeUnit.SECONDS);
}
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
}
private void changeImage() {
String name = pictures.get(index);
try {
File input = new File(name);
image = ImageIO.read(input);
index++;
index %= pictures.size();
} catch (IOException ie) {
Logger.getLogger().log(Level.SEVERE,
"No adds found in given path: " + name);
}
}
I have a frame that holds the panel, but no pictures are shown.
Tried to repaint periodically from the frame - caused some funny, yet unwanted results...
Any ideas why? What am I doing wrong? How should I refresh the frame's components?

you need to repaint each time you change the image.
Oh, and it should be done by the swing event handling thread:
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
new Runnable() {
#Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
changeImage();
repaint();
}
};
}
}, 0, 5, TimeUnit.SECONDS);
UPDATE To correct a few other issues
public class AdvertisementPanel extends JPanel {
private BufferedImage image;
private ArrayList<String> pictures;
private int index = 0;
public AdvertisementPanel(String... pics) {
pictures = new ArrayList<String>(Arrays.asList(pics));
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
new Runnable() {
#Override
public void run() {
changeImage();
}
}, 0, 5, TimeUnit.SECONDS);
}
private void changeImage() {
final BufferedImage img = nextImage();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
image = img;
repaint();
}
});
}
public void paint(Graphics g) {
if (image != null) {
g.drawImage(image, 0, 0, null);
}
}
private BufferedImage nextImage() {
String name = pictures.get(index);
try {
index++;
index %= pictures.size();
File input = new File(name);
return ImageIO.read(input);
} catch (IOException ie) {
Logger.getLogger("").log(Level.SEVERE,
"No adds found in given path: " + name);
return null;
}
}
}

Related

The constructor "public GUI()" is called twice, causing two similar windows to open

I am currently working on a test project using windows and servers. I have it working so far (doing what's supposed to be doing), but the only problem is that the constructor is being called twice, making the code to display two similar windows. Help!
Here is my code:
(you can ignore the mouse listener parts, I don't really think that's the problem).
public class RummyClient implements Runnable{
public GUI gui = new GUI();
public static Servidor servidor;
public static void main(String[] args) throws UnknownHostException, IOException {
servidor = new Servidor(25565, "localhost");
new Thread(new RummyClient()).start();
}
#Override
public void run() {
while(true) {
gui.repaint();
}
}
public class GUI extends JFrame {
public int clickedX = 0;
public int clickedY = 0;
public String stage = "";
public boolean start = false;
public GUI() {
setTitle("Rummy");
setSize(1280, 720);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
Board board = new Board();
setContentPane(board);
getContentPane().setPreferredSize(new Dimension(1280, 720));
Move move = new Move();
addMouseMotionListener(move);
Click click = new Click();
addMouseListener(click);
pack();
stage = "start";
System.out.println("created");
}
public class Board extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
Image board = ImageIO.read(new File("client/src/imgs/board.jpg")).getScaledInstance(1280, 720, java.awt.Image.SCALE_SMOOTH);
g.drawImage(board, 0, 0, this);
switch (stage) {
case "start":
Image playButtonNP = ImageIO.read(new File("client/src/imgs/play.png")).getScaledInstance(406, 220, java.awt.Image.SCALE_SMOOTH);
Image rummyTitle = ImageIO.read(new File("client/src/imgs/rummy.png")).getScaledInstance(526, 340, java.awt.Image.SCALE_SMOOTH);
g.drawImage(rummyTitle, 376, 0, this);
if (start){
g.drawImage(playButtonNP, 448, 360, this);
}
break;
}
} catch (Exception e) {
System.out.println("error!");
}
}
}
public class Move implements MouseMotionListener {
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
}
public class Click implements MouseListener{
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
clickedX = e.getX();
clickedY = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
clickedX = 0;
clickedY = 0;
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
public void start() {
this.start = true;
}
}
static class Servidor extends RummyClient{
Socket s;
PrintWriter out;
Scanner in;
public Servidor(int port, String ip) throws UnknownHostException, IOException {
this.s = new Socket(ip, port);
this.out = new PrintWriter(s.getOutputStream());
this.in = new Scanner(s.getInputStream());
Thread input = new Thread(new Input());
input.start();
}
public void send(String text) {
out.println(text);
out.flush();
}
class Input implements Runnable {
#Override
public void run() {
while(true) {
String incoming = in.nextLine();
switch (incoming) {
case "ready":
gui.start();
break;
}
}
}
}
}
}

Java animation:can't see anything

I am doing animation with Java and I'm using NetBeans. My applet has started but I don't see anything in the applet viewer? Can anybody see any problem with my code and this is my first programming course as U can see =)! Thanks for advance!!
Problem.1 Do animation with 10 gif pictures by using MediaTracker,addImage and thread.sleep.
(Code)
import java.applet.Applet;
import java.awt.*;
public class Animaatio extends Applet implements Runnable
{
Image images[] = null;
MediaTracker tracker = null;
Thread animaatio;
Graphics g;
#Override
public void init()
{
tracker = new MediaTracker(this);
images = new Image[10];
for (int i=0; i < 10; i++)
{
images[i] = getImage( getCodeBase(),"T" + (i+1) + ".gif");
tracker.addImage(images[i],0);
}
try{
tracker.waitForAll();
}catch (InterruptedException e){}
}
#Override
public void start() {
if (animaatio == null) {
animaatio = new Thread(this);
animaatio.start();
}
}
#Override
public void paint (Graphics g)
{
super.paint(g);
g.drawImage(images[10], 0, 0, this);
}
#Override
public void run(){
while(true){
repaint();
try{
Thread.sleep(1000);
}
catch (InterruptedException e) {}
}
}
}

Magic movement in game tile by tile

I have a 2D tile game and my hero can use magic(in this case fire), and the goal is to make the fireball move tile by tile until it finds either a wall or an enemy and to make the game stop while the fire is moving. I already have the fire moving and stopping if there is a wall or an enemy(and damaging the enemy). The problem is i can't seem to make the game show the fireball change from tile to tile, which means when i launch the fireball the game automatically shows me the fireball in its last position before collision, and then it disappears from the tiles. Anyone got any ideas as to what I am doing wrong or what i should do to make the game update the fire tile by tile?
(Btw i thought it might have something to do with my observer but I've tried thread.sleep and wait() and it isn't quite working, maybe I am doing it the wrong way).Thank you for your help and if you guys need any code just ask.
public class ImageMatrixGUI extends Observable {
private static final ImageMatrixGUI INSTANCE = new ImageMatrixGUI();
private final String IMAGE_DIR = "images";
private final int SQUARE_SIZE;
private final int N_SQUARES_WIDTH;
private final int N_SQUARES_HEIGHT;
private JFrame frame;
private JPanel panel;
private JPanel info;
private Map<String, ImageIcon> imageDB = new HashMap<String, ImageIcon>();
private List<ImageTile> images = new ArrayList<ImageTile>();
private List<ImageTile> statusImages = new ArrayList<ImageTile>();
private int lastKeyPressed;
private boolean keyPressed;
private ImageMatrixGUI() {
SQUARE_SIZE = 48;
N_SQUARES_WIDTH = 10;
N_SQUARES_HEIGHT = 10;
init();
}
public static ImageMatrixGUI getInstance() {
return INSTANCE;
}
public void setName(final String name) {
frame.setTitle(name);
}
private void init() {
frame = new JFrame();
panel = new RogueWindow();
info = new InfoWindow();
panel.setPreferredSize(new Dimension(N_SQUARES_WIDTH * SQUARE_SIZE, N_SQUARES_HEIGHT * SQUARE_SIZE));
info.setPreferredSize(new Dimension(N_SQUARES_WIDTH * SQUARE_SIZE, SQUARE_SIZE));
info.setBackground(Color.BLACK);
frame.add(panel);
frame.add(info, BorderLayout.NORTH);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initImages();
new KeyWatcher().start();
frame.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
lastKeyPressed = e.getKeyCode();
keyPressed = true;
releaseObserver();
}
});
}
synchronized void releaseObserver() {
notify();
}
synchronized void waitForKey() throws InterruptedException {
while (!keyPressed) {
wait();
}
setChanged();
notifyObservers(lastKeyPressed);
keyPressed = false;
}
private void initImages() {
File dir = new File(IMAGE_DIR);
for (File f : dir.listFiles()) {
assert (f.getName().lastIndexOf('.') != -1);
imageDB.put(f.getName().substring(0, f.getName().lastIndexOf('.')),
new ImageIcon(IMAGE_DIR + "/" + f.getName()));
}
}
public void go() {
frame.setVisible(true);
}
public void newImages(final List<ImageTile> newImages) {
synchronized (images) { // Added 16-Mar-2016
if (newImages == null)
return;
if (newImages.size() == 0)
return;
for (ImageTile i : newImages) {
if (!imageDB.containsKey(i.getName())) {
throw new IllegalArgumentException("No such image in DB " + i.getName());
}
}
images.addAll(newImages);
}
}
public void removeImage(final ImageTile image) {
synchronized (images) {
images.remove(image);
}
}
public void addImage(final ImageTile image) {
synchronized (images) {
images.add(image);
}
}
public void clearImages() {
synchronized (images) {
images.clear();
}
public void newStatusImages(final List<ImageTile> newImages) {
synchronized (statusImages) {
if (newImages == null)
return;
if (newImages.size() == 0)
return;
for (ImageTile i : newImages) {
if (!imageDB.containsKey(i.getName())) {
throw new IllegalArgumentException("No such image in DB " + i.getName());
}
}
statusImages.addAll(newImages);
}
}
public void removeStatusImage(final ImageTile image) {
synchronized (statusImages) {
statusImages.remove(image);
}
public void addStatusImage(final ImageTile image) {
synchronized (statusImages) {
statusImages.add(image);
}
}
public void clearStatus() {
synchronized (statusImages) {
statusImages.clear();
}
}
#SuppressWarnings("serial")
private class RogueWindow extends JPanel {
#Override
public void paintComponent(Graphics g) {
// System.out.println("Thread " + Thread.currentThread() + "
// repainting");
synchronized (images) {
for (ImageTile i : images) {
g.drawImage(imageDB.get(i.getName()).getImage(), i.getPosition().getX() * SQUARE_SIZE,
i.getPosition().getY() * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE, frame);
}
}
}
}
#SuppressWarnings("serial")
private class InfoWindow extends JPanel {
#Override
public void paintComponent(Graphics g) {
synchronized (statusImages) {
for (ImageTile i : statusImages)
g.drawImage(imageDB.get(i.getName()).getImage(), i.getPosition().getX() * SQUARE_SIZE, 0,
SQUARE_SIZE, SQUARE_SIZE, frame);
}
}
}
private class KeyWatcher extends Thread {
public void run() {
try {
while (true)
waitForKey();
} catch (InterruptedException e) {
}
}
}
public void update() {
frame.repaint();
}
public void dispose() {
images.clear();
statusImages.clear();
imageDB.clear();
frame.dispose();
}
public Dimension getGridDimension() {
return new Dimension(N_SQUARES_WIDTH, N_SQUARES_HEIGHT);
}
}

Repaint doesn't call paintcomponent

I'm trying to make a WebCam example in Java but it doesn't work. Repaint method for JPanel doesn't call paintComponent. When I call repaint anywhere, it doesn't update the image but the program still keeps running:
This is my example:
public class JFrameExample extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private CameraPanel cameraPanel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrameExample frame = new JFrameExample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public JFrameExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(300, 200, 900, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
cameraPanel = new CameraPanel();
cameraPanel.setBackground(Color.RED);
cameraPanel.setBounds(10, 52, 640, 480);
contentPane.add(cameraPanel);
JButton btnActivar = new JButton("Activar");
btnActivar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
startCamera();
}
});
btnActivar.setBounds(10, 11, 89, 23);
contentPane.add(btnActivar);
}
private void startCamera(){
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture eyeCamera = new VideoCapture(0);
if(eyeCamera.isOpened()){
while(true){
Mat frame = new Mat();
eyeCamera.read(frame);
cameraPanel.setimage(matToBufferedImage(frame));
cameraPanel.setSize(new Dimension(frame.width(),frame.height()));
contentPane.repaint();
cameraPanel.repaint();
this.repaint();
}
}
}
public static BufferedImage matToBufferedImage(Mat matrix) {
int cols = matrix.cols();
int rows = matrix.rows();
int elemSize = (int) matrix.elemSize();
byte[] data = new byte[cols * rows * elemSize];
int type;
matrix.get(0, 0, data);
switch (matrix.channels()) {
case 1:
type = BufferedImage.TYPE_BYTE_GRAY;
break;
case 3:
type = BufferedImage.TYPE_3BYTE_BGR;
// bgr to rgb
byte b;
for (int i = 0; i < data.length; i = i + 3) {
b = data[i];
data[i] = data[i + 2];
data[i + 2] = b;
}
break;
default:
return null;
}
BufferedImage image2 = new BufferedImage(cols, rows, type);
image2.getRaster().setDataElements(0, 0, cols, rows, data);
return image2;
}
}
CameraPanel
public class CameraPanel extends JPanel{
private static final long serialVersionUID = 1L;
private BufferedImage image;
public CameraPanel() {
super();
}
public BufferedImage getimage() {
return image;
}
public void setimage(BufferedImage newimage) {
image = newimage;
System.out.println("setImage method");
}
#Override
protected void paintComponent(Graphics grafics) {
System.out.println("paintComponent method");
super.paintComponent(grafics);
if(image != null)
grafics.drawImage(image, 10, 10, 50, 50, this);
}
}
I could not try because your app is not runnable. But maybe runnig while(true) {} part in a Thread can solve your problem.
Thread paintThread = new Thread(new Runnable(){
public void run() {
while(true){
Mat frame = new Mat();
eyeCamera.read(frame);
cameraPanel.setimage(matToBufferedImage(frame));
cameraPanel.setSize(new Dimension(frame.width(),frame.height()));
contentPane.repaint();
cameraPanel.repaint();
this.repaint();
}
}
}
paintThread.start();

How to Update Image in an Applet

How do i get an java applet to search an image from the specified path. I want to make a simple imageviewer applet which has 2 buttons NEXT,PREV . By clicking Next it should show next image and by clicking prev it should show the previous image.
i have written the following code .Please help me in writing the code for the updatenext() and updateprev() function.
public class pic extends Applet implements ActionListener
{
Button prev,next;
private static final String PREV="Previous";
private static final String NEXT="Next";
Image img;
public void init()
{
img=getImage(getCodeBase(),"image1.jpg");
prev = new Button();
prev.setLabel(PREV);
prev.setActionCommand(PREV);
prev.addActionListener(this);
add(prev);
next = new Button();
next.setLabel(NEXT);
next.setActionCommand(NEXT);
next.addActionListener(this);
add(next);
}
public void paint(Graphics g)
{
g.drawImage(img,0,0,600,700,this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals(NEXT))
updatenext();
else if(e.getActionCommand().equals(PREV))
updateprev();
}
void updatenext()
{
//updateImagehere
}
void updateprev()
{
//updateimage here
repaint();
}
}
A very simple example is this.
import java.applet.*;
import java.awt.*;
public class AppletImage extends Applet{
Image img;
MediaTracker tr;
public void paint(Graphics g) {
tr = new MediaTracker(this);
img = getImage(getCodeBase(), "demoimg.gif");
tr.addImage(img,0);
g.drawImage(img, 0, 0, this);
}
public static void main(String args[]){
AppletImage appletImage = new AppletImage();
appletImage.setVisible(true);
}
}
try this and ya u can take image according to your self.
If you want to get a list of the files in the location of your applet you can create a File object of the current directory with:
File currentDir = new File(getCodeBase().getPath());
Then to iterate over the files call:
for (File file : currentDir.listFiles()) {
// do something with the file
}
You will need to filter out directories and non image files, I would suggest you use a FileNameFilter as an argument when calling listFiles().
EDIT:
Here's an example of the solution you could use with this method:
public class pic extends Applet implements ActionListener
{
Button prev, next;
private static final String PREV = "Previous";
private static final String NEXT = "Next";
Image img;
private File[] imageFiles;
private int currentIndex = 0;
public void init()
{
File baseDir = new File(getCodeBase().getPath());
imageFiles = baseDir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
String image = ".*\\.(png|jpg|jpeg|gif)";
Pattern pattern = Pattern.compile(image);
Matcher matcher = pattern.matcher(name.toLowerCase());
return matcher.matches();
}
});
setImage();
prev = new Button();
prev.setLabel(PREV);
prev.setActionCommand(PREV);
prev.addActionListener(this);
add(prev);
next = new Button();
next.setLabel(NEXT);
next.setActionCommand(NEXT);
next.addActionListener(this);
add(next);
}
public void paint(Graphics g)
{
g.drawImage(img, 0, 0, 600, 700, this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals(NEXT))
updatenext();
else if (e.getActionCommand().equals(PREV))
updateprev();
}
private void setImage() {
img = getImage(getCodeBase(), imageFiles[currentIndex].getName());
}
void updatenext()
{
// needs circular increment
if (currentIndex == imageFiles.length - 1) {
currentIndex = 0;
} else {
currentIndex++;
}
setImage();
repaint();
}
void updateprev()
{
// needs circular decrement
if (currentIndex == 0) {
currentIndex = imageFiles.length-1;
} else {
currentIndex--;
}
setImage();
repaint();
}
}

Categories