Error in splash screen in Java/Swing - java

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

Related

How to download and display an image with SwingWorker [duplicate]

I want to display an image from the web to a panel in another JFrame at the click of a button. Whenever I click the button, first the image loads; and during this time, the current form potentially freezes. Once the image has loaded, the form is displayed with the image. How can I avoid the situation where my form freezes since it is very irritating. Among my codes:
My current class:
private void btn_TrackbusActionPerformed(java.awt.event.ActionEvent evt) {
try {
sendMessage("Query,map,$,start,211,Arsenal,!");
System.out.println(receiveMessage());
} catch (UnknownHostException ex) {
Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex);
}
catch (Exception ex) {
Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex);
}
client_trackedbus nextform=new client_trackedbus(planform,connection,packet_receive,packet_send);
this.setVisible(false);
this.dispose();
nextform.setVisible(true);
// TODO add your handling code here:
}
My next class that displays the image:
public class client_trackedbus extends javax.swing.JFrame {
client_planform planform=null;
DatagramSocket connection=null;
DatagramPacket packet_receive=null;
DatagramPacket packet_send=null;
JLabel label=null;
/** Creates new form client_trackedbus */
public client_trackedbus(client_planform planform,DatagramSocket connection,DatagramPacket packet_receive,DatagramPacket packet_send) {
initComponents();
this.planform=planform;
this.connection=connection;
this.packet_receive=packet_receive;
this.packet_send=packet_send;
try {
displayMap("http://www.huddletogether.com/projects/lightbox2/images/image-2.jpg", jPanel1, new JLabel());
} catch (MalformedURLException ex) {
Logger.getLogger(client_trackedbus.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void displayMap(String url,JPanel panel,JLabel label) throws MalformedURLException{
URL imageurl=new URL(url);
Image image=(Toolkit.getDefaultToolkit().createImage(imageurl));
ImageIcon icon = new ImageIcon(image);
label.setIcon(icon);
panel.add(label);
// System.out.println(panel.getSize().width);
this.getContentPane().add(panel);
}
/** 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();
btn_Exit = new javax.swing.JButton();
btn_Plan = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Public Transport Journey Planner");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 368, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 172, Short.MAX_VALUE)
);
jLabel1.setFont(new java.awt.Font("Arial", 1, 18));
jLabel1.setText("Your tracked bus");
btn_Exit.setText("Exit");
btn_Exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_ExitActionPerformed(evt);
}
});
btn_Plan.setText("Plan journey");
btn_Plan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_PlanActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(104, 104, 104)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(65, 65, 65)
.addComponent(btn_Plan)
.addGap(65, 65, 65)
.addComponent(btn_Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(20, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_Exit)
.addComponent(btn_Plan))
.addContainerGap(12, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btn_ExitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Exitform();
}
private void btn_PlanActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.setVisible(false);
this.dispose();
this.planform.setVisible(true);
}
private void Exitform(){
this.setVisible(false);
this.dispose();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// new client_trackedbus().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btn_Exit;
private javax.swing.JButton btn_Plan;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
As suggested in the article Concurrency in Swing, your button handler's query may be blocking the event dispatch thread. Using javax.swing.SwingWorker is one approach to loading images in the background, while displaying progress and keeping the GUI thread alive.
Addendum: Here's a sscce that loads the SO logo; it's been updated to handle exceptions and resize the enclosing container to fit the loaded image:
import java.awt.*;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
* #see http://stackoverflow.com/questions/4530659
*/
public final class WorkerTest extends JFrame {
private final JLabel label = new JLabel("Loading...");
public WorkerTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.BOTTOM);
this.add(label);
this.pack();
this.setLocationRelativeTo(null);
}
private void start() {
new ImageWorker().execute();
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
WorkerTest wt = new WorkerTest();
wt.setVisible(true);
wt.start();
}
});
}
class ImageWorker extends SwingWorker<Image, Void> {
private static final String TEST
= "http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png";
#Override
protected Image doInBackground() throws IOException {
Image image = ImageIO.read(new URL(TEST));
return image.getScaledInstance(640, -1, Image.SCALE_SMOOTH);
}
#Override
protected void done() {
try {
ImageIcon icon = new ImageIcon(get());
label.setIcon(icon);
label.setText("Done");
WorkerTest.this.pack();
WorkerTest.this.setLocationRelativeTo(null);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
}
public class SSBTest extends javax.swing.JFrame {
/** Creates new form worker1 */
public SSBTest() {
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() {
jLabel1 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("jLabel1");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 348, Short.MAX_VALUE));
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 210, 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(layout.createSequentialGroup().addContainerGap(196, Short.MAX_VALUE).addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(178, 178, 178)).addGroup(layout.createSequentialGroup().addGap(86, 86, 86).addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(122, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, 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, 40, Short.MAX_VALUE).addComponent(jLabel1).addGap(36, 36, 36)));
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
final SSBTest ssbTest = new SSBTest();
ssbTest.setVisible(true);
ssbTest.execute();
}
});
}
private void execute() {
(new MeaningOfLifeFinder(jLabel1, jPanel1)).execute();
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
class MeaningOfLifeFinder extends SwingWorker<Icon, Object> {
JLabel label = null;
JPanel panel;
MeaningOfLifeFinder(JLabel label, JPanel jpanel) {
this.label = label;
this.panel = jpanel;
}
protected Icon doInBackground() throws IOException {
URL imageurl;
Image image = null;
System.out.println("image loading");
imageurl = new URL("http://maps.google.com/maps/api/staticmap"
+ "?zoom=14&size=512x512&maptype=roadmap"
+ "&markers=color:green|label:21|-15.0,-150.0&sensor=false");
//image = (Toolkit.getDefaultToolkit().createImage(imageurl));
image = ImageIO.read(imageurl);
ImageIcon icon = new ImageIcon(image);
System.out.println("image loaded...");
return icon;
}
#Override
protected void done() {
try {
System.out.println("image adding to label...");
label.setIcon(get());
//panel.add(label);
System.out.println("image loaded to label...");
} catch (Exception ignore) {
}
}
// System.out.println(panel.getSize().width);
}

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

Repaint doesn't work and the value of my private fields won't change?

I am making a graphical interface in Netbeans where you can put a series of numbers (example: 7 8 5 4 10 13) in the textfield "punten" and when you press the button "ververs" a graphical linechart of all the numbers should appear (in my panel). I made a class "Gui" that extends JFrame with the Textfield, the button and a panel in it. I also made a class "Grafiek" that extends JPanel and that is linked with the panel in my "Gui".
The problems that I experience are: the repaint(); command won't go to the paintComponent(Graphics g)-method and my private variables won't change (the length of punt and punti stays 0).
Can somebody please help me, I've been working on this project for days.
My Gui-class:
import java.awt.Graphics;
public class Gui extends javax.swing.JFrame {
public Gui() {
initComponents();
panel = new javax.swing.JPanel();
}
/**
* 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() {
punten = new javax.swing.JTextField();
fout = new javax.swing.JLabel();
javax.swing.JButton ververs = new javax.swing.JButton();
panel = new Grafiek();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
fout.setText("j");
ververs.setText("Ververs");
ververs.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
verversActionPerformed(evt);
}
});
panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
panel.setLayout(panelLayout);
panelLayout.setHorizontalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
panelLayout.setVerticalGroup(
panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 195, 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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(punten, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(ververs)
.addGap(6, 6, 6)
.addComponent(fout)
.addGap(0, 302, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(punten, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(fout)
.addComponent(ververs))
.addContainerGap())
);
pack();
}// </editor-fold>
private void verversActionPerformed(java.awt.event.ActionEvent evt) {
Grafiek graf = new Grafiek();
graf.verwerkData(punten.getText());
}
/**
* #param args the command line arguments
*/
public static 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(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Gui.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 Gui().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel fout;
private javax.swing.JPanel panel;
private javax.swing.JTextField punten;
// End of variables declaration
}
And my "Grafiek"-class:
import java.awt.Graphics;
public class Grafiek extends javax.swing.JPanel {
private String[] punt;
private int[] punti;
private int afstandX, afstandY, puntX1=0, puntY1=0, puntX2=0, puntY2=0;
private int max=1;
/**
* Creates new form Grafiek
*/
public Grafiek() {
initComponents();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
try{
for(int i=0; i<punti.length; i++) {
if(max <= punti[i]) {
max = punti[i];
}
}
afstandX = getWidth()/punt.length;
afstandY = getHeight()/max;
for(int i=0; i<punti.length; i++) {
puntX1 = puntX2;
if(i == 0) {
puntY1 = getHeight();
}
else puntY1 = puntY2;
puntX2 += afstandX;
puntY2 = getHeight() - punti[i]*afstandY;
g.drawLine(puntX1, puntY1, puntX2, puntY2);
}
puntX2 = 0;
puntY2 = 0;
}catch(java.lang.NullPointerException npe) {
super.paintComponent(g);
}
}
public void verwerkData(String s) {
punt = s.split(" ");
punti = new int[punt.length];
for(int i=0; i<punt.length; i++) {
punti[i] = Integer.parseInt(punt[i]);
}
repaint();
}
/**
* 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() {
setBackground(new java.awt.Color(255, 255, 255));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>
}
The code does not work because you add your points to the wrong object.
First of all, your panel object is not of type Grafiek, second of all it is first initialized in the method initComponents() and then overwritten again in the constructor.
Second problem, in the method verversActionPerformed called by the action listener, you create a new instance of Grafiek that is obviously not the one you have created/added before.
Thus, to make it work alter the code as follows:
The constructor should look the following:
public Gui() {
initComponents();
//panel = new javax.swing.JPanel();
}
The method like this:
private void verversActionPerformed(java.awt.event.ActionEvent evt) {
Grafiek graf = (Grafiek)panel;
graf.verwerkData(punten.getText());
}
Thus, it works as you expected.
However, this is far away from good code. You should set the type of variable panel to the correct type Grafiek.

Exchange variable between two jFrames

I have 3 java files.
DBConn - This Class conencts to the database and execute query.
UserLogin - This jFrame will take username and password and compare with "users" table
if it matches it will display "Login Successfull" in LibSysMain java file
LibSysMain - This is the main file which shows the menu.
This is the jFrame which is displayed first when application is run.
The problem is I am not able to set the "Login Successful" message in LibSysMain.
My Database is MS Access. Table name is "users". Field is "username" and "password". Both of them are of string type.
A help would be highly apprecited.
I am new in Java. I am using NetBeans 6.9.1.
Here is the list:
DBConn:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package LibSystem;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class DBConn {
Connection con;
Statement stmt;
ResultSet rs;
public void DoConnect(String querydb)
{
String SQL;
SQL=querydb;
try
{
// CONNECT TO THE DATABASE
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Database\\libsys\\libsys.mdb";
con = DriverManager.getConnection(url);
System.out.println("\nConnected to the database");
//QUERY THE DATABASE
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
//String SQL ="Select * from Members";
rs=stmt.executeQuery(SQL);
//MOVE CURSOR AT FIRST RECORD AND FETCH DATA
rs.next();
}
catch(ClassNotFoundException e)
{
System.out.println("\nClass not found. Check Path");
e.printStackTrace();
}
catch (SQLException err)
{
JOptionPane.showMessageDialog(null, err.getMessage());
}
}
}
UserLogin:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* UserLogin.java
*
* Created on Apr 23, 2011, 8:46:59 PM
*/
package LibSystem;
import java.sql.*;
import javax.swing.JOptionPane;
import java.lang.*;
/**
*
* #author Administrator
*/
public class UserLogin extends javax.swing.JFrame {
private String user;
private String password;
private String status;
/** Creates new form UserLogin */
public UserLogin() {
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() {
txtUserName = new javax.swing.JTextField();
txtPassword = new javax.swing.JTextField();
btnClose = new javax.swing.JButton();
btnLogin = new javax.swing.JButton();
lbUserName = new javax.swing.JLabel();
lbPassword = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnClose.setText("Close");
btnClose.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCloseActionPerformed(evt);
}
});
btnLogin.setText("Login");
btnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoginActionPerformed(evt);
}
});
lbUserName.setText("User Name");
lbPassword.setText("Password");
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(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lbPassword)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(lbUserName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 128, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnClose)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 64, Short.MAX_VALUE)
.addComponent(btnLogin))
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtPassword, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE))))
.addGap(35, 35, 35))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(lbUserName)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbPassword)
.addGap(5, 5, 5)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnClose)
.addComponent(btnLogin))
.addContainerGap(39, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//CREATE AN INSTANCE OF DBCONN CLASS TO CONNECT TO THE DATABASE
//WE TAKE THE USERNAME FROM THE LOGIN WINDOW AND SEARCH THE USER
//BASED ON THAT USER. IF FOUND, COMPARE IT WITH THE LOGIN WINDOW.
//IF NOT FOUND DISPLAY ERROR MESSAGE.
DBConn dbc = new DBConn();
String qry = "Select * from users where username=" + "'" + txtUserName.getText() + "'";
dbc.DoConnect(qry);
try
{
setUsername(dbc.rs.getString("username"));
setPassword(dbc.rs.getString("password"));
//TEST PRINTOUT OF USERNAME AND PASSWORD FOR DEBUGGING
System.out.println(getUsername());
System.out.println(getPassword());
if (user.equals(txtUserName.getText()) && password.equals(txtPassword.getText()))
{
JOptionPane.showMessageDialog(UserLogin.this, "Login Successfull");
this.setStatus("pass");
dispose();
}
else
{
JOptionPane.showMessageDialog(UserLogin.this, "Login unsuccessful");
setStatus("fail");
}
}
catch (SQLException err)
{
JOptionPane.showMessageDialog(UserLogin.this, err.getMessage());
}
}
private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.dispose();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UserLogin().setVisible(true);
}
});
}
public void setUsername(String u)
{
user = u;
}
public void setPassword(String p)
{
password = p;
}
public String getUsername()
{
return user;
}
public String getPassword()
{
return password;
}
public void setStatus(String stat)
{
status = stat;
}
public String getStatus()
{
return status;
}
// Variables declaration - do not modify
private javax.swing.JButton btnClose;
private javax.swing.JButton btnLogin;
private javax.swing.JLabel lbPassword;
private javax.swing.JLabel lbUserName;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUserName;
// End of variables declaration
}
LibSysMain:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* LibsysMain.java
*
* Created on Apr 23, 2011, 6:48:18 PM
*/
package LibSystem;
import javax.swing.JOptionPane;
/**
*
* #author Administrator
*/
public class LibsysMain extends javax.swing.JFrame {
String q;
/** Creates new form LibsysMain */
public LibsysMain()
{
initComponents();
//DBConn dbc = new DBConn();
//q="Select * from users";
//dbc.DoConnect(q);
}
// LibsysMain frame1 = new LibsysMain();
// UserLogin frame2 = new UserLogin(frame1);
/** 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() {
jPanel2 = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
jMenuBar1 = new javax.swing.JMenuBar();
miLogin = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowActivated(java.awt.event.WindowEvent evt) {
formWindowActivated(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 539, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 328, Short.MAX_VALUE)
);
jLabel1.setText("Status");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addContainerGap(518, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
);
jSeparator1.setAlignmentX(0.0F);
jSeparator1.setMinimumSize(new java.awt.Dimension(10, 10));
miLogin.setText("Connect");
miLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
miLoginActionPerformed(evt);
}
});
jMenuItem1.setText("Login");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
miLogin.add(jMenuItem1);
jMenuItem2.setText("Exit");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
miLogin.add(jMenuItem2);
jMenuBar1.add(miLogin);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 559, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.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(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>
private void miLoginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
UserLogin ul = new UserLogin();
ul.setVisible(true);
//SET THE STATUS IF LOGIN IS SUCCESSFULL
if (ul.getStatus() == "pass")
{
jLabel1.setText("Logged In");
}
else
{
jLabel1.setText("Cannot Log in");
}
}
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void formWindowActivated(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LibsysMain().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JMenu miLogin;
// End of variables declaration
}
I have a couple of suggestions:
For one, don't compare Strings with == as you do here if (ul.getStatus() == "pass") as this checks to see if two variables refer to the same String object (which you don't care about) but rather use either the equals or the equalsIgnoreCase method which checks to see if the two Strings contain the same String data (which you do care about). e.g., if (ul.getStatus().equalsIgnoreCase("pass"))
Be sure to do all of your database queries and whatnot in a thread background to the GUI's thread, the EDT such as can be achieved by using a SwingWorker object. This article will tell you what I said but will give you the details: Concurrency in Swing.
Consider using a single JFrame and modal dialogs to act as dialog windows to the main app. This can be achieved by using JOptionPanes or modal JDialogs, in particular for your UserLogin window.
For this reason, I like to gear my GUI's towards creating JPanels rather than top level windows such as JFrames. This way I can place my GUI/JPanel into any type of window I desire depending on the situation be it a JFrame, a JApplet, a JDialog, a JOptionPane, or even nested into another JPanel. This gives you an amazing amount of flexibilty.

To display an image

I want to display an image from the web to a panel in another JFrame at the click of a button. Whenever I click the button, first the image loads; and during this time, the current form potentially freezes. Once the image has loaded, the form is displayed with the image. How can I avoid the situation where my form freezes since it is very irritating. Among my codes:
My current class:
private void btn_TrackbusActionPerformed(java.awt.event.ActionEvent evt) {
try {
sendMessage("Query,map,$,start,211,Arsenal,!");
System.out.println(receiveMessage());
} catch (UnknownHostException ex) {
Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex);
}
catch (Exception ex) {
Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex);
}
client_trackedbus nextform=new client_trackedbus(planform,connection,packet_receive,packet_send);
this.setVisible(false);
this.dispose();
nextform.setVisible(true);
// TODO add your handling code here:
}
My next class that displays the image:
public class client_trackedbus extends javax.swing.JFrame {
client_planform planform=null;
DatagramSocket connection=null;
DatagramPacket packet_receive=null;
DatagramPacket packet_send=null;
JLabel label=null;
/** Creates new form client_trackedbus */
public client_trackedbus(client_planform planform,DatagramSocket connection,DatagramPacket packet_receive,DatagramPacket packet_send) {
initComponents();
this.planform=planform;
this.connection=connection;
this.packet_receive=packet_receive;
this.packet_send=packet_send;
try {
displayMap("http://www.huddletogether.com/projects/lightbox2/images/image-2.jpg", jPanel1, new JLabel());
} catch (MalformedURLException ex) {
Logger.getLogger(client_trackedbus.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void displayMap(String url,JPanel panel,JLabel label) throws MalformedURLException{
URL imageurl=new URL(url);
Image image=(Toolkit.getDefaultToolkit().createImage(imageurl));
ImageIcon icon = new ImageIcon(image);
label.setIcon(icon);
panel.add(label);
// System.out.println(panel.getSize().width);
this.getContentPane().add(panel);
}
/** 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();
btn_Exit = new javax.swing.JButton();
btn_Plan = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Public Transport Journey Planner");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 368, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 172, Short.MAX_VALUE)
);
jLabel1.setFont(new java.awt.Font("Arial", 1, 18));
jLabel1.setText("Your tracked bus");
btn_Exit.setText("Exit");
btn_Exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_ExitActionPerformed(evt);
}
});
btn_Plan.setText("Plan journey");
btn_Plan.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_PlanActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(104, 104, 104)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(65, 65, 65)
.addComponent(btn_Plan)
.addGap(65, 65, 65)
.addComponent(btn_Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(20, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_Exit)
.addComponent(btn_Plan))
.addContainerGap(12, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btn_ExitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Exitform();
}
private void btn_PlanActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.setVisible(false);
this.dispose();
this.planform.setVisible(true);
}
private void Exitform(){
this.setVisible(false);
this.dispose();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// new client_trackedbus().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btn_Exit;
private javax.swing.JButton btn_Plan;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
As suggested in the article Concurrency in Swing, your button handler's query may be blocking the event dispatch thread. Using javax.swing.SwingWorker is one approach to loading images in the background, while displaying progress and keeping the GUI thread alive.
Addendum: Here's a sscce that loads the SO logo; it's been updated to handle exceptions and resize the enclosing container to fit the loaded image:
import java.awt.*;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
* #see http://stackoverflow.com/questions/4530659
*/
public final class WorkerTest extends JFrame {
private final JLabel label = new JLabel("Loading...");
public WorkerTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.BOTTOM);
this.add(label);
this.pack();
this.setLocationRelativeTo(null);
}
private void start() {
new ImageWorker().execute();
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
WorkerTest wt = new WorkerTest();
wt.setVisible(true);
wt.start();
}
});
}
class ImageWorker extends SwingWorker<Image, Void> {
private static final String TEST
= "http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png";
#Override
protected Image doInBackground() throws IOException {
Image image = ImageIO.read(new URL(TEST));
return image.getScaledInstance(640, -1, Image.SCALE_SMOOTH);
}
#Override
protected void done() {
try {
ImageIcon icon = new ImageIcon(get());
label.setIcon(icon);
label.setText("Done");
WorkerTest.this.pack();
WorkerTest.this.setLocationRelativeTo(null);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
}
public class SSBTest extends javax.swing.JFrame {
/** Creates new form worker1 */
public SSBTest() {
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() {
jLabel1 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("jLabel1");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 348, Short.MAX_VALUE));
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 210, 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(layout.createSequentialGroup().addContainerGap(196, Short.MAX_VALUE).addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(178, 178, 178)).addGroup(layout.createSequentialGroup().addGap(86, 86, 86).addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(122, Short.MAX_VALUE)));
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, 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, 40, Short.MAX_VALUE).addComponent(jLabel1).addGap(36, 36, 36)));
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
final SSBTest ssbTest = new SSBTest();
ssbTest.setVisible(true);
ssbTest.execute();
}
});
}
private void execute() {
(new MeaningOfLifeFinder(jLabel1, jPanel1)).execute();
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
class MeaningOfLifeFinder extends SwingWorker<Icon, Object> {
JLabel label = null;
JPanel panel;
MeaningOfLifeFinder(JLabel label, JPanel jpanel) {
this.label = label;
this.panel = jpanel;
}
protected Icon doInBackground() throws IOException {
URL imageurl;
Image image = null;
System.out.println("image loading");
imageurl = new URL("http://maps.google.com/maps/api/staticmap"
+ "?zoom=14&size=512x512&maptype=roadmap"
+ "&markers=color:green|label:21|-15.0,-150.0&sensor=false");
//image = (Toolkit.getDefaultToolkit().createImage(imageurl));
image = ImageIO.read(imageurl);
ImageIcon icon = new ImageIcon(image);
System.out.println("image loaded...");
return icon;
}
#Override
protected void done() {
try {
System.out.println("image adding to label...");
label.setIcon(get());
//panel.add(label);
System.out.println("image loaded to label...");
} catch (Exception ignore) {
}
}
// System.out.println(panel.getSize().width);
}

Categories

Resources