Java exe won't display specific jframe but IDE will - java

I've created a mini quiz game in java and wanted to convert it to an exe..It has photos and sounds attached to it but they are in their respective folders and with the correct paths. When i click on "Insert a new question" the exe works fine, the same thing happens for the "exit" option. But when i click "Play" no window pops up but i don't get an error either..
I tried placing the photos and sounds in the same folder as the class that uses them but it didn't fix the problem. I also tried inserting ".." at the beginning of the URL paths but it didn't fix it either. I've attached the code for the not showing frame.
ArrayList<Question> questions;
int selectedQuestion = 0;
int remainingLife = 3;
Random random = new Random();
int fillAnswer = 0;
String [] answerArray = new String[4];
Clip clipSuccess;
Clip clipFailure;
Clip clipGameOver;
public static Mixer mixer;
public static Clip clip;
javax.swing.Timer timer = new javax.swing.Timer(1000, new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
timer.stop();
jLabel5.setIcon(null);
playRound();
}
});
public PlayGame() {
initComponents();
questions = new ArrayList<Question>();
populateArrayList();
clipSuccess = setSound("../Sounds/success.wav");
clipFailure = setSound("../Sounds/failure.wav");
clipGameOver = setSound("../Sounds/gameOver.wav");
playRound();
}
public void populateArrayList(){
try{
FileInputStream file = new FileInputStream("Questions.dat");
ObjectInputStream inputFile = new ObjectInputStream(file);
boolean endOfFile = false;
while(!endOfFile){
try{
questions.add((Question) inputFile.readObject());
}
catch(EOFException e){
endOfFile = true;
}
catch(Exception f){
JOptionPane.showMessageDialog(null, f.getMessage());
}
}
inputFile.close();
}
catch(IOException e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
public Clip setSound(String soundPath){
Mixer.Info[] mixInfos = AudioSystem.getMixerInfo();
/*for(Mixer.Info info: mixInfos){
System.out.println(info.getName() + "----" + info.getDescription());
}*/
mixer = AudioSystem.getMixer(mixInfos[3]);
DataLine.Info dataInfo = new DataLine.Info(Clip.class, null);
try {
clip = (Clip)mixer.getLine(dataInfo);
}
catch(LineUnavailableException lue){
lue.printStackTrace();
}
try{
URL soundURL = PlayGame.class.getResource(soundPath);
AudioInputStream audioStream = AudioSystem.getAudioInputStream(soundURL);
clip.open(audioStream);
}
catch(LineUnavailableException lue){
lue.printStackTrace();
}
catch(UnsupportedAudioFileException uofe){
uofe.printStackTrace();
}
catch(IOException ioe){
ioe.printStackTrace();
}
return clip;
}
public void successAnswer(){
JOptionPane.showMessageDialog(null, "Απάντησες σωστά!");
jLabel5.setText("");
jLabel5.setIcon(new ImageIcon(PlayGame.class.getResource("../Images/Fireworks-animated.gif")));
clipSuccess.setFramePosition(0);
clipSuccess.start();
timer.start();
}
public void wrongAnswer(){
remainingLife--;
JOptionPane.showMessageDialog(null, "Απάντησες λάθος..");
jLabel5.setText("");
jLabel5.setIcon(new ImageIcon (PlayGame.class.getResource("../Images/failure.gif")));
if (remainingLife == 0){
clipFailure.setFramePosition(0);
clipFailure.start();
timer.start();
JOptionPane.showMessageDialog(null, "Δυστυχώς έχασες..");
clipGameOver.setFramePosition(0);
clipGameOver.start();
do{
try{
Thread.sleep(50);
}
catch(InterruptedException ie){
ie.printStackTrace();
}
}while(clipGameOver.isActive());
System.exit(0);
}
clipFailure.setFramePosition(0);
clipFailure.start();
timer.start();
}
public void playRound(){
selectedQuestion = random.nextInt(questions.size());
jTextField3.setText(Integer.toString(remainingLife));
jTextArea2.setText(questions.get(selectedQuestion).getQuestionName());
for (int i=0; i<4; i++){
fillAnswer = random.nextInt(questions.size());
answerArray[i] = questions.get(fillAnswer).getQuestionAnswer();
if (i==2){
answerArray[i] = questions.get(selectedQuestion).getQuestionAnswer();
continue;
}
}
Collections.shuffle(Arrays.asList(answerArray));
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(answerArray));
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int selectedAnswer = jComboBox1.getSelectedIndex();
jLabel5.setIcon(null);
if (questions.get(selectedQuestion).getQuestionAnswer().trim().equals(answerArray[selectedAnswer].trim())){
successAnswer();
}
else{
wrongAnswer();
}
timer.start();
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
In the IDE the output is a jframe with a question, a combo box of 4 answers, the player's life points and two buttons (one for locking the answer and one for exiting the program). But in the exe form it doesn't even pop up.
EDIT - This is the error the wrapper program shows:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/netbeans/lib/awtextra/AbsoluteLayout
at quiz.PlayGame.initComponents(PlayGame.java:277)
at quiz.PlayGame.(PlayGame.java:62)

Related

How I can check when music has ended

I have a JFrame with 2 buttons: Turn On and Turn Off
My problem is when a song has ended, I can't check that it ended and to play it again
How can I check it? Thank you so much
Below is the way that I play sound on Swing
class MP3 {
private Player player;
private String filename;
public MP3(String filename) {
this.filename = filename;
}
public void stop() {
if (player != null)
player.close();
}
public void play() {
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filename));
player = new Player(bis);
} catch (FileNotFoundException | JavaLayerException ex) {
System.out.println(ex);
}
new Thread(new Runnable() {
#Override
public void run() {
try {
player.play();
} catch (Exception ex) {
System.out.println(ex);
}
}
}).start();
}
}
And Event when I click buttons
private void btnPlayActionPerformed(java.awt.event.ActionEvent evt) {
sound = new MP3("src/Sound/02 - Cold Pizza.mp3");
sound.play();
btnPlay.setVisible(false);
btnStop.setVisible(true);
}
private void btnStopActionPerformed(java.awt.event.ActionEvent evt) {
sound.stop();
btnStop.setVisible(false);
btnPlay.setVisible(true);
}
sound is a instance of MP3 class in main class
I did it this way. I made the mp3 file a wav file. Then I made two objects
AudioInputStream songReader;
Clip song;
try{
songReader =
AudioSystem.getAudioInputStream(
getClass().getResource("wally.wav"));
song = AudioSystem.getClip();
song.open(songReader);
}catch (Exception e){
System.out.println("won't work");
}
try{
song.stop();
song.setFramePosition(0);
}catch(Exception e){
System.out.println("Error playing your music");
}
try{
song.start();
song.loop(song.LOOP_CONTINUOUSLY);
}catch(Exception e){
System.out.println("Won't work");
}
This makes it play infinitely, but if you need you can stop it at any point with song.stop(). Hopefully, that will work for you.

