Java Web browser connection issue - java

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

Related

Java FileDialog Save as

I'm working on a project for my Java class, we just have to modify code. I had to add a Save and Save As dialog box to a basic text file document. When I do Save As the first time its fine, but then do save as again but hit cancel it resets the file to null. I have made it so at least the title still stays but when you hit the Save button it acts like its a null file and save as dialog box appears again. I want it so when you cancel Save As, it keeps the previous file instead of going back to null. I'm still formatting it, so its funky
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class JavaEdit extends Frame implements ActionListener {
String clipBoard;
String fileName;
TextArea text;
MenuItem newMI, openMI, saveMI, saveAsMI, exitMI;
MenuItem selectAll, cutMI, copyMI, deleteMI, pasteMI;
MenuItem about;
/**
* Constructor
*/
public JavaEdit() {
super("JavaEdit"); // set frame title
setLayout(new BorderLayout()); // set layout
// create menu bar
MenuBar menubar = new MenuBar();
setMenuBar(menubar);
// create file menu
Menu fileMenu = new Menu("File");
menubar.add(fileMenu);
newMI = fileMenu.add(new MenuItem("New"));
newMI.addActionListener(this);
openMI = fileMenu.add(new MenuItem("Open"));
openMI.addActionListener(this);
fileMenu.addSeparator();
saveMI = fileMenu.add(new MenuItem("Save"));
saveMI.addActionListener(this);
saveAsMI = fileMenu.add(new MenuItem("Save As ..."));
saveAsMI.addActionListener(this);
fileMenu.addSeparator();
exitMI = fileMenu.add(new MenuItem("Exit"));
exitMI.addActionListener(this);
// create edit menu
Menu editMenu = new Menu("Edit");
menubar.add(editMenu);
selectAll = editMenu.add(new MenuItem("Select All"));
selectAll.addActionListener(this);
cutMI = editMenu.add(new MenuItem("Cut"));
cutMI.addActionListener(this);
copyMI = editMenu.add(new MenuItem("Copy"));
copyMI.addActionListener(this);
pasteMI = editMenu.add(new MenuItem("Paste"));
pasteMI.addActionListener(this);
deleteMI = editMenu.add(new MenuItem("Delete"));
deleteMI.addActionListener(this);
Menu helpMenu = new Menu("Help");
menubar.add(helpMenu);
about = helpMenu.add(new MenuItem("About"));
about.addActionListener(this);
// create text editing area
text = new TextArea();
add(text, BorderLayout.CENTER);
}
// implementing ActionListener
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if(source == newMI) {
clearText();
fileName = null;
setTitle("JavaEdit"); // reset frame title
}
else if(source == openMI) {
doOpen();
}
else if (source == saveAsMI) {
doSaveAs();
}
else if (source == saveMI) {
doSave();
}
else if(source == exitMI) {
System.exit(0);
}
else if(source == selectAll) {
doSelect();
}
else if(source == cutMI) {
doCopy();
doDelete();
}
else if(source == copyMI) {
doCopy();
}
else if(source == pasteMI) {
doPaste();
}
else if(source == deleteMI) {
doDelete();
}
else if(source == about){
MessageDialog dialog = new MessageDialog(this, "About",
"JavaEdit in Java, Version 2.0, 2017");
dialog.setVisible(true);
return;
}
}
/**
* method to specify and open a file
*/
private void doOpen() {
// display file selection dialog
FileDialog fDialog = new FileDialog(this, "Open ...", FileDialog.LOAD);
fDialog.setVisible(true);
// Get the file name chosen by the user
String name = fDialog.getFile();
// If user canceled file selection, return without doing anything.
if(name == null)
return;
fileName = fDialog.getDirectory() + name;
// Try to create a file reader from the chosen file.
FileReader reader=null;
try {
reader = new FileReader(fileName);
} catch (FileNotFoundException ex) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
"File Not Found: "+fileName);
dialog.setVisible(true);
return;
}
BufferedReader bReader = new BufferedReader(reader);
// Try to read from the file one line at a time.
StringBuffer textBuffer = new StringBuffer();
try {
String textLine = bReader.readLine();
while (textLine != null) {
textBuffer.append(textLine + '\n');
textLine = bReader.readLine();
}
bReader.close();
reader.close();
} catch (IOException ioe) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
"Error reading file: "+ioe.toString());
dialog.setVisible(true);
return;
}
setTitle("JavaEdit: " +name); // reset frame title
text.setText(textBuffer.toString());
}
private void doSaveAs() {
FileDialog fDialog = new FileDialog(this, "Save As ...", FileDialog.SAVE);
fDialog.setVisible(true);
fileName = fDialog.getFile();
String name = fileName.toString();
setTitle("JavaEdit: " + name); // reset frame title
fDialog.setFile(name);
FileWriter fileCharStream = null; // File stream for writing file
try {
fileCharStream = new FileWriter(fileName); // May throw IOException
// Use file output stream
fileCharStream.write(text.getText());
} catch (IOException excpt) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
fileName);
dialog.setVisible(true);
return;
} finally {
closeFileWriter(fileCharStream); // Ensure file is closed!
}
}
private void doSave() {
if(fileName == null )
{
doSaveAs();
}
FileWriter out = null;
try {
out =new FileWriter(fileName);
out.write(text.getText());
}
catch (IOException excpt) {
MessageDialog dialog = new MessageDialog(this, "Error Message",
fileName);
dialog.setVisible(true);
return;
} finally {
closeFileWriter(out); // Ensure file is closed!
}// Ensure file is closed!
}
static void closeFileWriter(FileWriter fileName) {
try {
if (fileName != null) { // Ensure "file" references a valid object
fileName.close(); // close() may throw IOException if fails
}
} catch (IOException closeExcpt) {
closeExcpt.getMessage();
}
return;
}
private void doSelect() {
text.selectAll();
}
/**
* method to clear text editing area
*/
private void clearText() {
text.setText("");
}
/**
* method to copy selected text to the clipBoard
*/
private void doCopy() {
clipBoard = new String(text.getSelectedText());
}
/**
* method to delete selected text
*/
private void doDelete() {
text.replaceRange("", text.getSelectionStart(), text.getSelectionEnd());
}
/**
* method to replace current selection with the contents of the clipBoard
*/
private void doPaste() {
if(clipBoard != null) {
text.replaceRange(clipBoard, text.getSelectionStart(),
text.getSelectionEnd());
}
}
/**
* class for message dialog
*/
class MessageDialog extends Dialog implements ActionListener {
private Label message;
private Button okButton;
// Constructor
public MessageDialog(Frame parent, String title, String messageString) {
super(parent, title, true);
setSize(400, 100);
setLocation(150, 150);
setLayout(new BorderLayout());
message = new Label(messageString, Label.CENTER);
add(message, BorderLayout.CENTER);
Panel panel = new Panel(new FlowLayout(FlowLayout.CENTER));
add(panel, BorderLayout.SOUTH);
okButton = new Button(" OK ");
okButton.addActionListener(this);
panel.add(okButton);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
dispose();
}
});
}
// implementing ActionListener
public void actionPerformed(ActionEvent event) {
setVisible(false);
dispose();
}
}
/**
* the main method
*/
public static void main(String[] argv) {
// create frame
JavaEdit frame = new JavaEdit();
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(size.width-80, size.height-80);
frame.setLocation(20, 20);
// add window closing listener
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// show the frame
frame.setVisible(true);
}
}
Simply check if the returned file is null:
String name = fDialog.getFile();
// if Cancel is pressed we just exit
if (name == null) {
return;
}
// otherwise we save it
fileName = name;
...

