browser using JFrame - java

I'm trying to create a web browser using swing and awt only. I have used actionlistener and actionevent too. But it is not working. Please help me with this.
It runs without any error but doesn't load the web page.
import java.awt.*;
import java.net.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class img extends JFrame
{
private TextField field=new TextField();
private JButton b=new JButton("go");
private JEditorPane display=new JEditorPane();
private JScrollPane panee=new JScrollPane(display);
public static void main(String args[])
{
img file=new img();
file.frameHandler();
}
public void frameHandler() {
setTitle("Browser");
setSize(1200,800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(null);
setResizable(false);
setLocationRelativeTo(null);
addComponentsToFrame(getContentPane());
}
public void addComponentsToFrame(Container pane) {
Insets insets=getInsets();
pane.add(field);
pane.add(panee);
Font font=new Font("STENCIL",Font.ITALIC,10);
field.setFont(font);
field.setBounds(8-insets.left, 30-insets.top,1160, 20);
b.setBounds(1150-insets.left, 30-insets.top,80, 20);
panee.setBounds(8-insets.left, 52-insets.top, 1200, 830);
pane.add(b);
}
private void actionListenerCalls()
{
b.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
loadData("http://"+e.getActionCommand());
}
});
display.addHyperlinkListener(new HyperlinkListener(){
#Override
public void hyperlinkUpdate(HyperlinkEvent e)
{
if(e.getEventType()==HyperlinkEvent.EventType.ACTIVATED){
loadData(e.getURL().toString());
}
}
});
}
private void loadData(String text)
{
try{
display.setPage(text);
}
catch(Exception ee)
{
System.out.println("error");
}
}
}

You have not invoked the method actionListenerCalls to bind listener
Possibly put it here:
public void frameHandler() {
....
addComponentsToFrame(getContentPane());
actionListenerCalls();//<-- invoke here
setVisible(true);
}
P.S. kindly avoid using null layout.
EDIT
From the docs:
We don't support the full CSS spec. Refer to the javadoc of the CSS
class to see what properties we support. The two major CSS parsing
related concepts we do not currently support are pseudo selectors,
such as A:link { color: red }, and the important modifier.
Note: This implementation is currently incomplete. It can be replaced
with alternative implementations that are complete. Future versions of
this class will provide better CSS support.
You may try this to load external css:
StyleSheet ss = new StyleSheet();
ss.importStyleSheet(styleSheetURL);
HTMLEditorKit kit = (HTMLEditorKit)jEditorPane.getEditorKit();
kit.setStyleSheet(ss);
To open default browser
You may try using Desktop browse()
From docs
The browse(uri) method can throw a variety of exceptions, including a
NullPointerException if the URI is null, and an
UnsupportedOperationException if the BROWSE action is unsupported.
This method can throw an IOException if the default browser or
application cannot be found or launched, and a SecurityException if a
security manager denies the invocation.
private void onLaunchBrowser(ActionEvent evt) {
URI uri = null;
try {
uri = new URI(txtBrowserURI.getText());
desktop.browse(uri);
} catch(IOException ioe) {
System.out.println("The system cannot find the " + uri +
" file specified");
//ioe.printStackTrace();
} catch(URISyntaxException use) {
System.out.println("Illegal character in path");
//use.printStackTrace();
}
}

Related

keylistener wait for input

