Java open one instance of JInternalFrame only - java

I am creating an inventory system using java but I am having problem in displaying only one JInternalFrame in my application. I put a condition that will validate if the JInternalFrame is already visible or not and it's working but the problem is that the first clicked doesn't display anything only after the succeeding clicks. Here is my code for calling the JInternalFrame class:
private Planning pFrame;
private void firstWindow()
{
if(pFrame == null)
{
pFrame = new Planning();
Dimension desktopSize = desktop.getSize();
pFrame.setSize(desktopSize);
pFrame.moveToFront();
pFrame.setVisible(true);
desktop.add(pFrame);
try{
pFrame.setMaximum(true);
}catch(Exception e){}
System.out.println("Clicked");
}
if(pFrame.isVisible())
{
pFrame.setVisible(false);
}
else
{
pFrame.setVisible(true);
}
}

After code and try for several hours I found my answer and this is my code that works:
private void firstWindow()
{
if(pFrame == null)
{
pFrame = new Planning();
Dimension desktopSize = desktop.getSize();
pFrame.setSize(desktopSize);
desktop.add(pFrame);
pFrame.setVisible(true);
pFrame.moveToFront();
try{
pFrame.setMaximum(true);
pFrame.setSelected(true);
}catch(Exception e){}
}
else if(!pFrame.isVisible())
{
pFrame.setVisible(true);
pFrame.moveToFront();
}
if(iFrame.isVisible())
{
desktop.remove(iFrame);
iFrame = null;
}
}
private void secondWindow()
{
if(iFrame == null)
{
iFrame = new Inventory();
Dimension desktopSize = desktop.getSize();
iFrame.setSize(desktopSize);
desktop.add(iFrame);
iFrame.setVisible(true);
iFrame.moveToFront();
try{
iFrame.setMaximum(true);
iFrame.setSelected(true);
}catch(Exception e){}
}
else if(!iFrame.isVisible())
{
iFrame.setVisible(true);
iFrame.moveToFront();
}
if(pFrame.isVisible())
{
desktop.remove(pFrame);
pFrame = null;
}
}
Note: I also found a way to close the previous frame when you open other frame class..
And in my internal frame I put this code to make its visibility to false if user clicks the close button.
setDefaultCloseOperation(this.HIDE_ON_CLOSE);
Thanks to the people who helped...

Related

How to check if a JFrame is open by checking it's one of the components are visible

