Add a background to a JFrame - java

I want to add a background to my JFrame, but I can't get it done.
I have searched on the internet to find to some tutorials on it.
I am still a newbie and I want to learn these things.
This is what I have so far.
package gui;
import java.awt.Desktop;
public class Gui extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JLabel BackgroundLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Gui frame = new Gui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Gui() {
setTitle("Exile Launcher");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1000, 563);
contentPane = new JPanel();
contentPane.setBorder(null);
setContentPane(contentPane);
contentPane.setLayout(null);
BufferedImage BackgroundImage = null;
try {
BackgroundImage = ImageIO.read(this.getClass().getResource("/Images/Background.jpg"));
} catch (IOException ex) {
}
JLabel BackgroundLabel = new JLabel(new ImageIcon(BackgroundImage));
add(BackgroundLabel);
JButton HomeButton = new JButton("Home");
HomeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Desktop.getDesktop().browse(new URL("http://www.google.nl").toURI());
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
HomeButton.setBounds(10, 9, 50, 50);
contentPane.add(HomeButton);
JButton ForumButton = new JButton("Vote");
ForumButton.setBounds(10, 70, 50, 50);
contentPane.add(ForumButton);
JButton VoteButton = new JButton("New button");
VoteButton.setBounds(10, 131, 50, 50);
contentPane.add(VoteButton);
}
}
But I get this error:
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1388)
at gui.Gui.<init>(Gui.java:59)
at gui.Gui$1.run(Gui.java:36)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:312)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:733)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:703)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