I want to write a live search using Swing components. I am using a keyListener to keep track of the input. Basically i dont want the keyListener to take action every time a button is pressed but instead wait (for some period of time) for more incoming input. This period of time is refreshed every time a button is pressed and the input gets evaluated when it eventually times out (e.g. no button is being pressed within the period meaning that the input is complete). How do I implement that into my keyListener?
Code snippet of main method:
static JTextField nameTextField = new JTextField();
public static void main(String args[]) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(nameTextField, BorderLayout.NORTH);
nameTextField.addKeyListener(new KeyListener() {
public void keyTyped(KeyEvent keyEvent) {
//
}
#Override
public void keyPressed(KeyEvent e) {
//
}
#Override
public void keyReleased(KeyEvent e) {
if(waitForMoreInput(50)) {
doSomething(nameTextField.getText());
}
}
}
}
}
);
frame.setSize(250, 100);
frame.setVisible(true);
}
Thanks in advance
Much better is for you to use a DocumentListener or DocumentFilter, depending on if you want to listen before or after text has been fully registered with the text component.
The DocumentListener will register any time the text has changed, be it via a key press, via a copy and paste, via a deletion of text. The Timer will then wait however long you wish to do whatever action is required on the text. For example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class DocListenerFoo extends JPanel {
private JTextField nameTextField = new JTextField(20);
public DocListenerFoo() {
add(new JLabel("Add Text:"));
add(nameTextField);
int timerDelay = 1000; // one second
nameTextField.getDocument().addDocumentListener(new MyDocListener(timerDelay));
}
private class MyDocListener implements DocumentListener {
private Timer docTimer;
private int timerDelay;
public MyDocListener(int timerDelay) {
this.timerDelay = timerDelay;
}
#Override
public void changedUpdate(DocumentEvent e) {
textChangedAction(e);
}
#Override
public void insertUpdate(DocumentEvent e) {
textChangedAction(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
textChangedAction(e);
}
private void textChangedAction(DocumentEvent e) {
Document doc = e.getDocument();
try {
String text = doc.getText(0, doc.getLength());
if (docTimer != null && docTimer.isRunning()) {
docTimer.stop();
}
docTimer = new Timer(timerDelay, new TimerListener(text));
docTimer.setRepeats(false);
docTimer.start();
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
}
private class TimerListener implements ActionListener {
private String text;
public TimerListener(String text) {
this.text = text;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO do check on text here
System.out.println("Checking text here: " + text);
}
}
private static void createAndShowGui() {
DocListenerFoo mainPanel = new DocListenerFoo();
JFrame frame = new JFrame("DocListenerFoo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Don't wait inside the key or document event, it just blocks the program from being processed further. Instead save the current time or (re)start a timer in the event and execute your action later somewhere else.
I'm guessing that you're trying to use a KeyListener with a Swing text component such as a JTextField (I have to guess since you don't tell or show us). If so, then the best solution is don't. Using a KeyListener with these components can mess up the functionality of the components. Much better is for you to use a DocumentListener or DocumentFilter, depending on if you want to listen before or after text has been fully registered with the text component.
For a better more complete answer, post a better more complete question, including your minimal code example and details about your problem.

Adopting another process's child window

I'm writing a sort of web applet emulator. I read a web page, find the applet parameters, download the applet and run it. It is very important that the applet runs in its own process (i.e. not the emulator process). It should, however, render in the emulator process window.
How does the Java plugin do it? When the separate_jvm flag is set, the plugin loads the applet in a separate JVM process but the applet still appears in the same browser panel.
I've made some progress by creating a loader class that, on another JVM, adds the target Applet to an undecorated, invisible frame and messages the frame's window handle to the emulator JVM. The latter binds it to a Canvas instance with user32.SetParent via JNA, and the display works perfectly.
However, only mouse events are being sent: keyboard input is not forwarded. The applet reports Component#isFocusOwner as false, and requestFocusInWindow does not make it the focus owner, returning false. How can I pass keyboard focus to the Applet window handle? My current approach involves a server (the emulator), which receives window handles from the client (the applet). Only mouse events appear to work, since the Applet cannot gain focus.
The server class handles the display of the applet.
import com.sun.jna.*;
import com.sun.jna.platform.win32.User32;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import static com.sun.jna.platform.win32.User32.*;
public class Loader {
private static final String APPLET_DIRECTORY = ""; // TODO: Set this to the directory containing the compiled applet
private static ServerSocket serverSocket;
private static JFrame frame;
private static Canvas nativeDisplayCanvas;
public static void main(String[] argv) throws Exception {
nativeDisplayCanvas = new Canvas();
frame = new JFrame("Frame redirect");
frame.setLayout(new BorderLayout());
frame.add(nativeDisplayCanvas, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
(new Thread() {
public void run() {
try {
serve();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
spawnAltJVM(APPLET_DIRECTORY, "AppletDemo");
}
public static void serve() throws Exception {
serverSocket = new ServerSocket(6067);
serverSocket.setSoTimeout(10000);
while (true) {
try {
System.out.println("Waiting for applet on port " + serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Connected to " + server.getRemoteSocketAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
DataOutputStream out = new DataOutputStream(server.getOutputStream());
while (true) {
String msg = in.readLine();
if (msg != null && msg.startsWith("child_hwnd")) {
windowCreatedHandler(msg);
out.writeUTF("hwnd_recv\n");
out.flush();
}
}
} catch (IOException ex) {
System.out.println("Something happened to the socket...");
break;
}
}
}
public static void windowCreatedHandler(String message) {
String[] tokens = message.split(":");
final User32 user32 = User32.INSTANCE;
HWND child_applet = new HWND(Pointer.createConstant(Long.parseLong(tokens[1])));
final HWND child_frame = new HWND(Pointer.createConstant(Long.parseLong(tokens[2])));
frame.addComponentListener(
new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
user32.SetWindowPos(child_frame, new HWND(Pointer.NULL), 0, 0, frame.getWidth(), frame.getHeight(), 0);
}
}
);
HWND parent = new HWND(Native.getComponentPointer(nativeDisplayCanvas));
user32.SetParent(child_applet, parent);
int style = user32.GetWindowLong(child_frame, GWL_STYLE) & ~WS_POPUP | (WS_CHILD | WS_VISIBLE);
user32.SetWindowLong(child_applet, GWL_STYLE, style);
user32.SetWindowPos(child_applet, new HWND(Pointer.NULL), 0, 0, nativeDisplayCanvas.getWidth(), nativeDisplayCanvas.getHeight(), 0);
}
public static void spawnAltJVM(String cp, String clazz) throws IOException, InterruptedException, ClassNotFoundException {
ProcessBuilder processBuilder = new ProcessBuilder(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java", "-cp", cp, clazz);
Process applet = processBuilder.start();
final BufferedReader in = new BufferedReader(new InputStreamReader(applet.getInputStream()));
final BufferedReader err = new BufferedReader(new InputStreamReader(applet.getErrorStream()));
(new Thread() {
public void run() {
while (true) {
try {
System.out.println("[client] " + in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
Meanwhile, the client class just instantiates and messages the handles.
import sun.awt.windows.WComponentPeer;
import javax.swing.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingDeque;
public class AppletDemo extends Applet {
private Canvas canvas;
private static Color backgroundColor = Color.RED;
public AppletDemo() {
setLayout(new BorderLayout());
canvas = new Canvas();
add(canvas, BorderLayout.CENTER);
setBackground(Color.CYAN);
canvas.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
refreshColors();
}
});
canvas.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
refreshColors();
}
});
}
private void refreshColors() {
SwingUtilities.invokeLater(
new Runnable() {
#Override
public void run() {
backgroundColor = (backgroundColor == Color.RED ? Color.GREEN : Color.RED);
canvas.setBackground(backgroundColor);
}
}
);
}
public static void main(String[] argv) throws Exception {
System.setErr(System.out);
final AppletDemo app = new AppletDemo();
Frame frame = new Frame("AppletViewer");
frame.setLayout(new BorderLayout());
frame.add(app, BorderLayout.CENTER);
frame.setUndecorated(true);
frame.pack(); // Create the native peers
frame.setSize(300, 200);
final Socket client = new Socket("localhost", 6067);
final LinkedBlockingDeque<String> messageQueue = new LinkedBlockingDeque<>();
final DataOutputStream out = new DataOutputStream(client.getOutputStream());
final BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
(new Thread() {
public void run() {
while (true) {
try {
out.writeBytes(messageQueue.take() + "\n");
out.flush();
} catch (IOException | InterruptedException ex) {
ex.printStackTrace();
}
}
}
}).start();
(new Thread() {
public void run() {
while (true) {
try {
if ("hwnd_recv".equals(in.readLine())) {
// Attempt to grab focus in the other process' frame
System.out.println("Trying to request focus...");
System.out.println(app.requestFocusInWindow());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}).start();
messageQueue.add("child_hwnd:" + ((WComponentPeer) app.getPeer()).getHWnd() + ":" + ((WComponentPeer) frame.getPeer()).getHWnd());
}
}
They're both a bit lengthy because they require some socket work, but they are compilable and should demonstrate the issue. They require JNA to compile. I've shortened them as much as possible at the cost of some good practices.
When Loader is ran, a window redirecting the AppletDemo's canvas should appear. Mouse events are sent: the canvas toggles between red and green on a mouse press. Ideally, the same behavior should occur for keystrokes too.
I've used WinSpy to get the handles of a notepad.exe window and text pane, and hardcoding the handles into Loader. Keyboard focus works perfectly with the multiline edit control, but not with the toplevel window itself. Why? Is this related to the issue I'm having?
I opened up a Chrome window running an applet in WinSpy, and found that the plugin creates no dummy Frame — the applet canvas is directly set as a child of Chrome. However, I haven't been able to create a native peer for the Applet, since it seems to require it to be displayable.
I've read about the dangers of cross-process parent/child or owner/owned window relationship, but I can't think of a better way to graft the child applet into the emulator.
Since what you really want is to create the applet as a child window, the easy solution would be to convince the applet to be your children, not forcefully adopting it, and working against both Windows and the JVM.
Luckily, the Sun/Oracle Java VM comes with a class called WComponentFrame (Windows-only as implied from the name). It can constructed from an hwnd, which you can send from your parent process. The applet can then be added as a child of your window.
import sun.awt.windows.WComponentPeer;
frame = new WEmbeddedFrame(hwnd);
frame.setLayout(new BorderLayout());
frame.add(applet, BorderLayout.CENTER);
It looks like you are trying to pass the event to the Canvas object, which you do not explicitly setFocusable(true) for.
If this is the case, then in your AppletDemo constructor, try:
canvas.setFocusable(true);
canvas.requestFocus();
Also it seems like you want to pass key events to your Applet rather than your Canvas from your question.
In this case, try this in your AppletDemo constructor:
this.setFocusable(true);
this.requestFocus();
After that, you should receive keyboard input by default to the component that is focused.
With JNA it is as easy as
HWND hwnd1 = User32.INSTANCE.FindWindow(null, "JFrame1");
HWND hwnd2 = User32.INSTANCE.FindWindow(null, "JFrame2");
HWND hwnd3 = User32.INSTANCE.SetParent(hwnd2, hwnd1);
see also
Good or evil - SetParent() win32 API between different processes

Java code works on eclipse but not on command prompt

I am writing a java program and it is properly running on Eclipse, there are no errors and the program gives accurate output. However when I compile it using command prompt it gives me 39 errors.
import java.util.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.event.*;
import java.io.*;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.*;
public class Main extends JFrame{
public static void main (String args [])
{
JFrame frame = new JFrame (); // making a frame in which we will add all the
// components
FrameWork work = new FrameWork ();
frame.setLayout(null);
frame.setBounds (10,10,700,500);
frame.setResizable(false); // making the frame non resizeable so that components are not misplaced
frame.add (work);
frame.setDefaultCloseOperation (EXIT_ON_CLOSE);
frame.setVisible (true);
} // main ends here
} // main class ends here
class FrameWork extends JPanel
{
// panel in which all the components are added
JPanel panel = new JPanel ();
JTextArea jarea = new JTextArea();
JTextField jfield = new JTextField();
// Buttons that can be used to switch between standard IO NIO and NIO2
JButton IO = new JButton ("Standard IO");
JButton NIO = new JButton ("New IO");
JButton NIO2 = new JButton ("New IO2");
JScrollPane scroll = new JScrollPane();
FrameWork ()
{
// setting the lay out null so that componenets can be places at respective postions
add(panel);
setLayout (null);
setBounds (0,0,700,500);
setBackground(Color.white);
add(jarea);
jarea.setBounds(5,85,670,360);
//setting border arround the JText area
jarea.setBorder(BorderFactory.createLineBorder(Color.black));
jarea.add(scroll);
add(jfield);
jfield.setBounds(10,10,650,25);
// adding Standard IO button and Implemnting action listener
add(IO);
IO.setBounds (50,40,150,40);
IO.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent ae)
{
try {
FileReader reader = new FileReader("test.txt");
BufferedReader buff = new BufferedReader(reader);
jarea.read(buff,null);
buff.close();
}
catch (IOException e) {
}
}
#Override
public void mouseEntered(MouseEvent ae) {
}
#Override
public void mouseExited(MouseEvent ae) {
}
#Override
public void mousePressed(MouseEvent ae) {
}
#Override
public void mouseReleased(MouseEvent ae) {
}});
// adding Standard NIO button and Implementing action listener
add(NIO);
NIO.setBounds (250,40,150,40);
NIO.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent ae) {
// some part of this code from java docs
Path file = Paths.get("test.txt");
try (InputStream in = Files.newInputStream(file);
BufferedReader reader =new BufferedReader(new InputStreamReader(in)))
{
String line = null;
while ((line = reader.readLine()) != null) {
jarea.read(reader,null);
}
} catch (IOException x) {
System.err.println(x);
}
}
#Override
public void mouseEntered(MouseEvent ae) {
}
#Override
public void mouseExited(MouseEvent ae) {
}
#Override
public void mousePressed(MouseEvent ae) {
}
#Override
public void mouseReleased(MouseEvent ae) {
}});
// adding Standard NIO2 button and Implemnting action listener
add(NIO2);
NIO2.setBounds (450,40,150,40);
NIO2.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent ae) {
try
{
ByteBuffer buffer = ByteBuffer.allocate(1024*1024);
Path file = Paths.get("test.txt");
ReadableByteChannel rbc = Files.newByteChannel(file);
int counter =0;
int flag = 0;
int enter = 0;
while(counter != -1)
{
buffer.rewind ();
counter = rbc.read(buffer);
buffer.rewind();
flag++;
for(enter =0 ; enter <= counter-1 ; enter++)
{
byte by = buffer.get();
jarea.append(""+(char)by);
}
}
}
catch(Exception e){}
}
#Override
public void mouseEntered(MouseEvent ae) {
}
#Override
public void mouseExited(MouseEvent ae) {
}
#Override
public void mousePressed(MouseEvent ae) {
}
#Override
public void mouseReleased(MouseEvent ae) {
}});
} // constructor ends
} //FrameWork Class ends
Errors:
Edit: based on the images of errors that you uploaded later, it looks like you are using a Java 1.6 or earlier compiler. Do java -version to see what version you are using.
Update your windows path to use the java 1.7 version that you have elsewhere on your machine.
In Command Line - Remove the imported packages on top , when it is a single file and standalone application.
Check List:-
Make user the libraries are available to the existing location.
Set the class path perfectly.
Execute the below commands to ensure they environmental variables are set properly for jdk and jre
c:\javac
c:\java
I ran into a similar issue today. My program was working fine in the Eclipse debugger but misbehaving from the OS command line. It finally turned out to be a CLASSPATH issue. My code was incompatible with a JAR that I had included in my CLASSPATH environment variable for the OS shell. This JAR was not even required for my program. For Eclipse I had only linked the requisite JARs, so this problem did not manifest in the Eclipse debugger. After excluding the offending JAR from my CLASSPATH, the problem disappeared.

Java-How to extend InputStream to read from a JTextField?

Working on a project I got into running java applications through a small console-like window. Thanks to the wonderful community in here I managed to solve the problem with outputting the data from a proccess but my command-line applications running will constantly give errors as there is no input stream.
Based on the last helpful reply in that thread I suppose I shall approach similarly the JTextFieldInputStream extends InputStream implementation, but looking in the javadocs and throughout google and the internet for some class that does just that I really found nothing explaining how to do this.
So I am asking for some link, example, tutorial, sample code for it just like in the previous topic.
Give me just a class that extends InputStream and can be extended to read from a JTextField when I press Enter and I will do the rest with implementing this and making it work! Thanks in advance!
What I don't understand if why you need a JTextField that extends InputStream? Basically, what you are looking for is:
Add an ActionListener on the JTextField (ie, when use presses Enter, actionPerformed will be invoked)
You need to grab the text of the JTextField using getText()
You can then "transform" the String text to an InputStream with new ByteArrayInputStream(text.getBytes("UTF-8"));
Here is a small snippet that should get you the basic idea:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestTextField {
private void initUI() {
JFrame frame = new JFrame(TestTextField.class.getSimpleName());
frame.setLayout(new FlowLayout());
final JTextField textfield = new JTextField(20);
textfield.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
String text = textfield.getText();
InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
// Here do something with your input stream (something non-blocking)
System.err.println(text);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(textfield);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestTextField().initUI();
}
});
}
}
How about this implementation
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JTextField;
public class JTextFieldInputStream extends InputStream {
byte[] contents;
int pointer = 0;
public JTextFieldInputStream(final JTextField text) {
text.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar()=='\n'){
contents = text.getText().getBytes();
pointer = 0;
text.setText("");
}
super.keyReleased(e);
}
});
}
#Override
public int read() throws IOException {
if(pointer >= contents.length) return -1;
return this.contents[pointer++];
}
}
to use this input stream, do the following
InputStream in = new JTextFieldInputStream( someTextField );
char c;
while( (c = in.read()) != -1){
//do whatever with c
}
does it read only when I hit enter?
it reads when you call in.read() if the return value -1 it means end of the stream
(And will I be able to modify so that the Enter key empties the JTextField?)
you need to add an action listener and this functionality has nothing to do with the job of input stream

JMapViewer ADD tiles for offline view

Hello I'm using this sample in Java to try to load OpenStreetMaps Offline tiles,
for example I have my tiles on C:/OSM/tiles/
but I need to know how to add this information in map (JMapViewer) class to load tiles locally.
Thank you very much for your help this is my source:
//License: GPL. Copyright 2008 by Jan Peter Stotz
import org.openstreetmap.gui.jmapviewer.JMapViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* Demonstrates the usage of {#link JMapViewer}
*
* #author Jan Peter Stotz
*
*/
public class Demo extends JFrame {
public Demo() {
super("JMapViewer Demo");
setSize(400, 400);
final JMapViewer map = new JMapViewer();
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
JPanel panel = new JPanel();
add(panel, BorderLayout.NORTH);
final JCheckBox showMapMarker = new JCheckBox("Map markers visible");
showMapMarker.setSelected(map.getMapMarkersVisible());
showMapMarker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
map.setMapMarkerVisible(showMapMarker.isSelected());
}
});
panel.add(showMapMarker);
final JCheckBox showTileGrid = new JCheckBox("Tile grid visible");
showTileGrid.setSelected(map.isTileGridVisible());
showTileGrid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
map.setTileGridVisible(showTileGrid.isSelected());
}
});
panel.add(showTileGrid);
final JCheckBox showZoomControls = new JCheckBox("Show zoom controls");
showZoomControls.setSelected(map.getZoomContolsVisible());
showZoomControls.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
map.setZoomContolsVisible(showZoomControls.isSelected());
}
});
panel.add(showZoomControls);
add(map, BorderLayout.CENTER);
//
// map.addMapMarker(new MapMarkerDot(49.814284999, 8.642065999));
// map.addMapMarker(new MapMarkerDot(49.91, 8.24));
// map.addMapMarker(new MapMarkerDot(49.71, 8.64));
// map.addMapMarker(new MapMarkerDot(48.71, -1));
// map.addMapMarker(new MapMarkerDot(49.807, 8.644));
map.setDisplayPositionByLatLon(-0.223056, -78.5126, 11);
}
/**
* #param args
*/
public static void main(String[] args) {
new Demo().setVisible(true);
}
}
A much better alternative that doesn't require modifying JMapViewer and recompiling it is to provide your own TileSource implementation, as shown here.
Grab the OfflineOsmTileSource, and use it like the blog post says.
Simple and elegant. All you need is some osm tiles stored locally, which I assume you already have.
As far as I remember JMapViewer is designed to work only using online maps.
Changing that behavior seams to be complicated. May be you can achieve this by implementing your own org.openstreetmap.gui.jmapviewer.TileLoader instance. The implementation only has to be able to create Runnable instances that load a specific tile into the TileCache and inform the registered TileLoaderListener that a tile loading is completed.
I compile by the source directly and change
\org\openstreetmap\gui\jmapviewer\tilesources\AbstractOsmTileSource.java
Here is the source code inside JMapViewer.zip/JMapViewer_src.jar extract the Jar file and copy the folder /org in the mail source code folder
http://svn.openstreetmap.org/applications/viewer/jmapviewer/releases/2011-02-19/JMapViewer.zip
and change the next
public AbstractOsmTileSource(String name, String base_url, String attr_img_url) {
this.name = name;
// this.baseUrl = base_url;
this.baseUrl = "file:///C:/OSM/tiles";
attrImgUrl = attr_img_url;
}
I have no idea if this approach wasn't supported back when this thread happened, but for caching offline tiles they provide OsmFileCacheTileLoader;
http://josm.openstreetmap.de/doc/org/openstreetmap/gui/jmapviewer/OsmFileCacheTileLoader.html
It is super easy to use.
this.mapViewer = new JMapViewer();
OsmFileCacheTileLoader ofctl;
try {
File cacheDir = new File(System.getProperty("user.home"), "OpenStreetMapTileCache");
logger.info("Home Directory = " + System.getProperty("user.home") + ", cacheDir=" + cacheDir);
cacheDir.mkdirs();
ofctl = new OsmFileCacheTileLoader(mapViewer, cacheDir);
this.mapViewer.setTileLoader(ofctl);
} catch (IOException ex) {
Logger.getLogger(MapDisplayPanel.class.getName()).log(Level.SEVERE, "Exception creating OsmFileCacheTileLoader" + ex, ex);
}

Categories

Resources