I have this code sample in a separate jDialog (jDialog is in the same package as that of JFrame) which used to check (using a Thread) if the jCheckBox1 in the jFrame is whether visible or not. JDialog is set to visible by clicking a JLabel (Change Password) in JFrame. I have not set the visibility of the JFrame even to false even after I click on the Change Password JLabel.
The problem I encountered is that even if the JFrame is not visible i.e when I run the JDialog separately (without clicking on the Change Password JLabel) it prints the "Visible" and I'm more than sure that the jFrame is not visible and not running.
This is the code snippet (Thread) I have used to check the visibility of the JFrame's jCheckBox1:
LockOptions lock = new LockOptions();
private void setLocation2() {
new Thread() {
public void run() {
boolean running = true;
while (running) {
try {
Thread.sleep(1000);
if (lock.jCheckBox1.isVisible()) {
System.out.println("Visible");
} else {
System.out.println("Not Visible");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
And this is the Code I have written in JFrame's Change Password JLabel:
private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {
Container c = new ChangePassword(this, rootPaneCheckingEnabled);
if (!c.isShowing()) {
c.setVisible(true);
hideMeToSystemTray();
this.requestFocusInWindow();
}
}
But when I run the JDialog separately (without clicking on the Change Password JLabel) it prints the "Visible"
I have attached a Screenshots of both JFrame and JDialog
JFrame containing jCheckBox1
JDialog:
OK, let's have the simplest possible example.
The following code creates a main frame having a button to create a new frame of class LockOptionsWindow, which extends JFrame.
The class FrameDemo implements Runnable. So can it be accessed on the event dispatching thread using SwingUtilities.invokeLater as mentioned in Swing's Threading Policy. So it is possible creating a new thread checklockoptionswindow which then can check whether the new window created by the button is visible or not visible.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameDemo extends WindowAdapter implements ActionListener, Runnable {
private LockOptionsWindow lockoptionswindow;
private Thread checklockoptionswindow = new Thread();
private void showLockOptionsWindow() {
if (lockoptionswindow != null && lockoptionswindow.isDisplayable()) {
lockoptionswindow.setVisible(true);
lockoptionswindow.setExtendedState(Frame.NORMAL);
} else {
lockoptionswindow = new LockOptionsWindow();
lockoptionswindow.setSize(new Dimension(300, 100));
lockoptionswindow.setVisible(true);
lockoptionswindow.setExtendedState(Frame.NORMAL);
}
}
private void startCheckLockOptionsWindow() {
if (!checklockoptionswindow.isAlive()) {
checklockoptionswindow = new Thread() {
public void run() {
boolean running = true;
while (running) {
try {
Thread.sleep(1000);
if (lockoptionswindow.isVisible()) {
if (lockoptionswindow.getExtendedState() == Frame.ICONIFIED) {
System.out.println("Visible iconified");
} else {
System.out.print("Visible on screen ");
int x = lockoptionswindow.getLocation().x;
int y = lockoptionswindow.getLocation().y;
System.out.println("at position " + x + ", " + y);
}
} else {
System.out.println("Not Visible");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
checklockoptionswindow.start();
}
}
public void actionPerformed(ActionEvent e) {
showLockOptionsWindow();
startCheckLockOptionsWindow();
}
public void run() {
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Show LockOptions frame");
button.addActionListener(this);
Container contentPane = frame.getContentPane();
contentPane.add(button);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new FrameDemo());
}
class LockOptionsWindow extends JFrame {
public LockOptionsWindow() {
super("LockOptions frame");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
}
Edited to determine whether the LockOptionsWindow is visible iconified only or is really showed as window on the screen.

How to update look and feel clean seperate in a class?

I want to update my look and feel by JRadioButtonMenuItem. And I searching in Stackoverflow but what I find was a big bunch of code in 1 class. For me as a beginner its easier to seperate function in a special class.
That is my Frame-Class.
public class CalenderFrame extends JFrame {
public CalenderFrame() throws HeadlessException {
createFrame();
}
public void createFrame() {
setJMenuBar(CalenderMenuBar.getInstance().createMenu());
setTitle("Calender");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400, 300));
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
And that is my MenueBar Class. I just give a short one of Code that is specific for this question. This class is an Singleton.
public JMenuBar createMenu() {
JMenu lookAndFeelMenu = new JMenu("Look & Feel");
JRadioButtonMenuItem lAndFWindowsItem = new JRadioButtonMenuItem("Windows",true);
lAndFWindowsItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == lAndFWindowsItem) {
lAndFAction(1);
}
}
});
JRadioButtonMenuItem lAndFMetalItem = new JRadioButtonMenuItem("Metal",false);
lAndFMetalItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == lAndFMetalItem) {
lAndFAction(2);
}
}
});
JRadioButtonMenuItem lAndFMotifItem = new JRadioButtonMenuItem("Motif", false);
lAndFMotifItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == lAndFMotifItem) {
lAndFAction(3);
}
}
});
ButtonGroup group = new ButtonGroup();
group.add(lAndFWindowsItem);
group.add(lAndFMetalItem);
group.add(lAndFMotifItem);
lookAndFeelMenu.add(lAndFWindowsItem);
lookAndFeelMenu.add(lAndFMetalItem);
lookAndFeelMenu.add(lAndFMotifItem);
}
public void lAndFAction(int counter) {
try {
String plaf = "";
if (counter == 1) {
plaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
} else if (counter == 2) {
plaf = "javax.swing.plaf.metal.MetalLookAndFeel";
} else if (counter == 3) {
plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
}
UIManager.setLookAndFeel(plaf);
//SwingUtilities.updateComponentTreeUI(this);
} catch (UnsupportedLookAndFeelException ue) {
System.err.println(ue.toString());
} catch (ClassNotFoundException ce) {
System.err.println(ce.toString());
} catch (InstantiationException ie) {
System.err.println(ie.toString());
} catch (IllegalAccessException iae) {
System.err.println(iae.toString());
}
}
}
I hope you guys can help me.
I'm not sure what your problem actually is. But, you must update your components after changing the LaF. According to the Look and Feel Documentation:
Changing the Look and Feel After Startup
You can change the L&F with setLookAndFeel even after the program's
GUI is visible. To make existing components reflect the new L&F,
invoke the SwingUtilities updateComponentTreeUI method once per
top-level container. Then you might wish to resize each top-level
container to reflect the new sizes of its contained components. For
example:
UIManager.setLookAndFeel(lnfName);
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
Therefore, you would need a reference to the frame holding the components in your UI. An idea would be doing something like:
public class CalendarMenuBar {
// Add this field to tour factory
private static JFrame frameThatWillBeUpdated;
// ... (Your code goes here)
// update this method to receive the reference of the frame which will
// need to be refreshed (update the GUI)
public JMenuBar createMenu(JFrame frame) {
// sets the reference for the frame
frameThatWillBeUpdated = frame;
// ... (the rest of your code for this method)
}
// ...
// Update this method to refresh the frame
public void lAndFAction(int counter) {
try{
// ... (your code)
// Set the LaF
UIManager.setLookAndFeel(plaf);
// Update the component tree (frame and its children)
SwingUtilities.updateComponentTreeUI(frameThatWillBeUpdated);
// repack to resize
frame.pack();
} catch(Exception ex){
// Your catches
}
}
}
And here is how you use it when creating your frame (inside your CalenderFrame class):
public void createFrame() {
// use this frame as reference
setJMenuBar(CalenderMenuBar.getInstance().createMenu(this));
// ... (your code goes here)
}

