I am using this mmscomputing library as java applet to scan an image or document.
Using swings,awt i created one scan button which is acquiring scanner by calling scanner.acquire() method of mmscomputing jar..
and then placing that scanned image into jpanel for displaying.
Problem is, first time when i start my applet and hitting my scan button..scanning works fine..Twain states it goes into are: 3,4,5,6,7,5,4,3
then second time,hitting my scan button again ..
Twain states it goes into are: 3,4,5,4,3
It's not going into image transfer ready and transferring state and thus not into below CODE IF loop
if (type.equals(ScannerIOMetadata.ACQUIRED))
so i am not able to see the new scanned image into my jpanel second time...
then third time, hitting my scan button .. again it works fine.. getting into all states.
So i mean, For alternatively turns or restarting the java applet again ..it works.
what would be the issue.. ?
I want, every time when i hit scan button it should get me a new image into Jpanel.. but it's doing alternative times.
can i forcefully explicitly set or change twain states to come into 6th and 7th states..
or is there some twain source initialisation problem occurs second time?
because restarting applet is doing fine every time.. or some way to reinitialise applet objects everytime on clicking scan button..as it would feel like I am restarting applet everytime on clicking scan button...
I am not getting it..
Below is the sample code:
import uk.co.mmscomputing.device.twain.TwainConstants;
import uk.co.mmscomputing.device.twain.TwainIOMetadata;
import uk.co.mmscomputing.device.twain.TwainSource;
import uk.co.mmscomputing.device.twain.TwainSourceManager;
public class XXCrop extends JApplet implements PlugIn, ScannerListener
{
private JToolBar jtoolbar = new JToolBar("Toolbar", JToolBar.HORIZONTAL);
ImagePanel ipanel;
Image im =null;
BufferedImage imageforCrop;
ImagePlus imp=null;
int imageWidth;
int imageHeight;
private static final long serialVersionUID = 1L;
Container content = null;
private JPanel jContentPane = null;
private JButton jButton = null;
private JButton jButton1 = null;
JCheckBox clipBox = null;
JPanel crpdpanel=null;
JPanel cpanel=null;
private Scanner scanner=null;
private TwainSource ts ;
private boolean is20;
ImagePanel imagePanel,imagePanel2 ;
public static void main(String[] args) {
new XXCrop().setVisible(true);
}
public void run(String arg0) {
new XXCrop().setVisible(false);
repaint();
}
/**
* This is the default constructor
*/
public XXCrop() {
super();
init();
try {
scanner = Scanner.getDevice();
if(scanner!=null)
{
scanner.addListener(this);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* This method initializes this
*
* #return void
*/
public void init()
{
this.setSize(1200, 600);
this.setLayout(null);
//this.revalidate();
this.setContentPane(getJContentPane());
}
private JToolBar getJToolBar()
{
jtoolbar.add(getJButton1());
jtoolbar.add(getJButton());
jtoolbar.setName("My Toolbar");
jtoolbar.addSeparator();
Rectangle r=new Rectangle(0, 0,1024, 30 );
jtoolbar.setBounds(r);
return jtoolbar;
}
private JPanel getJContentPane()
{
if (jContentPane == null)
{
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJToolBar());
}
return jContentPane;
}
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton();
jButton.setBounds(new Rectangle(4, 16, 131, 42));
jButton.setText("Select Device");
jButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
if (scanner.isBusy() == false) {
selectDevice();
}
}
});
}
return jButton;
}
/* Select the twain source! */
public void selectDevice() {
try {
scanner.select();
} catch (ScannerIOException e1) {
IJ.error(e1.toString());
}
}
private JButton getJButton1()
{
if (jButton1 == null) {
jButton1 = new JButton();
jButton1.setBounds(new Rectangle(35,0, 30, 30));
jButton1.setText("Scan");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e)
{//jContentPane.remove(crpdpanel);
//jContentPane.removeAll();
//jContentPane.repaint();
//jContentPane.revalidate();
getScan();
}
});
}
return jButton1;
}
public void getScan()
{
try
{
//scanner = Scanner.getDevice();
//scanner.addListener(this);
scanner.acquire();
}
catch (ScannerIOException e1)
{
IJ.showMessage("Access denied! \nTwain dialog maybe already opened!");
e1.printStackTrace();
}
}
public Image getImage()
{
Image image = imp.getImage();
return image;
}
/*Image cimg;
public Image getCimg()
{
return cimg;
}*/
public void update(ScannerIOMetadata.Type type, ScannerIOMetadata metadata) {
if (type.equals(ScannerIOMetadata.ACQUIRED))
{
//imagePanel.revalidate();
//imagePanel.repaint();
//imagePanel.invalidate();
//jContentPane.remove(ipanel);
//ipanel.repaint();
if(imp!=null)
{
jContentPane.remove(ipanel);
jContentPane.remove(cpanel);
jContentPane.remove(crpdpanel);
}
imp = new ImagePlus("Scan", metadata.getImage());
//imp.show();
im = imp.getImage();
//imagePanel = new ImagePanel(im,imageWidth,imageHeight);
imagePanel = new ImagePanel(im);
imagePanel.updateUI();
imagePanel.repaint();
imagePanel.revalidate();
ClipMover mover = new ClipMover(imagePanel);
imagePanel.addMouseListener(mover);
imagePanel.addMouseMotionListener(mover);
ipanel = imagePanel.getPanel();
ipanel.setBorder(new LineBorder(Color.blue,1));
ipanel.setBorder(BorderFactory.createTitledBorder("Scanned Image"));
ipanel.setBounds(0, 30,600, 600);
ipanel.repaint();
ipanel.revalidate();
ipanel.updateUI();
jContentPane.add(ipanel);
jContentPane.getRootPane().revalidate();
jContentPane.updateUI();
//jContentPane.repaint();
// cimg=imagePanel.getCimg();
// ImagePanel cpanel = (ImagePanel) imagePanel.getUIPanel();
/*
cpanel.setBounds(700, 30,600, 800);
jContentPane.add(imagePanel.getUIPanel());
*/
cpanel = imagePanel.getUIPanel();
cpanel.setBounds(700, 30,300, 150);
cpanel.repaint();
cpanel.setBorder(new LineBorder(Color.blue,1));
cpanel.setBorder(BorderFactory.createTitledBorder("Cropping Image"));
jContentPane.add(cpanel);
jContentPane.repaint();
jContentPane.revalidate();
metadata.setImage(null);
try {
new uk.co.mmscomputing.concurrent.Semaphore(0, true).tryAcquire(2000, null);
} catch (InterruptedException e) {
IJ.error(e.getMessage());
}
}
else if (type.equals(ScannerIOMetadata.NEGOTIATE)) {
ScannerDevice device = metadata.getDevice();
try {
device.setResolution(100);
} catch (ScannerIOException e) {
IJ.error(e.getMessage());
}
try{
device.setShowUserInterface(false);
// device.setShowProgressBar(true);
// device.setRegionOfInterest(0,0,210.0,300.0);
device.setResolution(100); }catch(Exception e){
e.printStackTrace(); }
}
else if (type.equals(ScannerIOMetadata.STATECHANGE)) {
System.out.println("Scanner State "+metadata.getStateStr());
System.out.println("Scanner State "+metadata.getState());
//switch (metadata.ACQUIRED){};
ts = ((TwainIOMetadata)metadata).getSource();
//ts.setCancel(false);
//ts.getState()
//TwainConstants.STATE_TRANSFERREADY
((TwainIOMetadata)metadata).setState(6);
if ((metadata.getLastState() == 3) && (metadata.getState() == 4)){}
// IJ.error(metadata.getStateStr());
}
else if (type.equals(ScannerIOMetadata.EXCEPTION)) {
IJ.error(metadata.getException().toString());
}
}
public void stop(){ // execute before System.exit
if(scanner!=null){ // make sure user waits for scanner to finish!
scanner.waitToExit();
ts.setCancel(true);
try {
scanner.setCancel(true);
} catch (ScannerIOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm not an expert, but when ScannerIOMetadata.STATECHANGE shouldn't you check if the scanning is complete?
And if it is you should initialize the scanner again.
Something like that:
if (metadata.isFinished())
{
twainScanner = (TwainScanner) Scanner.getDevice();
}
Related
I know there are already lot of thread available for this topic. I have already visited almost all of em, this one, this one, this one, also this one and this one.But didn't solve my issue.
My problem is different over here when I try to restore the JFrame it blinks, and didn't come on top of everything. I have already run this code in Ubuntu and it worked like a charm on ubuntu. frame.setAlwaysOnTop(true); works absolutely fine on ubuntu.
To solve this issue in windows I tried to use WindowsListener,
But in windows 7 it blinks and didn't come on top of every windows. What I think is that it's trying to come on top of everything but may be other application has higher priority than this it goes away. How can I resolve this issue ?
EDIT :
I have two thread over here one thread is authenticating and if it's authenticated it minimized. If not authenticated it should always be on top for authenticating. Even if user switches window by pressing Alt key tab it should again come on top after 2 seconds.
Code for authentication :
public class ScreenLockAndUnlock implements Runnable{
public static JFrame frame;
public static boolean working = false;
private JTextField punch;
public void stop(){
working = false;
}
public void run(){
try{
frame = new JFrame("Protected");
frame.setContentPane(new JLabel(new ImageIcon("C:\\Users\\four.four-PC\\eclipse-workspace\\optimization\\src\\main\\java\\com\\greycode\\optimization\\finger_PNG6297.png")));
frame.setVisible(true);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
gs.setFullScreenWindow(frame);
frame.validate();
frame.setLayout(new BorderLayout());
punch = new JTextField();
frame.add(punch,BorderLayout.SOUTH);
punch.requestFocus();
punch.addActionListener(action);
}finally{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
private void onTop() throws AWTException{
// TODO Auto-generated method stub
AlwaysOnTop top = new AlwaysOnTop();
new Thread(top).start();
while(true){
try{
frame.setState(Frame.NORMAL);
if(punch.getText().trim()!= null && punch.getText().trim().toLowerCase().equals("true")){
working = true;
top.cancel();
frame.setState(JFrame.ICONIFIED);
Thread.sleep(10000);
top.star();
top = new AlwaysOnTop();
new Thread(top).start();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
#SuppressWarnings("serial")
Action action = new AbstractAction(){
public void actionPerformed(ActionEvent e){
try{
onTop();
} catch (AWTException e1){
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
}
This code always look for whether JFrame is on top or not if not authenticated
public class AlwaysOnTop implements Runnable{
boolean cancelled = false;
public void run(){
while(!cancelled){
try{
lookForMinimised();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void cancel(){
this.cancelled = true;
}
public void star(){
this.cancelled = false;
}
public void lookForMinimised() throws InterruptedException{
// TODO Auto-generated method stub
ScreenLockAndUnlock.frame.addWindowStateListener(new WindowStateListener(){
public void windowStateChanged(WindowEvent e){
// TODO Auto-generated method stub
int newState = e.getNewState();
if((newState & Frame.ICONIFIED) == Frame.ICONIFIED){
System.out.println("Frame is minimised");
ScreenLockAndUnlock.frame.setAlwaysOnTop(false);
ScreenLockAndUnlock.frame.setAlwaysOnTop(true);
ScreenLockAndUnlock.frame.setVisible(true);
ScreenLockAndUnlock.frame.toFront();
ScreenLockAndUnlock.frame.requestFocus();
ScreenLockAndUnlock.frame.validate();
ScreenLockAndUnlock.frame.setState(Frame.NORMAL);
}
else if ((newState & Frame.NORMAL) == Frame.NORMAL){
System.out.println("Waiting for authentication ...");
}
}
});
Thread.sleep(2000);
}
}
Main method:
public class Authenticate{
public static void main(String[] args){
Thread displayScreen = new Thread(new ScreenLockAndUnlock());
displayScreen.start();
}
}
Please find a code which depicts the logical functionality that you want.
Also note that this code just depicts the functionality only which are frame restore-minimize, thread and their inter-working.
At the end, it will be you, who have to use the same at appropriate locations as per your need.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Frame;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
public class TestClass2 extends JFrame {
private JPanel contentPane;
private JTextField textField;
static boolean isAuthenticationStarted = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestClass2 frame = new TestClass2();
frame.setVisible(true);
frame.addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent e) {
// minimized
if ((e.getNewState() & Frame.ICONIFIED) == Frame.ICONIFIED){
if (!isAuthenticationStarted)
{
// Authentication not started yet and window minimized
frame.setState(Frame.NORMAL);
}
}
// // maximized
// else if ((e.getNewState() & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH){
//
// }
}
});
frame.setAlwaysOnTop(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestClass2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER)
{
new Thread()
{
public void run()
{
// Start authentication here
isAuthenticationStarted = true;
// if authentication is success show next jframe
// else restore window
// reset the flag only when authentication is successful
// isAuthenticationStarted = false;
// Minimizing frame
setState(Frame.ICONIFIED);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// restoring frame
setState(Frame.NORMAL);
}
}.start();
}
}
});// End listener
contentPane.add(textField, BorderLayout.CENTER);
textField.setColumns(10);
}
}
Hope this will help you. :-)
i have a problem trying to stop my Timer. I have two different classes, the first contains the button that starts and stop the button and the second is the chrono class. Here is the button:
btnStopstart = new JButton("START");
btnStopstart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
Chrono1 cn = new Chrono1(chrono);
String texte = btnStopstart.getText();
if(texte.equals("START")){
btnStopstart.setText("STOP");
try {
cn.Editchrono(texte);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else if(texte.equals("STOP")){
btnStopstart.setText("START");
cn.Editchrono(texte);
}
}
});
And here is the chrono class:
public class Chrono1 {
private static int sec;
private JTextField chrono;
public Chrono1(JTextField chrono){
this.chrono = chrono;
}
public void Editchrono(String txt){
/* Le timer */
int delais=1000;
ActionListener tache_timer;
tache_timer = new ActionListener(){
public void actionPerformed(ActionEvent e){
sec++;
if(sec == 15 ){
//Conditions
}
if(sec == 16){
/*On realise une pause de 1 sec */
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//mettre les conditions ici
sec = 0;
}
//System.out.println(sec);
chrono.setText("" + sec);
}
};
final Timer timer1= new Timer(delais,tache_timer);
if(txt.equals("START")){
timer1.start();
}else if(txt.equals("STOP")){
timer1.stop();
//sec = 0;
}
}
}
Thank you for the help.
You're calling stop() on a Swing Timer all right, but not on the Timer instance that's running. Rather you're calling stop() on a completely new Timer instance, one that's not even running, and one that is completely unrelated to the Timer that is in fact running. You need to give the Chrono1 class a Timer field, say called timer, set this field to reference the running Timer when it starts, and call stop on this field (if not null) when stop is called. You also need to create one and only one Chrono1 object.
e.g.,
public class Chrono1 {
private static int sec;
private JTextField chrono;
private Timer timer1; // ***** added ***
public Chrono1(JTextField chrono){
this.chrono = chrono;
}
public void Editchrono(String txt){
int delais=1000;
ActionListener tache_timer;
tache_timer = new ActionListener(){
public void actionPerformed(ActionEvent e){
// .... etc.....
}
};
if(txt.equals("START")) {
// **** note changes? ****
// final Timer timer1= new Timer(delais,tache_timer); // ** no **
timer1= new Timer(delais,tache_timer); // ** yes! **
timer1.start();
}else if(txt.equals("STOP")){
if (timer1 != null && timer1.isRunning()) {
timer1.stop();
}
//sec = 0;
}
}
}
Also this guy shouldn't be re-created:
Chrono1 cn = new Chrono1(chrono);
And so this should be a private instance field of either the whole class or of the inner ActionListener class and not re-created with each button push.
e.g., make the changes below:
btnStopstart.addActionListener(new ActionListener(){
private Chrono1 cn = new Chrono1(chrono); // **** add this
public void actionPerformed(ActionEvent e) {
// Chrono1 cn = new Chrono1(chrono); // **** remove this
String texte = btnStopstart.getText();
if(texte.equals("START")){
btnStopstart.setText("STOP");
try {
cn.Editchrono(texte);
} catch (Exception e1) {
e1.printStackTrace();
}
} else if(texte.equals("STOP")) {
btnStopstart.setText("START");
cn.Editchrono(texte);
}
}
});
I am currently working on a small application to display/save notes. The content of each note is stored inside a .properties file on my hard drive after closing the application. If you open the application again then all notes are loading inside the application.
While this loading process is taking place, I show a dialog box with a progressbar that indicates the state of the process. Furthermore, I display a GlassPane so the user can’t interact with the GUI or crate/save notes while loading.
Following is my current Code for loading the notes:
public void load() {
new Thread() {
#Override
public void run() {
Properties data = new Properties();
FileInputStream iStream = null;
File[] files = sortPairs();
int fileIndex = -1;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
pnlGlass = new MyGlassPane();
infoText = new JTextField();
progBar = new JProgressBar(0,100);
progBar.setValue(0);
progBar.setStringPainted(true);
infoBox = new LoadInfoDialog(infoText,progBar);
infoBox.setLocationRelativeTo(gui);
infoBox.setVisible(true);
infoBox.setDefaultCloseOperation(infoBox.DO_NOTHING_ON_CLOSE);
pnlGlass.setOpaque(false);
pnlGlass.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent me) {
me.consume();
}
});
gui.setGlassPane(pnlGlass);
pnlGlass.setVisible(true);
pnlGlass.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
});
for (File file : files) {
if (file.isFile()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
iStream = new FileInputStream(file);
data.load(iStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (!(iStream == null)) {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String title = data.getProperty("title");
String text = data.getProperty("text");
String erstellt = data.getProperty("date");
String fileName = data.getProperty("filename");
Note note = new Note(text, title);
note.setFileName(fileName);
note.setDate(erstellt);
fileIndex++;
final int fileIndexFinal = fileIndex;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
progBar.setValue(progBar.getValue() + 100 / fileCount);
infoText.setText("Lade Notizen, bitte warten..." + progBar.getValue() + "%");
noteModel.addNote(note);
System.out.println("Index:" + fileIndexFinal);
}
});
}
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
pnlGlass.setVisible(false);
infoBox.setVisible(false);
}
});
}
}.start();
}
I am sure that my solution is pretty ragged. After some research I figured that there is a class called "SwingWorker" for exactly this purpose (running Taks in background and update gui) BUT, how can I create my note (add Note-Object to my Model) from within the SwingWorker?
I know that I can update my progressbar using the publish and process methods but how can I create an object using the SwingWorker?
The loading process should do the following routine for every note:
Read content from .properties file -> create note Object -> show note in JList -> update progressbar.
Start by defining your core worker...
public class NotesLoader extends SwingWorker<List<Properties>, Properties> {
#Override
protected List<Properties> doInBackground() throws Exception {
List<Properties> notes = new ArrayList<>(25);
File[] files = new File(".").listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".properties");
}
});
for (File file : files) {
int count = 0;
try (Reader reader = new FileReader(file)) {
Properties note = new Properties();
note.load(reader);
notes.add(note);
publish(note);
setProgress((int) ((count / (double) files.length) * 100d));
}
}
return notes;
}
}
This simple scans the current working directory for .properties files and tries to load them one at a time. When one is loaded, it is sent via the publish method and the progress is updated via the setProgress method.
Now, I devised a simple progress panel which looks like this...
public class LoadingPane extends JPanel {
private JLabel label;
private JProgressBar pb;
public LoadingPane() {
setLayout(new GridBagLayout());
setOpaque(false);
label = new JLabel("Loading, please wait");
pb = new JProgressBar();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(label, gbc);
add(pb, gbc);
addMouseListener(new MouseAdapter() {
});
setFocusable(true);
}
public void setProgress(float progress) {
pb.setValue((int) (progress * 100f));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(128, 128, 128, 128));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
}
}
This is important, as it has a setProgress method
Now, we can use these two together to load the notes in the background and update the UI safely as the progress updates.
LoadingPane loadingPane = new LoadingPane();
JFrame frame = new JFrame("Testing");
frame.setGlassPane(loadingPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel("I'll wait here okay"));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
NotesLoader loader = new NotesLoader() {
#Override
protected void process(List<Properties> chunks) {
System.out.println(chunks.size() + " notes were loaded");
// Update you model??
}
};
loader.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
String name = evt.getPropertyName();
switch (name) {
case "state":
switch (loader.getState()) {
case STARTED:
frame.getGlassPane().setVisible(true);
frame.getGlassPane().requestFocusInWindow();
break;
case DONE:
frame.getGlassPane().setVisible(false);
try {
// Doubt your need the list, but it's good to do this
// incase there was an exception which occured during
// the running of the worker
List<Properties> notes = loader.get();
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
// Maybe show an error message...
}
break;
}
break;
case "progress":
// I like working with normalised values :P
loadingPane.setProgress(((int)evt.getNewValue() / 100f));
break;
}
}
});
The example overrides the process method, so you can get the notes as they are loaded, but equally, you could wait till the state changes to DONE and get them all at once, it's up to you
I have an application I'm making for a game to automatically update a game client.
Once you press Launch, it will open up my DownloadFrame (extends JDialog), and will look like this:
If you click the icon for the application in the taskbar, (maybe Windows 8 is the problem?) it will minimize the application like usual. However when you go to maximise the application again, the JDialog will be hidden, I'm assuming, behind the parent. It looks like this:
Here's my code for my extension of JDialog. Apologies in advance for it being messy.
public class DownloadFrame extends JDialog implements Runnable {
private static final long serialVersionUID = -8764984599528942303L;
private Background frame;
private ImageIcon[] gifs;
private JLabel spinner;
public DownloadFrame() {
super(Loader.application, false);
setLayout(null);
setUndecorated(true);
setAutoRequestFocus(true);
new Thread(this).start();
generateBackground();
generateButton();
generateGif();
}
private void generateBackground() {
frame = new Background("sub_background.png");
setSize(frame.getWidth(), frame.getHeight());
setBackground(new Color(1.0f, 1.0f, 1.0f, 0.0f));
setLocationRelativeTo(null);
setLocation(this.getX(), this.getY() + 5);
setLayout(null);
setContentPane(frame);
}
private void generateGif() {
gifs = Utils.generateGifImages();
spinner = new JLabel(gifs[0]);
spinner.setBounds(70, 30, gifs[0].getIconWidth(), gifs[0].getIconHeight());
add(spinner);
}
private HoverableButton cancel;
public HoverableButton getCancelButton() {
return cancel;
}
private void generateButton() {
cancel = new HoverableButton(Settings.CANCEL_BUTTON, 75, 145);
cancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
/*
* TODO -
* stop the download in progress
*/
for (HoverableButton button : Loader.application.getPrimaryButtons()) {
button.setActive(true);
button.setVisible(true);
}
dispose();
}
});
add(cancel);
}
private int cycleCount;
private void cycleGif() {
if (spinner == null) {
return;
}
cycleCount++;
if (cycleCount > 7) {
cycleCount = 0;
}
spinner.setIcon(gifs[cycleCount]);
}
#Override
public void run() {
while (true) {
cycleGif();
try {
Thread.sleep(100L);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
In case it's needed, here's my usage of it. Most of the stuff can be ignored I'm sure, it's simply there to hide the four buttons while the download is in progress.
((HoverableButton) components[2]).addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
HoverableButton source = (HoverableButton) components[2];
if (source.isActive()) {
try {
Thread.sleep(500L);
} catch (Exception ex) {
ex.printStackTrace();
}
if (panel == null) {
panel = new DownloadFrame();
panel.setVisible(true);
} else {
panel.setVisible(true);
panel.getCancelButton().removeHighlight();
}
for (HoverableButton button : getPrimaryButtons()) {
button.setActive(false);
button.setVisible(false);
button.removeHighlight();
}
/*
* TODO -
* handle checking for updates / downloading updates
*/
}
}
});
However when you go to maximise the application again, the JDialog will be hidden, I'm assuming, behind the parent
Yes. When you create the JDialog, you need to specify the "owner" JFrame of the dialog in the constructor.
So you must create and make the JFrame and make the frame visible before you create the dialog.
My java Web Browser app doesn't show the web pages from Internet like:
http://www.google.com
when entering the correct url and finally it shows the exception provided as
Unable to load page
What is the problem inside my application code?
please help me to find out and fix the problem.
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.html.*;
// The Mini Web Browser.
public class MiniBrowser extends JFrame
implements HyperlinkListener
{
// These are the buttons for iterating through the page list.
private JButton backButton, forwardButton;
// Page location text field.
private JTextField locationTextField;
// Editor pane for displaying pages.
private JEditorPane displayEditorPane;
// Browser's list of pages that have been visited.
private ArrayList pageList = new ArrayList();
// Constructor for Mini Web Browser.
public MiniBrowser()
{
// Set application title.
super("Mini Browser");
// Set window size.
setSize(640, 480);
// Handle closing events.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
actionExit();
}
});
// Set up file menu.
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem fileExitMenuItem = new JMenuItem("Exit",
KeyEvent.VK_X);
fileExitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionExit();
}
});
fileMenu.add(fileExitMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Set up button panel.
JPanel buttonPanel = new JPanel();
backButton = new JButton("< Back");
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionBack();
}
});
backButton.setEnabled(false);
buttonPanel.add(backButton);
forwardButton = new JButton("Forward >");
forwardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionForward();
}
});
forwardButton.setEnabled(false);
buttonPanel.add(forwardButton);
locationTextField = new JTextField(35);
locationTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
actionGo();
}
}
});
buttonPanel.add(locationTextField);
JButton goButton = new JButton("GO");
goButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionGo();
}
});
buttonPanel.add(goButton);
// Set up page display.
displayEditorPane = new JEditorPane();
displayEditorPane.setContentType("text/html");
displayEditorPane.setEditable(false);
displayEditorPane.addHyperlinkListener(this);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(buttonPanel, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(displayEditorPane),
BorderLayout.CENTER);
}
// Exit this program.
private void actionExit() {
System.exit(0);
}
// Go back to the page viewed before the current page.
private void actionBack() {
URL currentUrl = displayEditorPane.getPage();
int pageIndex = pageList.indexOf(currentUrl.toString());
try {
showPage(
new URL((String) pageList.get(pageIndex - 1)), false);
}
catch (Exception e) {}
}
// Go forward to the page viewed after the current page.
private void actionForward() {
URL currentUrl = displayEditorPane.getPage();
int pageIndex = pageList.indexOf(currentUrl.toString());
try {
showPage(
new URL((String) pageList.get(pageIndex + 1)), false);
}
catch (Exception e) {}
}
// Load and show the page specified in the location text field.
private void actionGo() {
URL verifiedUrl = verifyUrl(locationTextField.getText());
if (verifiedUrl != null) {
showPage(verifiedUrl, true);
} else {
showError("Invalid URL");
}
}
// Show dialog box with error message.
private void showError(String errorMessage) {
JOptionPane.showMessageDialog(this, errorMessage,
"Error", JOptionPane.ERROR_MESSAGE);
}
// Verify URL format.
private URL verifyUrl(String url) {
// Only allow HTTP URLs.
if (!url.toLowerCase().startsWith("http://"))
return null;
// Verify format of URL.
URL verifiedUrl = null;
try {
verifiedUrl = new URL(url);
} catch (Exception e) {
return null;
}
return verifiedUrl;
}
/* Show the specified page and add it to
the page list if specified. */
private void showPage(URL pageUrl, boolean addToList)
{
// Show hour glass cursor while crawling is under way.
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
// Get URL of page currently being displayed.
URL currentUrl = displayEditorPane.getPage();
// Load and display specified page.
displayEditorPane.setPage(pageUrl);
// Get URL of new page being displayed.
URL newUrl = displayEditorPane.getPage();
// Add page to list if specified.
if (addToList) {
int listSize = pageList.size();
if (listSize > 0) {
int pageIndex =
pageList.indexOf(currentUrl.toString());
if (pageIndex < listSize - 1) {
for (int i = listSize - 1; i > pageIndex; i--) {
pageList.remove(i);
}
}
}
pageList.add(newUrl.toString());
}
// Update location text field with URL of current page.
locationTextField.setText(newUrl.toString());
// Update buttons based on the page being displayed.
updateButtons();
}
catch (Exception e)
{
// Show error messsage.
showError("Unable to load page");
}
finally
{
// Return to default cursor.
setCursor(Cursor.getDefaultCursor());
}
}
/* Update back and forward buttons based on
the page being displayed. */
private void updateButtons() {
if (pageList.size() < 2) {
backButton.setEnabled(false);
forwardButton.setEnabled(false);
} else {
URL currentUrl = displayEditorPane.getPage();
int pageIndex = pageList.indexOf(currentUrl.toString());
backButton.setEnabled(pageIndex > 0);
forwardButton.setEnabled(
pageIndex < (pageList.size() - 1));
}
}
// Handle hyperlink's being clicked.
public void hyperlinkUpdate(HyperlinkEvent event) {
HyperlinkEvent.EventType eventType = event.getEventType();
if (eventType == HyperlinkEvent.EventType.ACTIVATED) {
if (event instanceof HTMLFrameHyperlinkEvent) {
HTMLFrameHyperlinkEvent linkEvent =
(HTMLFrameHyperlinkEvent) event;
HTMLDocument document =
(HTMLDocument) displayEditorPane.getDocument();
document.processHTMLFrameHyperlinkEvent(linkEvent);
} else {
showPage(event.getURL(), true);
}
}
}
// Run the Mini Browser.
public static void main(String[] args) {
MiniBrowser browser = new MiniBrowser();
browser.show();
}
}
It appears that showPage() gets called before a url is entered which causes a NullPointerException to get thrown. So you may want to change when/how showPage() gets called and/or add some additional null checks to showPage(). Just doing the null checks should do the trick:
private void showPage(URL pageUrl, boolean addToList) {
// Show hour glass cursor while crawling is under way.
if (pageUrl == null) {
return;
}
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
// Get URL of page currently being displayed.
URL currentUrl = displayEditorPane.getPage();
// Load and display specified page.
displayEditorPane.setPage(pageUrl);
// Get URL of new page being displayed.
URL newUrl = displayEditorPane.getPage();
// Add page to list if specified.
if (newUrl != null && addToList) {
int listSize = pageList.size();
if (listSize > 0) {
int pageIndex = pageList.indexOf(currentUrl.toString());
if (pageIndex < listSize - 1) {
for (int i = listSize - 1; i > pageIndex; i--) {
pageList.remove(i);
}
}
}
pageList.add(newUrl.toString());
}
// Update location text field with URL of current page.
if (newUrl != null) {
locationTextField.setText(newUrl.toString());
}
// Update buttons based on the page being displayed.
updateButtons();
} catch (Exception e) {
// Show error messsage.
e.printStackTrace();
showError("Unable to load page");
} finally {
// Return to default cursor.
setCursor(Cursor.getDefaultCursor());
}
}