I want to show the progress of my program process which using progress monitor in java. i've put this code below as progress monitor in my new frame.
package eksim.view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.ProgressMonitor;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
public class ProgBar extends javax.swing.JInternalFrame implements ActionListener {
static ProgressMonitor pbar;
static int counter = 0;
/**
* Creates new form ProgBar
*/
public ProgBar() {
initComponents();
}
public void ProgressMonitorExample() {
super("Progress Monitor Demo");
setSize(250, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pbar = new ProgressMonitor(null, "Monitoring Progress",
"Initializing . . .", 0, 100);
// Fire a timer every once in a while to update the progress.
Timer timer = new Timer(500, this);
timer.start();
setVisible(true);
}
public static void main(String args[]) {
UIManager.put("ProgressMonitor.progressText", "This is progress?");
UIManager.put("OptionPane.cancelButtonText", "Go Away");
ProgressMonitorExample();
}
public void actionPerformed(ActionEvent e) {
// Invoked by the timer every half second. Simply place
// the progress monitor update on the event queue.
SwingUtilities.invokeLater(new Update());
}
class Update implements Runnable {
public void run() {
if (pbar.isCanceled()) {
pbar.close();
System.exit(1);
}
pbar.setProgress(counter);
pbar.setNote("Operation is " + counter + "% complete");
counter += 2;
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jProgressBar1 = new javax.swing.JProgressBar();
setClosable(true);
setIconifiable(true);
setMaximizable(true);
setTitle("Progress Monitor");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(28, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(66, Short.MAX_VALUE)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48))
);
pack();
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JProgressBar jProgressBar1;
// End of variables declaration
}
But, it didn't show anything as it works. Could anyone help me? Thanks
Apart from a few compilation problems in your code (detailed below), it works fine here. The progress bar updates as expected here.
First, move the code from public void ProgressMonitorExample() to the constructor, and remove that method. The constructor should look like this:
public ProgBar() {
super("Progress Monitor Demo");
initComponents();
setSize(250, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pbar = new ProgressMonitor(null, "Monitoring Progress",
"Initializing . . .", 0, 100);
// Fire a timer every once in a while to update the progress.
Timer timer = new Timer(500, this);
timer.start();
setVisible(true);
}
Second, since public void ProgressMonitorExample() is now gone, properly create a new ProgBar object instead:
public static void main(String args[]) {
UIManager.put("ProgressMonitor.progressText", "This is progress?");
UIManager.put("OptionPane.cancelButtonText", "Go Away");
ProgBar pb = new ProgBar();
}
Related
I am trying to present a splash screen during application initialization in a new thread so that processing can continue in the main thread. The screen is presented but the thread does not stop when told to terminate by the main thread. I have tried using a volatile boolean flag and the interrupt() method, neither of which stops the thread.
Here's what I have so far:
Main thread
startScreen = new StartScreen("Loading Resume Builder");
Thread splashThread = new Thread(startScreen);
splashThread.start();
loadDB();
splashThread.interrupt();
new thread
public class StartScreen extends JFrame
implements Runnable {
private static volatile boolean exit;
/**
* Creates new form StartScreen
*
* #param status
* #throws java.io.IOException
*/
public StartScreen(String status) throws IOException {
initComponents();
setupFrame(status);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
imageLabel = new javax.swing.JLabel();
statusLabel = new javax.swing.JLabel();
setAlwaysOnTop(true);
setMaximumSize(new java.awt.Dimension(400, 300));
setMinimumSize(new java.awt.Dimension(400, 300));
setPreferredSize(new java.awt.Dimension(640, 371));
statusLabel.setName(""); // NOI18N
statusLabel.setOpaque(true);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(statusLabel)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(imageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 369, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(statusLabel)
.addGap(16, 16, 16))
);
imageLabel.getAccessibleContext().setAccessibleName("");
}// </editor-fold>
private void setupFrame(String status) throws IOException {
setUndecorated(true);
setLocationRelativeTo(null);
ImageIcon imageIcon = new ImageIcon("E:\\Users\\flash\\Documents\\"
+ "NetBeansProjects\\ResumeBuilder\\"
+ "career-g5c3a164de_640.jpg");
imageLabel.setIcon(imageIcon);
imageLabel.setOpaque(false);
imageLabel.setSize(new Dimension(395, 250));
this.getContentPane().add(imageLabel);
setStatus(status);
statusLabel.setLocation(new Point(10, 275));
this.add(statusLabel);
setVisible(true);
}
public void setStatus(String status) {
statusLabel.setText(status);
}
// Variables declaration - do not modify
private javax.swing.JLabel imageLabel;
private javax.swing.JLabel statusLabel;
// End of variables declaration
#Override
public synchronized void run() {
if (!Thread.currentThread().isInterrupted()) {
} else {
setVisible(false);
repaint();
}
}
public static void close() {
exit = true;
}
}
You might consider saving yourself writing code for splash screen by using the default Java splash screen parameter. Just add -splash:/somepathto/splash.jpg to your java command line and the splash screen will be presented at JVM startup.
Your application can cancel the default splash screen at an appropriate moment by inserting a call to:
/**
* Closes splash screen if JVM startup parameter used:
* JAVA.EXE -splash:"/somepath/splash.jpg" ...
*/
public static void closeSplash() {
SplashScreen ss = SplashScreen.getSplashScreen();
if (ss != null) {
ss.close();
}
}
If you don't cancel the splashscreen, it will linger in the background until JVM exits.
The post by DuncG is the solution I went with. It's clean and easy to implement.
I have a game that has a MainUI class, a GameClass and a SettingsClass. The game works fine except when I click "Restart" or "Help" which takes me to another JFrame and then returns back to the MainUI by a click of a button. But, when that happens, the MainUI class does not dispose of itself when it should. I believe it has to do with instantiating the MainUI class again when I leave and come back from settings but I'm but sure how to fix it.
This is the code I'm using to dispose of the MainUI frame and open a new JFrame:
private final JFrame mainFrame;
mainFrame.dispose(); //the mainFrame variable is passed in the constructor since it's trying to dispose of the MainUI
EndingPage endingPage = new EndingPage(); //open ending page
endingPage.setVisible(true);
This is an example of part of the code for one of the buttons in the settings class
restart.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
MainUI.started=false;
mainFrame.dispose();
TitlePage title = new TitlePage();
title.setVisible(true);
}
});
When one of those buttons are clicked, another JFrame is opened accordingly. To go back to the MainUI this is run:
this.dispose();
MainUI main = new MainUI();
main.setVisible(true);
For more clarification, the second code is run when the user clicks the settings button. Then, the last code is run to get back to the JFrame it already was at. When the user wins the first code is run. But the issue is sometimes the mainFrame.dispose(); in the first code does not work. Any help is appreciated! If you need to see other code please tell me! I'm stuck.
EDIT:
This is the MainUI (there is a timer because I want to delay before the action)
package stackoverflowcode;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class MainUI extends javax.swing.JFrame {
/**
* Creates new form MainUI
*/
public MainUI() {
initComponents();
GameClass game = new GameClass(this, end);
SettingsClass settings = new SettingsClass(restart, this);
Timer timer;
private javax.swing.JButton end;
private javax.swing.JButton restart;
ActionListener action = new ActionListener(){
#Override
public void actionPerformed(ActionEvent event)
{
game.openEnd();
}
};
timer= new Timer (1000,action);
timer.start();
settings.settings();
}
private void initComponents() {
restart = new javax.swing.JButton();
end = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
restart.setText("SETTINGS");
end.setText("END");
javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(151, 151, 151)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(end)
.addComponent(restart))
.addContainerGap(168, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(120, 120, 120)
.addComponent(restart)
.addGap(48, 48, 48)
.addComponent(end)
.addContainerGap(86, Short.MAX_VALUE))
);
pack();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainUI().setVisible(true);
}
});
}
}
SettingsClass
package stackoverflowcode;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SettingsClass {
JButton restart;
JFrame mainFrame;
public SettingsClass(JButton restart, JFrame mainFrame){
this.restart=restart;
this.mainFrame=mainFrame;
}
public void settings() {
restart.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
mainFrame.dispose();
TitlePage title = new TitlePage();
title.setVisible(true);
}
});
}
}
TitlePage
package stackoverflowcode;
public class TitlePage extends javax.swing.JFrame {
/**
* Creates new form TitlePage
*/
public TitlePage() {
initComponents();
private javax.swing.JButton Play;
}
private void initComponents() {
Play = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Play.setText("PLAY");
Play.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PlayActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(134, 134, 134)
.addComponent(Play)
.addContainerGap(209, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(129, 129, 129)
.addComponent(Play)
.addContainerGap(148, Short.MAX_VALUE))
);
pack();
}
private void PlayActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.dispose();
MainUI main = new MainUI();
main.setVisible(true);
}
public static void main(String args[]){
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TitlePage().setVisible(true);
}
});
}
}
GameClass
package stackoverflowcode;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GameClass {
private final JFrame mainFrame;
private final JButton endButton;
public GameClass(JFrame mainFrame, JButton endButton){
this.mainFrame=mainFrame;
this.endButton=endButton;
}
public void openEnd(){
endButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
mainFrame.dispose(); //the mainFrame variable is passed in the constructor since it's trying to dispose of the MainUI
TitlePage endingPage = new TitlePage(); //open title page
endingPage.setVisible(true);
}
});
}
}
I'm trying to make a game in Java, and I decided to use GIFs as animations in a JFrame. However, the program keeps showing past frames of the GIF, so the whole image looks like a mess.
This is what the GIF should look like in the program:
However, the GIF ends up looking like this (this is a screenshot of what appears on the JFrame):
And here is my code so far. I'm using NetBeans with Java 8.0.2.
package giftest;
public class MainWindow extends javax.swing.JFrame {
public MainWindow() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/giftest/Chespin2.gif"))); // NOI18N
jLabel1.setText("jLabel1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(jLabel1)
.addContainerGap(12, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(89, 89, 89)
.addComponent(jLabel1)
.addContainerGap(19, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
// End of Program
The effect can be reproduced with these lines of code:
import javax.swing.*;
import java.net.*;
public class AnimatedGifTest {
AnimatedGifTest() throws MalformedURLException {
URL url = new URL(
"https://i.stack.imgur.com/y9O4G.gif");
ImageIcon ii = new ImageIcon(url);
JOptionPane.showMessageDialog(null, ii);
}
public static void main(String[] args) {
Runnable r = () -> {
try {
new AnimatedGifTest();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
};
SwingUtilities.invokeLater(r);
}
}
I'm using Java Swing, and I'm using jLabels and putting the GIF as the icon. Is there a way to fix this issue in NetBeans on Java 8.0.2? Thanks in advance!
I am creating new Splash screen in Java (using Netbeans as my IDE).
But the problem is that after reaching 100% by progress bar it is automatically move to 2nd frame and exit the 1st frame which is showing the splash screen. But here 1st screen of splash screen is not exiting.
This is my code
public NewJFrame() {
initComponents();
try {
for (int i=0;i<=100;i++){
Thread.sleep(40);
jLabel1.setText(Integer.toString(i)+"%");
jProgressBar2.setValue(i);
if (i==100)
{
this.setVisible(false);
new NewJFrame1().setVisible(true);
}
}
} catch (Exception e) {
}
}
I once created a simple splash, not to fancy but for me it did the trick.
This is a copy paste from the entire class from netbeans, so you will need to change somethings.
This example you will get a splash with a image and a progress bar bellow.
import javax.swing.SwingUtilities;
public class Splash extends javax.swing.JWindow {
private static final long serialVersionUID = -6711792976773608816L;
/**
* Creates new form Splash
*/
public Splash() {
initComponents();
}
public void splashScreenInit() {
setLocationRelativeTo(null);
setProgressMax(100);
setVisible(true);
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("all")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
imageLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
imageLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help/splash.png"))); // NOI18N
getContentPane().add(imageLabel, java.awt.BorderLayout.CENTER);
progressBar.setForeground(new java.awt.Color(51, 85, 112));
progressBar.setStringPainted(true);
getContentPane().add(progressBar, java.awt.BorderLayout.PAGE_END);
pack();
}// </editor-fold>
/**
* Sets the max value for the progressbar
* #param maxProgress
*/
public void setProgressMax(int maxProgress) {
progressBar.setMaximum(maxProgress);
}
public void setProgress(int progress) {
final int theProgress = progress;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
progressBar.setValue(theProgress);
}
});
}
/**
* Changes the string message and set a new value fro the progressbar
* #param message String the message
* #param progress int the new value of the progressbar. This cant be higher than the value defined in the setProgressMax
*/
public void setProgress(String message, int progress) {
final int theProgress = progress;
final String theMessage = message;
setProgress(progress);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
progressBar.setValue(theProgress);
setMessage(theMessage);
}
});
}
private void setMessage(String message) {
if (message == null) {
message = "";
progressBar.setStringPainted(false);
} else {
progressBar.setStringPainted(true);
}
progressBar.setString(message);
}
// Variables declaration - do not modify
private javax.swing.JLabel imageLabel;
private javax.swing.JProgressBar progressBar;
// End of variables declaration
}
To call
final Splash s = new Splash();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
s.splashScreenInit();
}
});
and in the end
s.setVisible(false);
the following is my code it is working properly in my system.. u can try add import the following in your codes
//import com.sun.awt.AWTUtilities;
//import java.awt.event.ActionEvent;
//import javax.swing.Timer;
//import javax.swing.UIManager;
//import java.awt.event.ActionListener;
//import javax.swing.JProgressBar;
private Timer t;
private ActionListener al;
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
ActionListener a1 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
if(jProgressBar1.getValue()<100)
{
jProgressBar1.setValue(jProgressBar1.getValue()+5);
}
else
{
t.stop();
abcd();
}
}
};
t=new Timer(80, a1);
initComponents();
AWTUtilities.setWindowOpaque(this, false);
t.start();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jProgressBar1 = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
jLabel1.setText("jLabel1");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(123, 123, 123)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(141, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(66, 66, 66)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(41, 41, 41)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(133, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void abcd()
{
NewJFrame1 f1= new NewJFrame1();
f1.setLocationRelativeTo(null);
f1.setVisible(true);
this.dispose();
}
I have installed OpenCV-3.1.0 and in 3.0.0 or later versions, there's no HighGUI module in Java. That functionality is split in to two additional modules (videoio,imgcodecs).
I'm trying to capture a video from web cam using Java with OpenCv. Here's a class I found that does the Job. But since my version is not having HighGUI module, what is the way (or the code) that I can use to get the same functionality, instead of "Highgui.imencode()"?
package gui;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import javax.imageio.ImageIO;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.videoio.VideoCapture;
/**
* #author erandi
*/
public class WebCamTesting extends javax.swing.JFrame {
/**
* Creates new form WebCamTesting
*/
//definitions
private DaemonThread myThread = null;
int count = 0;
VideoCapture webSource = null;
Mat frame = new Mat();
MatOfByte mem = new MatOfByte();
//class of thread
class DaemonThread implements Runnable {
protected volatile boolean runnable = false;
#Override
public void run() {
synchronized (this) {
while (runnable) {
if (webSource.grab()) {
try {
webSource.retrieve(frame);
//Error - can't find the class Highgui
Highgui.imencode(".bmp", frame, mem);
Image im = ImageIO.read(new ByteArrayInputStream(mem.toArray()));
BufferedImage buff = (BufferedImage) im;
Graphics g = jPanelVideo.getGraphics();
if (g.drawImage(buff, 0, 0, getWidth(), getHeight() - 150, 0, 0, buff.getWidth(), buff.getHeight(), null))
if (runnable == false) {
System.out.println("Going to wait()");
this.wait();
}
} catch (Exception ex) {
System.out.println("Error");
}
}
}
}
}
}
public WebCamTesting() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanelVideo = new javax.swing.JPanel();
jButtonStart = new javax.swing.JButton();
jButtonPause = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout jPanelVideoLayout = new javax.swing.GroupLayout(jPanelVideo);
jPanelVideo.setLayout(jPanelVideoLayout);
jPanelVideoLayout.setHorizontalGroup(
jPanelVideoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 454, Short.MAX_VALUE)
);
jPanelVideoLayout.setVerticalGroup(
jPanelVideoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 335, Short.MAX_VALUE)
);
jButtonStart.setText("Start");
jButtonStart.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonStartActionPerformed(evt);
}
});
jButtonPause.setText("Pause");
jButtonPause.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonPauseActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(121, 121, 121)
.addComponent(jButtonStart)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButtonPause)
.addGap(117, 117, 117))
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jPanelVideo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(40, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanelVideo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButtonPause)
.addComponent(jButtonStart))
.addGap(55, 55, 55))
);
pack();
}// </editor-fold>
private void jButtonStartActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
webSource = new VideoCapture(0); //video capture from default cam
myThread = new DaemonThread(); //create object from thread class
Thread t = new Thread(myThread);
t.setDaemon(true);
myThread.runnable = true;
t.start(); //start thread
jButtonStart.setEnabled(false); //deactivate start button
jButtonPause.setEnabled(true); // activate pause button
}
private void jButtonPauseActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
myThread.runnable = false; //stop thread
jButtonPause.setEnabled(false); //activate start
jButtonStart.setEnabled(true); //deactivate pause
webSource.release();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // load native library of opencv
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new WebCamTesting().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButtonPause;
private javax.swing.JButton jButtonStart;
private javax.swing.JPanel jPanelVideo;
// End of variables declaration
}
I use this:
Imgcodecs.imencode(".jpg", image, bytemat);