How to run a thread step by step using a jButton

i have a thread running which keeps repainting the maze recursively until the exit is reached. The method below is responsible for repainting the maze.
private void moveFromStep(int x, int y) {
if(step){
if(isWall(x,y))
return ;
if(isVisited(x,y))
return ;
if(isGoal(x,y)){
free = true;
JOptionPane.showMessageDialog(this, "Solution Complete: finish reachable");
}
if(!free){
step = false;
setVisited(x,y);
repaint();
//try {Thread.sleep(3000);} catch (Exception e) { }
//try {wait();} catch (Exception e) { }
moveFromStep(x-1,y);
moveFromStep(x+1,y);
moveFromStep(x,y-1);
moveFromStep(x,y+1);
}
}
}
now i have a JPanel running separately and i want to repaint it step by step.
i want to do this by using a "Step" button. So like the maze is printed step by step when "Step" button is pressed. The code below is the action listener for the buttons
public void actionPerformed(ActionEvent event) {
String action = event.getActionCommand();
MazeStep mazeStep = new MazeStep();
Thread mazeThreadStep = null;
if (action.equals("Load Maze")) {
mazeAnim.readFile(getName());
//mazeStep = new MazeStep();
mazeStep.readFile(getName());
}
else if(action.equals("Start")){
JFrame world = new JFrame();
mazeStep = new MazeStep();
mazeStep.readFile(getName());
world.setSize(300, 300);
world.setTitle("Maze solver");
world.setContentPane(mazeStep);
world.setVisible(true);
mazeThreadStep = new Thread(mazeStep);
mazeThreadStep.start();
}
if(action.equals("Step")){
mazeStep.step = true;
synchronized (mazeThreadStep) {
mazeThreadStep.notify();
}
}
}
So can anyone help me what could be done in order to achieve this plz.

Java Web browser connection issue

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

uk.co.mmscomputing twain scanner

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

Categories