Java JNA- Jar application hangs in 32 bit windows system

Here's a screenshot application. Compiled with 1.8 JDK, works perfectly well in 64 bit systems, but lags and hangs in two iterations in 32 bit systems.
Basically this application takes a screenshot using robot class, takes the file name from user which is a URL. Truncates and removes all illegal characters from it and saves it using a save as dialog box with time-stamp as the prefix.
I am using Windows Low Level KeyHook to initiate the screenshot with PrtSc key.
Error in 32 bit systems:
It only takes 2 screenshots and then does not respond when I press PrtSc for the 3rd time. Can JFrame cause any problems, it certainly loads up slow. Should I use any alternate text box than JFrame or is it because I have complied in java 1.8 jdk 64 bit environment, which wont work in lower versions of jdk or 32 bit systems.
public class KeyHook {
private static HHOOK hhk;
private static LowLevelKeyboardProc keyboardHook;
static JFileChooser fileChooser = new JFileChooser();
public static void main(String[] args) {
final User32 lib = User32.INSTANCE;
HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
keyboardHook = new LowLevelKeyboardProc() {
public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
if (nCode >= 0) {
switch(wParam.intValue()) {
case WinUser.WM_KEYUP:
case WinUser.WM_KEYDOWN:
case WinUser.WM_SYSKEYUP:
case WinUser.WM_SYSKEYDOWN:
if (info.vkCode == 44) {
try {
Robot robot = new Robot();
// Capture the screen shot of the area of the screen defined by the rectangle
BufferedImage bi=robot.createScreenCapture(new Rectangle(0,25,1366,744));
JFrame frame = new JFrame();
JFrame.setDefaultLookAndFeelDecorated(true);
frame.toFront();
frame.requestFocus();
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// prompt the user to enter their name
String name = JOptionPane.showInputDialog(frame, "Enter file name");
// frame.pack();
frame.dispose();
String fileName= dovalidateFile(name);
FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG", ".png");
fileChooser.setFileFilter(filter);
fileChooser.setSelectedFile(new File (fileName));
int returnVal = fileChooser.showSaveDialog(null);
if ( returnVal == JFileChooser.APPROVE_OPTION ){
File file = fileChooser.getSelectedFile();
file = validateFile(file);
System.out.println(file);
ImageIO.write(bi, "png", file);
}
}
catch (NullPointerException e1)
{e1.printStackTrace(); }
catch (AWTException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
}
private File validateFile(File file) {
DateFormat dateFormat = new SimpleDateFormat("HH.mm.ss.ddMMMMMyyyy");
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
// System.out.println(dateFormat.format(cal.getTime()));
String filePath = file.getAbsolutePath();
if (filePath.indexOf(".png") == -1) {
filePath += "." + dateFormat.format(cal.getTime()) + ".png";
}
//System.out.println("File Path :" + filePath);
file = new File(filePath);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private String dovalidateFile(String name) {
String input = name.replace("https://www.","");
input = input.replaceAll("http://www.","");
input = input.replaceAll("https://","");
input = input.replace("http://","");
input = input.replace("/?",".");
input = input.replace("/",".");
input = input.replace("|",".") ;
input = input.replace("%",".");
input = input.replace("<",".");
input = input.replace(">",".");
input = input.replaceAll("\\?",".");
input = input.replaceAll("\\*",".");
input = input.replace(":",".");
input = input.replace("\\",".");
input = Character.toUpperCase(input.charAt(0)) + input.substring(1);
return input;
}
};
hhk = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod, 0);
if(!SystemTray.isSupported()){
return ;
}
SystemTray systemTray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage(KeyHook.class.getResource("/images/icon.png"));
//popupmenu
PopupMenu trayPopupMenu = new PopupMenu();
MenuItem close = new MenuItem("Exit");
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
});
trayPopupMenu.add(close);
//setting tray icon
TrayIcon trayIcon = new TrayIcon(image, "captur", trayPopupMenu);
//adjust to default size as per system recommendation
trayIcon.setImageAutoSize(true);
try{
systemTray.add(trayIcon);
}catch(AWTException awtException){
awtException.printStackTrace();
}
int result;
MSG msg = new MSG();
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
if (result == -1) {
System.err.println("error in get message");
break;
}
else {
System.err.println("got message");
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
}
lib.UnhookWindowsHookEx(hhk);
}
}
I don't have any experience with JNA, but there are several things that are wrong about your code - I don't think I got them all, but here are some:
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
quit=true;
}
});
The quit=true will never be reached because your program exit()s before it ever goes there.
2.
new Thread() {
public void run() {
while (!quit) {
try { Thread.sleep(10); } catch(Exception e) { }
}
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
}.start();
doesn't make any sense since quit will never be true. Also spinning on a variable to detect a change will severly slow down your application (espacially with sleep-times of 10 ms). Why not do the unhook in your ActionListener?
3.
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
Here I'm not too sure because I don't have experience with JNA and the windows event system. The method waits for messages sent to the specified window, but since you don't specify any (second parameter is null) I don't think you will ever get one.
For each callback you are creating a new JFrame but at the end of the method you are only hiding it using frame.setVisible(false);. Since it is still referenced from various Swing-classes it will never be garbage-collected. This creates a memory-leak which will slow down your application. You will have to call frame.dispose() to get rid of it.

am I overloading my actionListener? JFileChooser

I am attempting to load a saved file from JFileChooser using an actionListener. Here is a snippet of code.
class chooserListener implements ActionListener{
public void actionPerformed (ActionEvent e)
{
if (e.getSource() instanceof JFileChooser){
JFileChooser openFile = (JFileChooser)e.getSource();
String command = e.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)){
File selectedFile = openFile.getSelectedFile();
loadSavedGame(selectedFile);
System.out.print("clicked open file");
tp.setSelectedIndex(0);
}
else if (command.equals(JFileChooser.CANCEL_SELECTION)) {
System.out.print("tester");
tp.setSelectedIndex(0);
}
}
}
}
chooser.addActionListener(new chooserListener());
public void loadSavedGame(File loadfile) {
int allCells = countCells(loadfile);
setMineGame(allCells);
try {
Scanner loadFile = new Scanner(loadfile);
while (loadFile.hasNextInt()){
for (int i = 0; i < allCells; i++){
mineGame.setCell(i, loadFile.nextInt());
//System.out.print("loading saved game");
}
loadFile.close();
mineGame.repaint();
tp.setSelectedIndex(0);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private int countCells(File countCell) {
int cellCount = 0;
try {
Scanner getCells = new Scanner(countCell);
while (getCells.hasNextInt()){
cellCount++;
}
getCells.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print(cellCount);
return cellCount;
}
public void setMineGame(int cells) {
game.removeAll();
mineGame.setDifficulty(cells);
mineGame = new Board(statusbar, difficulty);
game.add(mineGame, BorderLayout.CENTER);
game.add(statusbar, BorderLayout.SOUTH);
frame.validate();
frame.repaint();
}
public void setDifficulty(int cells){
if(cells == 256){
difficulty = 0;
}
if (cells == 676){
difficulty = 1;
}
else difficulty = 2;
}
I feel like I have too many methods for the action listener to do. It is hanging when I click 'open', and the test print line 'System.out.print("clicked open file");' does not print. the rest of my code is really large and I'm not sure how to to an SSCE(?). I'm wondering if anyone can see why my actionListener is hanging? thanks IA
It seems like loadSavedGame(File file) takes a lot of time to execute. As this method is running in the Event Dispatch Thread you feel like your program is hanging and never reaches System.out.print("clicked open file"); line. I'd start testing the time of response for this method in a separate test case
Anyway I'd suggest you a few tips:
1) Note there's no need to implement an ActionListener to do your code. You can simple make this:
JFileChooser chooser = new JFileChooser();
int returnValue = chooser.showOpenDialog(null);
if(returnValue == JFileChooser.APPROVE_OPTION){
//make stuff if approved
} else if(returnValue == JFileChooser.CANCEL_OPTION){
//make stuff if canceled
}
I think it makes people life easier.
2) On the other hand note you have two I/O operations: getting the cells count through countCells(File countCell) method and getting the cells themselves inside loadSavedGame(File loadfile) method. You can do it better reading the file just once:
public List<Integer> getCells(File file){
List<Integer> list = new ArrayList<>();
try {
Scanner getCells = new Scanner(file);
while (getCells.hasNextInt()){
list.add(Integer.valueOf(getCells.nextInt()));
}
getCells.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
return list;
}
}
And make this change in loadSavedGame method:
public void loadSavedGame(File loadfile) {
List<Integer> allCells = getCells(loadfile);
setMineGame(allCells.size());
int index = 0;
for(Integer value : allCells){
mineGame.setCell(index, value);
index++;
}
mineGame.repaint();
tp.setSelectedIndex(0);
}

How to save desktop application state?

I am creating an editor in java. I would like to know how to save an intermediate state in java?
For Example when user wants to save the changes done on the editor, how could it be done and also should be reloaded later.
Eg. powerpoint application is saved as .ppt or .pptx. Later the same .ppt while could be opened for further editions. I hope I am clear with my requirement.
The Preferences API with user preferences; most recently edited files, per file maybe timestamp + cursor position, GUI settings.
To save the contents of JTextPane you can serialize the DefaultStyledDocument of JTextPane in a file using proper way of serialization. And when you want to load the content again you can deserialize the same and display it on the JTextPane . Consider the code given below:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SaveEditor extends JFrame implements ActionListener{
public static final String text = "As told by Wikipedia\n"
+"Java is a general-purpose, concurrent, class-based, object-oriented computer programming language."
+ "It is specifically designed to have as few implementation "
+ "dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), "
+ "meaning that code that runs on one platform does not need to be recompiled to run on another. "
+ "Java applications are typically compiled to bytecode (class file) that can run on any Java virtual "
+ "machine (JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming "
+ "languages in use, particularly for client-server web applications, with a reported 10 million users.";
JTextPane pane ;
DefaultStyledDocument doc ;
StyleContext sc;
JButton save;
JButton load;
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
SaveEditor se = new SaveEditor();
se.createAndShowGUI();
}
});
} catch (Exception evt) {}
}
public void createAndShowGUI()
{
setTitle("TextPane");
sc = new StyleContext();
doc = new DefaultStyledDocument(sc);
pane = new JTextPane(doc);
save = new JButton("Save");
load = new JButton("Load");
JPanel panel = new JPanel();
panel.add(save);panel.add(load);
save.addActionListener(this);load.addActionListener(this);
final Style heading2Style = sc.addStyle("Heading2", null);
heading2Style.addAttribute(StyleConstants.Foreground, Color.red);
heading2Style.addAttribute(StyleConstants.FontSize, new Integer(16));
heading2Style.addAttribute(StyleConstants.FontFamily, "serif");
heading2Style.addAttribute(StyleConstants.Bold, new Boolean(true));
try
{
doc.insertString(0, text, null);
doc.setParagraphAttributes(0, 1, heading2Style, false);
} catch (Exception e)
{
System.out.println("Exception when constructing document: " + e);
System.exit(1);
}
getContentPane().add(new JScrollPane(pane));
getContentPane().add(panel,BorderLayout.SOUTH);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == save)
{
save();
}
else if (evt.getSource() == load)
{
load();
}
}
private void save()//Saving the contents .
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Save");
int returnVal = chooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file != null)
{
FileOutputStream fos = null;
ObjectOutputStream os = null;
try
{
fos = new FileOutputStream(file);
os = new ObjectOutputStream(fos);
os.writeObject(doc);
JOptionPane.showMessageDialog(this,"Saved successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (Exception ex){}
}
if (os != null)
{
try
{
os.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
private void load()//Loading the contents
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Open");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file!= null)
{
FileInputStream fin = null;
ObjectInputStream ins = null;
try
{
fin = new FileInputStream(file);
ins = new ObjectInputStream(fin);
doc = (DefaultStyledDocument)ins.readObject();
pane.setStyledDocument(doc);
JOptionPane.showMessageDialog(this,"Loaded successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fin != null)
{
try
{
fin.close();
}
catch (Exception ex){}
}
if (ins != null)
{
try
{
ins.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}

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