Java open one instance of JInternalFrame only

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...

Why do JButtons that open webpages only work the first time one is clicked and then get deactivated?

I have a set of JButtons, each of which opens a separate YouTube video webpage. When first running the program, I can click on any ONE button and get the video page. When I try to get another video page with a button click, it doesn't work - in fact, all the buttons are deactivated. This is the case whether or not I close the video webpage.
How can I keep all the buttons activated? Thanks in advance.
Here's the code for reference. The button links and tags are populated from a text file.
//import statements
public class VideoRecord extends JFrame {
private File videoRecordFile;
public VideoRecord() throws FileNotFoundException {
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(2,2));
setSize(new Dimension(500, 500));
videoRecordFile = new File("videorecord.txt");
getButtons();
pack();
}
public void getButtons() throws FileNotFoundException {
Scanner input = new Scanner(videoRecordFile);
while (input.hasNextLine()) {
Scanner lineInput = new Scanner(input.nextLine());
while (lineInput.hasNext()) {
final String urlString = lineInput.next();
String buttonText = lineInput.next();
JButton btn = new JButton(buttonText);
add(btn);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
URL videoURL = new URL(urlString);
URLConnection videoConnection = videoURL.openConnection();
videoConnection.connect();
openWebpage(videoURL);
}
catch (MalformedURLException mue) {}
catch (IOException ioe) {}
setEnabled(false);
}
});
}
}
}
public static void openWebpage(URI uri) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void openWebpage(URL url) {
try {
openWebpage(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws FileNotFoundException {
VideoRecord vr = new VideoRecord();
}
}
Take a second to look at you code...
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
URL videoURL = new URL(urlString);
URLConnection videoConnection = videoURL.openConnection();
videoConnection.connect();
openWebpage(videoURL);
}
catch (MalformedURLException mue) {}
catch (IOException ioe) {}
setEnabled(false);
}
});
When you click a button you call setEnabled(false);...
This has actually disable the frame, not the button that was clicked...
Try using ((JButton)e.getSource()).setEnabled(false) instead
Don't throw away you Exceptions blindly, they provide important and useful information that can help solve problems

Jtable content is visible through different tab

