JPanel JFrame PaintComponent || Image is not being shown to JPanel - java

Please see the below code. I'm trying to display an image on the JPanel. Look at the screenshoot. I want to paint image over FrameImagePanel. but it is not working.
this.imagePanel = new ImagePanel();
FrameImagePanel.add(this.imagePanel);
FrameImagePanel.setSize(this.imagePanel.getWidth(), this.imagePanel.getHeight());
Look at the part above. this code was supposed to show the image. ?? some part of the code is not added here. as stackoverflow does not allow much details code.
enter image description here
package imagetopixelvalue;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* #author MARUF AHMAD
*/
public class ViewImage extends javax.swing.JFrame {
public ImagePanel imagePanel;
/** Creates new form ViewImage */
public ViewImage() {
initComponents();
// JFrame frame = new JFrame("Testing");
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.imagePanel = new ImagePanel();
FrameImagePanel.add(this.imagePanel);
FrameImagePanel.setSize(this.imagePanel.getWidth(), this.imagePanel.getHeight());
System.out.print(" --> "+this.imagePanel.getWidth()+" || "+ this.imagePanel.getHeight());
// frame.pack();
// frame.setLocationRelativeTo(null);
// frame.setVisible(true);
}
public class ImagePanel extends JPanel {
int ImageH =0;
int ImageW =0;
BufferedImage imageBuff;
public ImagePanel(){
try{
BufferedImage image = ImageIO.read(new File("image.jpg"));
imageBuff = image;
System.out.print(image.getWidth()+" || "+ image.getHeight());
ImageH = image.getHeight();
ImageW = image.getWidth();
}
catch(IOException e){
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(ImageW, ImageH);
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.red);
g.drawImage(imageBuff, 0, 0, this);
}
}
/** 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() {
FrameImagePanel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
FrameImagePanel.setBackground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout FrameImagePanelLayout = new javax.swing.GroupLayout(FrameImagePanel);
FrameImagePanel.setLayout(FrameImagePanelLayout);
FrameImagePanelLayout.setHorizontalGroup(
FrameImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 380, Short.MAX_VALUE)
);
FrameImagePanelLayout.setVerticalGroup(
FrameImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 278, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(FrameImagePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(FrameImagePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ViewImage().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel FrameImagePanel;
// End of variables declaration
}
you do not need to check all the code just see the above part.

Related

Basically what i want is to display the usb directoires and a local drive directoires in two jscrollpane side by side

I have made two JScrollPane components. The left one shows the directories in USB and right shows the directories of a local drive. For I am able to display the complete file path as shown in first pic. But I want to display it with icons just like the way directories are displayed in any local drive on PC. This is my designed GUI, here is the example of what I want example
public class MainForm extends javax.swing.JFrame {
iRecordCopy obj = new iRecordCopy();
public MainForm() {
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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jScrollPane2 = new javax.swing.JScrollPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Main From");
setLocation(new java.awt.Point(0, 0));
setName("mainframe"); // NOI18N
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel1.setText("iRecordCopy");
jLabel2.setText("jLabel2");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(48, 48, 48)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(25, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(30, 30, 30))
);
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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE)
.addComponent(jScrollPane2))
.addContainerGap())
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainForm().setVisible(true);
}
});
}
public void showusb()
{
File[] usb;
int count = 0;
String str;
usb = obj.detectUSB();
if(usb == null)
{
//USB_window.setText("No USB attached\n");
return;
}
for (File filename : usb) {
str = filename.toString().substring(3);
str = str.substring(0, str.length() - 3);
System.out.println(str);
if(str.equalsIgnoreCase("vehicle"))
{
System.out.print(filename.toString());
//USB_window.append(filename.getPath()+"\n");
count++;
}
}
if(count == 0)
{
System.out.println("No recordings found in usb");
}
else
System.out.println("Number of directries :" + count);
//File currentDir = new File(System.getProperty("user.home"));
JList<File> jlist=new JList<File>(obj.path.listFiles());
jScrollPane1 = new JScrollPane(jlist);
jScrollPane1.setPreferredSize(new Dimension(400, 800));
setContentPane(jScrollPane1);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
}
public void showPc(File f)
{
JList<File> jlist=new JList<File>(f.listFiles());
jScrollPane2 = new JScrollPane(jlist);
//jScrollPane2.setPreferredSize(new Dimension(400, 800));
setContentPane(jScrollPane2);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration
}
Here a short example to create a minimal JList with file icons, it displays the content of the user's home directory using the system file icons.
package test;
import java.awt.Component;
import java.awt.Dimension;
import java.io.File;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.filechooser.FileSystemView;
public class Test {
public static void main(String[] args) {
JFrame frame=new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File currentDir=new File(System.getProperty("user.home"));
JList<File> jlist=new JList<File>(currentDir.listFiles());
JScrollPane scrollPane=new JScrollPane(jlist);
scrollPane.setPreferredSize(new Dimension(400, 800));
frame.setContentPane(scrollPane);
final JLabel label=new JLabel();
jlist.setCellRenderer(new ListCellRenderer<File>() {
#Override
public Component getListCellRendererComponent(JList<? extends File> list, File value, int index,
boolean isSelected, boolean cellHasFocus) {
label.setIcon(FileSystemView.getFileSystemView().getSystemIcon(value));
label.setText(value.getName());
return label;
}
});
frame.pack();
frame.setVisible(true);
}
}

Error in splash screen in Java/Swing

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();
}

When using OpenCV-3.1.0, what is the method to get the functionality of "Highgui.imencode()" provided in OpenCV-2x?

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);

viewing entire pdf in java using pdf renderer

I'm trying to view an entire pdf in a panel by adding splits and scroller and a for loop that goes through all pages.
The problem is that it is showing only the last page. Can anyone rectify my error please.
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PagePanel;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.swing.*;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jFrame1 = new javax.swing.JFrame();
jButton1 = new javax.swing.JButton();
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(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(64, 64, 64)
.addComponent(jButton1)
.addContainerGap(263, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(65, 65, 65)
.addComponent(jButton1)
.addContainerGap(212, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JSplitPane split= new JSplitPane();
JScrollPane thumbscroll=new JScrollPane();
JFrame frame = new JFrame("PDF Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PagePanel panel = new PagePanel();
frame.add(panel);
frame.pack();
frame.setVisible(true);
File file = new File("C:\\Users\\om\\Downloads\\cse.pdf");
try{
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY,
0, channel.size());
frame.add(split);
frame.add(thumbscroll);
frame.pack();
// show the first page
for(int i=0;i<10;i++)
{
PDFFile pdffile = new PDFFile(buf);
PDFPage page = pdffile.getPage(i);
panel.showPage(page);
}
}
catch(IOException e)
{
System.out.print(e.getMessage());
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JFrame jFrame1;
// End of variables declaration
}
Every time you call showPage the shown page will be overridden. For a working example of a PDF-Viewer look here

How to draw a vertical line in JPanel at a specific position?

I am trying to design a timeline for this media playback application using a JPanel. In order to provide an indication of the current video frame with respect to the timeline, I need to be able to draw a vertical line at a specific x-coordinate in this TimeLinePanel class that extends JPanel. So far, I haven't had much luck with using the paint() function or overriding the paintComponent(). When I tried to use the paint() function in my NewJApplet (this class extends JApplet) class, the vertical line is drawn, but the JPanel that I'm using as the timeline disappears (the border is no longer visible). In addition, I've heard that using the paint() method was not preferrable. As a result, I've tried to override paintComponent() method in JPanel and I've tried calling the paintComponent method from NewJApplet, but it does not update timeLinePanel1 with the vertical line.
Any help would be appreciated.
The following is the code I have so far:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package helloworld;
import java.awt.GridLayout;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* #author Justin
*/
public class NewJApplet extends javax.swing.JApplet {
/**
* Initializes the applet NewJApplet
*/
#Override
public void init() {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
/*
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
* */
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJApplet.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the applet */
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
timeLinePanel1.paintComponent(timeLinePanel1.getGraphics());
timeLinePanel1.repaint();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* This method is called from within the init() method 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() {
myPanel = new javax.swing.JPanel();
timeLinePanel1 = new helloworld.TimeLinePanel();
myPanel.setBackground(new java.awt.Color(51, 51, 51));
javax.swing.GroupLayout myPanelLayout = new javax.swing.GroupLayout(myPanel);
myPanel.setLayout(myPanelLayout);
myPanelLayout.setHorizontalGroup(
myPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(myPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(timeLinePanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
.addContainerGap())
);
myPanelLayout.setVerticalGroup(
myPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, myPanelLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(timeLinePanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(myPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(0, 0, 0))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(myPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JPanel myPanel;
private helloworld.TimeLinePanel timeLinePanel1;
// End of variables declaration
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package helloworld;
import java.awt.GridLayout;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* #author Justin
*/
public class TimeLinePanel extends javax.swing.JPanel {
/**
* Creates new form TimeLinePanel
*/
public TimeLinePanel() {
initComponents();
}
#Override
protected void paintComponent(Graphics g) {
Rectangle r = new Rectangle(3, 0, 1, 25);
g.fillRect(25, 0, 1, 25);
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 200, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 25, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.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)
);
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
This is what I get when I try to run the applet. Ideally, I'd like to have a vertical line drawn at some (x,y) coordinate in the white box (timeLinePanel1), such as (25,0) (as indicated in the code) to get an understanding of how I can proceed with drawing vertical lines within a JPanel.
You need to call super.paintComponent in order to paint everything in your panel:
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(25, 0, 1, 25);
}
I'm not sure, that it's correct answer but probably you forget to set the color?
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
Rectangle r = new Rectangle(3, 0, 1, 25);
g.fillRect(25, 0, 1, 25);
}

Categories

Resources