UPDATE
I've got it running. First off your using null layout but not specifying the aspects you need to be focusing on. You don't actually create your background image when you just do "add(backgroundLabel);" you need to run backgroundLabel.setBounds(new Rectangle(int x, int y, width, hight); I'm going to give you the entire code. Make sure you have the file path reset to what you need.
Just drop it in, set your path and it should run. You will need to make sure the class name matches whatever your expecting to have but here you go:
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Gui extends JFrame {
private static final long serialVersionUID = 1L;
private final JPanel contentPane;
private JLabel BackgroundLabel;
Image background;
/**
* Launch the application.
*/
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
final Gui frame = new Gui();
frame.setVisible(true);
} catch (final Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Gui() {
this.setTitle("Exile Launcher");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100, 100, 1000, 563);
this.contentPane = new JPanel();
this.contentPane.setBorder(null);
this.setContentPane(this.contentPane);
this.contentPane.setLayout(null);
try {
this.background = ImageIO.read(new File("src/Images/Background.jpg"));
} catch (final IOException e) {
e.printStackTrace();
}
final JLabel backgroundLabel = new JLabel(new ImageIcon(this.background));
backgroundLabel.setBounds(new Rectangle(0, 0, 1000, 563));
this.add(backgroundLabel);
final JButton HomeButton = new JButton("Home");
HomeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
try {
Desktop.getDesktop().browse(new URL("http://www.google.nl").toURI());
} catch (final MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (final IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (final URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
HomeButton.setBounds(10, 9, 50, 50);
this.contentPane.add(HomeButton);
final JButton ForumButton = new JButton("Vote");
ForumButton.setBounds(10, 70, 50, 50);
this.contentPane.add(ForumButton);
final JButton VoteButton = new JButton("New button");
VoteButton.setBounds(10, 131, 50, 50);
this.contentPane.add(VoteButton);
}
// Final Piece to add an image to the jpanel
public void paintComponent(final Graphics pic) {
this.paintComponent(pic);
pic.drawImage(this.background, 0, 0, null);
}
}

Exception is Self Explanatory
BackgroundImage = ImageIO.read(this.getClass().getResource("/Images/Background.jpg"));
You are passing illegalArgument to read() method of ImageIO class
As JavaDoc syas
public static BufferedImage read(File input)
throws IOException
Returns a BufferedImage as the result of decoding a supplied File with
an ImageReader chosen automatically from among those currently
registered. The File is wrapped in an ImageInputStream. If no
registered ImageReader claims to be able to read the resulting stream,
null is returned.
You need to pass the File Class Object like this :
BackgroundImage = ImageIO.read(new File("C:\\Users\\Ruud\\workspace\\ExileLauncher\\Images\\Background.jpg"));
Note : You need to pass the absolute path of the file where it is located
A suggestion: if you are catching an Exception try to print it so that you may know the root cause.
try {
BackgroundImage = ImageIO.read(this.getClass().getResource("/Images/Background.jpg"));
} catch (IOException ex) {
ex.printStackTrace();// Here printing the stackTrace of Exception
}

Related

Simple Output Prints Twice to JTextArea in Java

I was wondering why the JTextArea prints the same line twice. Im using multithreading and im new to this concept. I was wondering if that's where the issue is. As of looking it over I tried seeing if any run methods were called twice to cause such a thing. There aren't any loops in the code either. The line that says "Prints twice?" in the GameThread class is where the issue starts. Thanks for help.
Main Menu Class
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.awt.event.ActionEvent;
public class MainMenu {
private JFrame menu;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainMenu window = new MainMenu();
window.menu.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws IOException
*/
public MainMenu() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws IOException
*/
private void initialize() throws IOException {
menu = new JFrame();
menu.getContentPane().setBackground(Color.BLACK);
menu.setTitle("Zombie Game");
menu.setBounds(100, 100, 574, 374);
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.getContentPane().setLayout(null);
JButton btnPlay = new JButton("Play");
// button action on click
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
GameScreen enterGame = new GameScreen();
menu.setVisible(false);
enterGame.run();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
JLabel lblNewLabel = new JLabel("Zombie Survival");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 40));
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBounds(118, 34, 381, 73);
menu.getContentPane().add(lblNewLabel);
btnPlay.setBackground(Color.WHITE);
btnPlay.setForeground(Color.RED);
btnPlay.setFont(new Font("Tahoma", Font.BOLD, 17));
btnPlay.setToolTipText("Click to begin.");
btnPlay.setBounds(225, 190, 118, 54);
menu.getContentPane().add(btnPlay);
}
}
Game Board
import java.awt.EventQueue;
import java.io.PrintStream;
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JTextArea;
import java.awt.Font;
import javax.swing.JScrollPane;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class GameScreen {
private JFrame gameFrm;
/**
* Launch the application.
*/
public void run() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GameScreen window = new GameScreen();
window.gameFrm.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #throws InterruptedException
*/
public GameScreen() throws InterruptedException {
initialize();
}
/**
* Initialize the contents of the frame.
* #throws InterruptedException
*/
private void initialize() throws InterruptedException {
gameFrm = new JFrame();
gameFrm.getContentPane().setBackground(Color.BLACK);
gameFrm.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 478, 718, 134);
gameFrm.getContentPane().add(scrollPane);
JTextArea displayTextArea = new JTextArea();
displayTextArea.setLineWrap(true);
displayTextArea.setWrapStyleWord(true);
displayTextArea.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
}
}
});
scrollPane.setViewportView(displayTextArea);
displayTextArea.setFont(new Font("Monospaced", Font.PLAIN, 18));
displayTextArea.setForeground(Color.WHITE);
displayTextArea.setBackground(Color.BLACK);
PrintStream printStream = new PrintStream(new CustomOutputStream(displayTextArea));
System.setOut(printStream);
JLabel forestPicture = new JLabel("New label");
forestPicture.setIcon(new ImageIcon("C:\\Users\\fstal\\Documents\\Java Programs\\UpdatedZombieGame\\src\\gameForest.jpg"));
forestPicture.setBounds(0, 0, 738, 622);
gameFrm.getContentPane().add(forestPicture);
gameFrm.setBackground(Color.WHITE);
gameFrm.setTitle("Zombie Game");
gameFrm.setBounds(100, 100, 752, 659);
gameFrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Game work
GameThread gThread = new GameThread();
gThread.start();
}
}
Thread Class
public class GameThread extends Thread {
static String [] zombies = {"Zombie", "Fast Zombie", "Big Zombie", "Crawler"};
static String [] bag = {"Assault Rifle", "SMG", "Shotgun", "Sniper"};
static int [] zHealth = {100, 90, 200, 50};
static int [] damage = {90, 80, 100, 200};
static int playerHealth = 50;
public void run() {
try {
System.out.println("Zombies are coming!");
//Thread.sleep(2000);
System.out.println("Prints twice?");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
CustomOutputStream Class for TextArea
import java.io.IOException;
import java.io.OutputStream;
import javax.swing.JTextArea;
public class CustomOutputStream extends OutputStream {
private JTextArea displayTextArea;
CustomOutputStream(JTextArea textArea) {
this.displayTextArea = textArea;
}
#Override
public void write(int b) throws IOException {
// redirects data to the text area
displayTextArea.append(String.valueOf((char)b));
// scrolls the text area to the end of data
displayTextArea.setCaretPosition(displayTextArea.getDocument().getLength());
}
}
You're creating two instance of the GameScreen, so your output get's printed twice
When you perform...
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
GameScreen enterGame = new GameScreen();
menu.setVisible(false);
enterGame.run();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
It calls the GameScreen constructor, which calls initialize()
/**
* Create the application.
*
* #throws InterruptedException
*/
public GameScreen() throws InterruptedException {
initialize();
}
And when you call run, it does it again...
/**
* Launch the application.
*/
public void run() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GameScreen window = new GameScreen();
window.gameFrm.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
You really don't need to do this again in run.
Now that we've discussed that problem, you have a number of other issues.
Firstly, Swing is NOT thread safe and you should never modify the UI (or anything the UI relies on) from outside the context of the Event Dispatching Thread.
See Concurrency in Swing for some more details (and possible solutions)
Second, null layouts are generally a bad idea - it made a mess of your UI on my PC. You should really take the time to learn how to use the various layout managers available in the API - see Laying Out Components Within a Container

java catch process time real time progress bar

new Scanner(new URL("SOME_URL.txt").openStream(), "UTF-8").useDelimiter("\\A").next();
Using this ^ I get the data from a .txt-File which I save in a String.
For my progress bar, I wondered if it would be possible for jobs like that (or in general for methods etc.) to count (or sth. like that) the time it needed to be finished. So that I can show in real time process time in my bar.
Is this somehow possible?
EDIT:
package app.gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.net.URL;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.commons.io.IOUtils;
public class Updater {
private JFrame frame;
private static String rawG;
private static String versI;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
rawG = new Scanner(new URL("SOME_URL.txt").openStream(), "UTF-8").useDelimiter("\\A").next();
versI = IOUtils.toString(getClass().getClassLoader().getResourceAsStream("version.txt"));
} catch (Exception e) {
System.out.println("error class Updater try/catch raw github");
}
if (Integer.parseInt(rawG.split("\\.")[0]) < Integer.parseInt(versI.split("\\.")[0])) {
System.out.println("Version check failure, update needed");
try {
Updater window = new Updater();
window.frame.setVisible(true);
} catch (Exception e) {
System.out.println("error class Updater try/catch initialize frame");
}
} else {
System.out.println("Version check correct, no update needed");
}
}
});
}
public Updater() {
initialize();
}
private void initialize() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.SOUTH);
panel.setLayout(new BorderLayout(0, 0));
JProgressBar progressBar = new JProgressBar();
progressBar.setStringPainted(true);
panel.add(progressBar, BorderLayout.NORTH);
}
}
Is it possible? Yes. Is it possible when using Scanner.next() to read the contents of the URL? No.
You will need to read the bytes yourself, and count them:
URL url = new URL("SOME_URL.txt");
URLConnection conn = url.openConnection();
ByteBuffer buffer = ByteBuffer.allocate(conn.getContentLength());
EventQueue.invokeLater(() -> progressBar.setMaximum(buffer.limit()));
EventQueue.invokeLater(() -> progressBar.setValue(0));
try (ReadableByteChannel channel = Channels.newChannel(conn.getInputStream())) {
while (channel.read(buffer) >= 0) {
EventQueue.invokeLater(() -> progressBar.setValue(buffer.position()));
}
}
buffer.flip();
String rawG = StandardCharsets.UTF_8.decode(buffer).toString();