I have JTabbedPane with 4 tabs. JtabbedPane is situated on a JLayeredPane. 1st and 4th tab contain JTable with custom models. Each of the tables is being refreshed every 5-10 seconds.
When 1st tab is active, and JTable on 4th has just finished refreshing, I can see content of the 4th on the 1st. Look at the screenshot.
When I click on the other tab, or minimize window, that strange effect is gone. Till the next refresh of that table on 4th tab. Refreshing is done using Future<> object.
I used Swing GUI builder in Netbeans, so I have huge amount of code. Would post any piece which could be useful.
I tried to revalidate jTabbedPane, is had no effect. Both tables and jScrollPanes has opaque property set to true. So I tried to use SwingUtilities.invokeLater(). It helped a little bit - now first content update goes well, but later - the same problem.
2nd table model has method to update it's content
public void setData(LinkedList<Object[]> __rows) {
NewDevsTableModel.__rows = __rows;
fireTableDataChanged();
}
It is used here (I added SwingUtilities here)
static class checkNew implements Callable<Boolean> {
#Override
public Boolean call() {
ServiceMessage sm = ServiceMessage.getNewList();
try {
connect();
os.write(sm.serialize());
for (int i=0; i<10; i++) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {}
if (is.available() > 0) {
break;
}
if (i == 9) {
disconnect();
return false;
}
}
byte[] actByte = new byte[is.available()];
is.read(actByte);
try {
sm = ServiceMessage.Deserialize(actByte); //may be there are no new devices
if (sm.getType() == ServiceMessageType.NODATA) {
MainWindow.jTabbedPane1.setEnabledAt(3, false);
if (MainWindow.jTabbedPane1.getSelectedIndex() == 3) {
MainWindow.jTabbedPane1.setSelectedIndex(0);
}
return true;
} else {
return false; //wrong answer type
}
} catch (ClassCastException | StreamCorruptedException e) {
//remember selection and scroll
final int scroll = MainWindow.jScrollPane3.getVerticalScrollBar().getValue();
final int[] rows = MainWindow.newDevsTable.getSelectedRows();
int col = MainWindow.devicesTable.getSelectedColumn();
String[] parts = new String(actByte).split("\n");
final LinkedList<Object[]> l = new LinkedList();
for (int i=0; i<parts.length; i++) {
String[] dev = parts[i].split(";", -1);
String descr = dev[2];
boolean iptype = (!dev[3].equals("-"));
String address = dev[4];
boolean atmtype = (dev[5].equals("+"));
if (MainWindow.newDevsTable.getRowCount() >= (i+1)) {
if ((MainWindow.newDevsTable.getValueAt(i, 4) != null) && !MainWindow.newDevsTable.getValueAt(i, 4).equals("")) {
descr = MainWindow.newDevsTable.getValueAt(i, 4).toString();
}
}
Object[] o = {dev[0], dev[1], MainWindow.language[180], MainWindow.language[4], descr, iptype, address, atmtype};
l.add(o);
}
if (!l.isEmpty()) {
SwingUtilities.invokeLater( new Runnable() {
#Override
public void run() {
MainWindow.newDevsPanel.setVisible(true);
MainWindow.jTabbedPane1.setEnabledAt(3, true);
((NewDevsTableModel)MainWindow.newDevsTable.getModel()).setData(l);
ButtonColumn buttonColumn = new ButtonColumn(MainWindow.newDevsTable, addAction, 2, true);
buttonColumn = new ButtonColumn(MainWindow.newDevsTable, rejAction, 3, false);
//put selection back
for (int i=0; i<rows.length; i++) {
MainWindow.newDevsTable.addRowSelectionInterval(rows[i], rows[i]);
}
MainWindow.jScrollPane3.getVerticalScrollBar().setValue(scroll);
}
});
} else {
MainWindow.jTabbedPane1.setEnabledAt(3, false);
if (MainWindow.jTabbedPane1.getSelectedIndex() == 3) {
MainWindow.jTabbedPane1.setSelectedIndex(0);
}
}
return true;
}
} catch (IOException e) {
disconnect();
return false;
} catch (ClassNotFoundException e) {
return false;
}
}
}
I submit the task this way
public static Future<Boolean> checkNewDevices() {
final Future<Boolean> task;
task = service.submit(new checkNew());
return task;
}
To refresh automatically I use separate thread
public class CheckNewPassThread extends Thread {
int pause = 10000;
#Override
public void run() {
for (;;) {
HostConnection.checkNewDevices();
try {
Thread.sleep(pause);
} catch (InterruptedException e) {}
}
}
}
Which is started when the window is opened
private void formWindowOpened(java.awt.event.WindowEvent evt) {
HostConnection.getData();
HostConnection.getDeviceAddress();
RefreshData refreshThread = new RefreshData();
refreshThread.start();
new CheckNewPassThread().start();
}
OMG, the problem was in calling jTabbedPane.setEnabledAt(3, true) to already enabled tab. Swing is fascinating

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