How do open a internal frame only once

The following code opens a JInternalFrame when a button is clicked. But I want this window to be opened once, so if the user clicks that button again it will not open another frame instead it would bring to the front the window whether it is iconified, behind another window, etc. I have tried a couple of ways mainly using a counter, but the problems is once the frame is closed it doesn't open it again either. Is there another easy way to do this, cause I am not able to make it work properly. Thanks in advance.
Below is the code I am working on:
public class About implements ActionListener{
private int openFrameCount;
private JDesktopPane desk;
private JTextArea Tarea;
private JScrollPane scroll;
private BufferedReader in ;
int count =0;
MyInternalFrame frame;
public About(JDesktopPane desktop) {
// TODO Auto-generated constructor stub
desk = desktop;
System.out.println(count);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
count += 1;
if(count == 1){
frame = new MyInternalFrame("SAD Imaging");
count +=1;
try {
in = new BufferedReader(new FileReader("SADInfo.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line;
String file = "";
try {
while((line = in.readLine()) != null)
{
System.out.println(line);
file += line;
file +="\n";
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Tarea = new JTextArea();
//System.out.println(file);
Tarea.setText(file);
Font f = new Font("TimesNewRoman", Font.ROMAN_BASELINE, 16);
Tarea.setFont(f);
Tarea.setBackground(Color.white);
Tarea.setAlignmentX(SwingConstants.CENTER);
Tarea.setEditable(false);
JPanel panel = new JPanel();
panel.add(Tarea);
panel.setBackground(Color.white);
//scroll = new JScrollPane(Tarea);
scroll = new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
frame.add(scroll);
frame.setVisible(true);
desk.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
else if(count > 1){
try {
//frame.setIcon(true);
frame.setMaximum(true);
frame.toFront();
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Basically, you just need to check to see if the frame is null or not. If it is, you create an instance, if it's not, you bring it to the front, for example
#Override
public void actionPerformed(ActionEvent arg0) {
if (frame == null || (frame.getParent() == null && !frame.isIconifiable())) {
// Your exitsing code
} else {
frame.setIcon(false);
frame.setSelected(true);
frame.moveToFront();
}
You can also use an InteralFrameListener to the frame so you can detect when the frame is closed, so you null the internal reference, for example...
frame.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e) {
frame = null;
}
});
Updated with runnable example
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestInternalFrame {
public static void main(String[] args) {
new TestInternalFrame();
}
private JInternalFrame imageFrame;
private JDesktopPane desktop;
public TestInternalFrame() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JMenu fileMenu = new JMenu("File");
JMenuItem newMenu = fileMenu.add("Show...");
newMenu.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (imageFrame == null || imageFrame.isClosed()) {
imageFrame = new JInternalFrame("Image");
imageFrame.setIconifiable(true);
imageFrame.setMaximizable(true);
imageFrame.setClosable(true);
imageFrame.setResizable(true);
JLabel label = new JLabel(new ImageIcon("..."));
imageFrame.add(label);
imageFrame.pack();
desktop.add(imageFrame);
imageFrame.setLocation(0, 0);
imageFrame.setVisible(true);
}
try {
imageFrame.setIcon(false);
imageFrame.setSelected(true);
} catch (PropertyVetoException ex) {
ex.printStackTrace();
}
imageFrame.moveToFront();
}
});
desktop = new JDesktopPane();
JMenuBar mb = new JMenuBar();
mb.add(fileMenu);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(mb);
frame.add(desktop);
frame.setSize(1200, 900);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Captured webcam image not refreshing and max size too big to show

I am having some problems with my program. I have a GUI that shows a live image from a webcam (using [jvacv][1]) in one side, and the captured image in the other. To capture the image, I have a button. One problem is that the captured image is refreshing only if I close and open the program again. The other is that I want to capture a 1080p image from webcam, but live image at 640x480.
Here is the code:
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.FrameGrabber.Exception;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
public class Final
{
private VideoPanel videoPanel = new VideoPanel();
private ImagePanel imagePanel = new ImagePanel();
private JButton jbtCapture = new JButton("Captura");
private JRadioButton jbtAutoCap = new JRadioButton("Captura Automatica");
private FrameGrabber vision;
private BufferedImage image;
private IplImage gimage;
public class VideoPanel extends JPanel
{
public VideoPanel()
{
vision = new OpenCVFrameGrabber(0);
try
{
vision.start();
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
try {
image = vision.grab().getBufferedImage();
if (image != null)
{
g.drawImage(image, 0, 0, 640, 480, null);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
}
}
class ImagePanel extends JPanel
{
private BufferedImage image;
public ImagePanel()
{
try {
image = ImageIO.read(new File("image001.bmp"));
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(image != null)
{
g.drawImage(image,5,0,640,480, null);
}
}
}
private void displayGUI()
{
JFrame janela = new JFrame();
JPanel jpButton = new JPanel();
jpButton.setLayout(null);
jbtCapture.setBounds(145,0,110,30);
jpButton.add(jbtCapture);
jbtAutoCap.setBounds(0, 5, 140, 23);
jpButton.add(jbtAutoCap);
janela.setLayout(null);
videoPanel.setBounds(5, 5, 640, 480);
janela.add(videoPanel);
imagePanel.setBounds(705,5,640,480);
janela.add(imagePanel);
jpButton.setBounds(5, 500, 670, 40);
janela.add(jpButton);
janela.setSize(1366,730);
janela.setVisible(true);
jbtCapture.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try {
gimage = vision.grab();
cvSaveImage("image001.bmp", gimage);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
);
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
// TODO Auto-generated method stub
new Final().displayGUI();
}
});
}
}

Problems with a SwingWorker

I'm trying to get a SwingWorker to work.
I've the following code at the moment:
public class ImageWorker extends SwingWorker<Void, Void> implements KeyListener
{
private JLabel imageLabel;
private ImageIcon basicImage;
private ImageIcon whiteImage;
public static void main(String[] args)
{
new ImageWorker();
}
public ImageWorker()
{
final JFrame frame = new JFrame();
imageLabel = new JLabel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.getContentPane().add(imageLabel);
frame.setVisible(true);
try
{
basicImage = new ImageIcon(ImageIO.read(new File("src\\img\\basis1.jpg")).getScaledInstance(1024, 768, Image.SCALE_SMOOTH));
whiteImage = new ImageIcon(ImageIO.read(new File("src\\img\\wit.jpg")).getScaledInstance(1024, 768, Image.SCALE_SMOOTH));
}
catch(IOException ex)
{
ex.getMessage();
}
this.execute();
}
#Override
protected Void doInBackground()
{
try
{
while (true)
{
displayImage(basicImage);
Thread.sleep(1000L);
if(isCancelled())
return null;
}
}
catch(InterruptedException e)
{
e.getMessage();
}
return null;
}
private void displayImage(final Icon image)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
imageLabel.setIcon(image);
}
});
}
I was expecting the images to appear in the JLabel, but I only see the JFrame popping up. The files are loaded correctly Ive tested that in another setup.
Any pointers?
Here is an example using a Timer rather than using the SwingWorker which really isn't appropriate to your situation. Note that it's not too different from your existing code.
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class ImageWorker implements KeyListener
{
private JLabel imageLabel;
private ImageIcon basicImage;
private ImageIcon whiteImage;
private boolean isBasic = true;
private int delay = 1000; //milliseconds
private Timer timer;
public static void main(String[] args)
{
new ImageWorker();
}
public ImageWorker()
{
final JFrame frame = new JFrame();
imageLabel = new JLabel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.getContentPane().add(imageLabel);
frame.setVisible(true);
try
{
basicImage = new ImageIcon(ImageIO.read(new File("src\\img\\basis1.jpg")).getScaledInstance(1024, 768, Image.SCALE_SMOOTH));
whiteImage = new ImageIcon(ImageIO.read(new File("src\\img\\wit.jpg")).getScaledInstance(1024, 768, Image.SCALE_SMOOTH));
}
catch (IOException ex)
{
ex.getMessage();
ex.printStackTrace();
}
frame.addKeyListener(this);
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(isBasic) {
//display basic image
imageLabel.setIcon(basicImage);
}
else {
//display white image
imageLabel.setIcon(whiteImage);
}
//toggle the flag
isBasic = !isBasic;
}
};
//use a timer instead of SwingWorker
timer = new Timer(delay, taskPerformer);
timer.start();
}
#Override
public void keyPressed(KeyEvent e)
{
//key pressed, we want to stop toggling so stop the timer
timer.stop();
//do whatever else you were doing to set the value for isCancelled();
}
#Override
public void keyReleased(KeyEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e)
{
// TODO Auto-generated method stub
}
}
A SwingWorker is not appropriate for your situation look into a Timer in the swing package. Here is a link to the API: http://download.oracle.com/javase/6/docs/api/javax/swing/Timer.html
You have the timer run and change an image every second since that is what you need.
Also, whenever you have exceptions, print out a stacktrace or the message at least. Otherwise you won't know if an exception occurs and is caught.

Categories