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);
}
Related
I'm using WorldWind and trying to "pick" multiple surface images in the same layer and not understanding why it isn't working.
I was under the impression that calling this:
this.getWwd().getSceneController().setDeepPickEnabled(true);
Would enable me to pick multiple renderables in the same layer. This seems to work for all other cases other than SurfaceImage. I also noticed if I force the loaded SurfaceImage into different layers it works as expected.
This is the code I'm using to test this out:
public class SurfaceImageViewer extends ApplicationTemplate
{
public static class AppFrame extends ApplicationTemplate.AppFrame
{
private JFileChooser fileChooser = new JFileChooser();
private JSlider opacitySlider;
private SurfaceImageLayer layer;
private JLabel statusLabel = new JLabel("status: ready");
public AppFrame()
{
super(true, true, false);
this.getWwd().getSceneController().setDeepPickEnabled(true);
try
{
this.layer = new SurfaceImageLayer();
this.layer.setOpacity(1);
this.layer.setPickEnabled(true);
this.layer.setName("Surface Images");
insertBeforeCompass(this.getWwd(), layer);
this.getControlPanel().add(makeControlPanel(), BorderLayout.SOUTH);
}
catch (Exception e)
{
e.printStackTrace();
}
this.getWwd().addSelectListener(new SelectListener() {
#Override
public void selected(SelectEvent event) {
PickedObjectList pol = AppFrame.this.getWwd().getObjectsAtCurrentPosition();
if(event.isLeftClick()){
System.out.println("POL SIZE "+pol.size());
}
}
});
}
Action openElevationsAction = new AbstractAction("Open Elevation File...")
{
public void actionPerformed(ActionEvent e)
{
int status = fileChooser.showOpenDialog(AppFrame.this);
if (status != JFileChooser.APPROVE_OPTION)
return;
final File imageFile = fileChooser.getSelectedFile();
if (imageFile == null)
return;
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
CompoundElevationModel cem
= (CompoundElevationModel) getWwd().getModel().getGlobe().getElevationModel();
LocalElevationModel em = new LocalElevationModel();
em.addElevations(imageFile.getPath());
cem.addElevationModel(em);
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
});
t.setPriority(Thread.MIN_PRIORITY);
t.start();
}
};
Action openImageAction = new AbstractAction("Open Image File...")
{
public void actionPerformed(ActionEvent actionEvent)
{
int status = fileChooser.showOpenDialog(AppFrame.this);
if (status != JFileChooser.APPROVE_OPTION)
return;
final File imageFile = fileChooser.getSelectedFile();
if (imageFile == null)
return;
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
statusLabel.setText("status: Loading image");
// TODO: proper threading
layer.addImage(imageFile.getAbsolutePath());
getWwd().redraw();
statusLabel.setText("status: ready");
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
t.setPriority(Thread.MIN_PRIORITY);
t.start();
}
};
private JPanel makeControlPanel()
{
JPanel controlPanel = new JPanel(new GridLayout(0, 1, 5, 5));
JButton openImageButton = new JButton(openImageAction);
controlPanel.add(openImageButton);
this.opacitySlider = new JSlider();
this.opacitySlider.setMaximum(100);
this.opacitySlider.setValue((int) (layer.getOpacity() * 100));
this.opacitySlider.setEnabled(true);
this.opacitySlider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
int value = opacitySlider.getValue();
layer.setOpacity(value / 100d);
getWwd().redraw();
}
});
JPanel opacityPanel = new JPanel(new BorderLayout(5, 5));
opacityPanel.setBorder(new EmptyBorder(0, 10, 0, 0));
opacityPanel.add(new JLabel("Opacity"), BorderLayout.WEST);
opacityPanel.add(this.opacitySlider, BorderLayout.CENTER);
controlPanel.add(opacityPanel);
JButton openElevationsButton = new JButton(openElevationsAction);
controlPanel.add(openElevationsButton);
controlPanel.add(statusLabel);
controlPanel.setBorder(new EmptyBorder(15, 15, 15, 15));
return controlPanel;
}
}
public static void main(String[] args)
{
ApplicationTemplate.start("World Wind Surface Images", SurfaceImageViewer.AppFrame.class);
}
}
These are 2 geotiffs that are layered on top of each other that I've been using to test this out. I would expect my println on the SelectListener to print out "3" when I single left click on both geotiffs. (I've uploaded the geotiffs into a zip available here)
The area where you will see these is in San Francisco, see screenshot:
Update:
It was discovered that the examples for Batch Picking were oriented around AbstractSurfaceObject instances, which did not apply in this case. For the handling of SurfaceImage instances the property for setAlwaysOnTop should be configured to false which appears to let the selection event process all elements under the cursor.
Reading through the examples for DeepPicking, there are actually 2 things that need to be done.
setDeepPickEnabled(true); //This is done.
Disable Batch picking on the desired elements
https://github.com/nasa/World-Wind-Java/blob/master/WorldWind/src/gov/nasa/worldwindx/examples/DeepPicking.java
In order to enable deep picking, any batch picking for the desired elements must be disabled and the
SceneController's deep picking property must be enabled. See {#link gov.nasa.worldwind.SceneController#setDeepPickEnabled(boolean)
Took me a little while to understand the second one, but it appears to be tied to the AbstractSurfaceObject class.
I am assuming that the things that you're drawing on the layer are a subclass of AbstractSurfaceObject
I believe that in this situation, I would subclass the SurfaceImageLayer, and override the addRenderable methods. I would check the renderable if it was an instance of an AbstractSurfaceObject, and disable batch picking on it before forwarding it to the super class.
This code may not be the best long-term solution, but it may provide quick results to determine if this is the underlying issue.
import gov.nasa.worldwind.layers.SurfaceImageLayer;
import gov.nasa.worldwind.render.AbstractSurfaceObject;
import gov.nasa.worldwind.render.Renderable;
/**
* Very Rough extension of SurfaceImageLayer which disables batch picking on all AbstractSurfaceobjects.
* #author http://stackoverflow.com/users/5407189/jeremiah
* #since Nov 26, 2016
*
*/
public class MySurfaceImageLayer extends SurfaceImageLayer {
#Override
public void addRenderable(Renderable renderable) {
if (renderable instanceof AbstractSurfaceObject) {
((AbstractSurfaceObject)renderable).setEnableBatchPicking(false);
}
super.addRenderable(renderable);
}
#Override
public void addRenderables(Iterable<? extends Renderable> renderables) {
for (Renderable r : renderables) {
addRenderable(r);
}
}
}
IF the thing you want to have picked is the image directly, that appears to not be supported out-of-the-box. You would need to do something to get the SurfaceImage references from the SurfaceImageLayer to be visible to the RenderableLayer on doPick. That may come with a new set of problems to watch out for.
As a side-note, if you're rendering Icons then all you need to do is set the IconRenderer.setAllowBatchPicking(false)
I hope that's at least somewhat helpful.
Best of Luck.
I recently have implemented clipping in my VTK Java program. I used BoxWidget to control what should be clipped. However, i'm having an issue with vtkRenderWindowInteractor that attached to BoxWidget. The program freezes at the renderWindowInteractor.Start() statement (I've remarked it in my code).
This is my re-simulate code :
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import vtk.*;
public class VTKWindowInteractor extends JPanel {
static {
if (!vtkNativeLibrary.LoadAllNativeLibraries()) {
for (vtkNativeLibrary lib : vtkNativeLibrary.values()) {
if (!lib.IsLoaded()) {
System.out.println(lib.GetLibraryName() + " not loaded");
}
}
System.out.println("Make sure the search path is correct: ");
System.out.println(System.getProperty("java.library.path"));
}
vtkNativeLibrary.DisableOutputWindow(null);
}
private vtkPanel renWin;
private vtkRenderWindowInteractor renderWindowInteractor;
private vtkPolyDataMapper mapper;
private vtkActor coneActor;
private vtkPlanes planes;
private vtkBoxWidget boxWidget;
public VTKWindowInteractor() {
setLayout(new BorderLayout());
renWin = new vtkPanel();
add(renWin, BorderLayout.CENTER);
renWin.setMinimumSize(new Dimension(50, 50));
renWin.GetRenderer().SetBackground(0, 0, 0); // black
renWin.GetRenderWindow().AddRenderer(renWin.GetRenderer());
}
public void render() {
mapper = new vtkPolyDataMapper();
vtkConeSource cone = new vtkConeSource();
cone.SetHeight(3.0);
cone.SetRadius(1.0);
cone.SetResolution(10);
mapper.SetInputConnection(cone.GetOutputPort());
coneActor = new vtkActor();
coneActor.SetMapper(mapper);
renWin.GetRenderer().AddActor(coneActor);
planes = new vtkPlanes();
renderWindowInteractor = new vtkRenderWindowInteractor();
renderWindowInteractor.SetRenderWindow(renWin.GetRenderWindow());
boxWidget = new vtkBoxWidget();
boxWidget.SetInteractor(renderWindowInteractor);
boxWidget.SetPlaceFactor(1.25);
boxWidget.PlaceWidget(coneActor.GetBounds());
boxWidget.AddObserver("InteractionEvent", this, "executeClipping");
renderWindowInteractor.Initialize();
boxWidget.On();
renWin.Render();
renWin.resetCamera();
/**************************************/
// This is where the freeze come from //
// //
/************************************/
renderWindowInteractor.Start(); // if i comment out this line, the program works but the boxWidget cannot be resized or rescale or moved
}
public void executeClipping() {
planes = new vtkPlanes();
boxWidget.GetPlanes(planes);
mapper.SetClippingPlanes(planes);
planes.Delete();
}
public static final int WINDOW_WIDTH = 1000;
public static final int WINDOW_HEIGHT = 500;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
VTKWindowInteractor _vtkRendererPanel = new VTKWindowInteractor();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("......");
frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
frame.setVisible(true);
frame.setLayout(new BorderLayout());
frame.add(_vtkRendererPanel);
_vtkRendererPanel.render();
}
});
}
}
I have been finding my mistake for hours and hours and frustrated hence come here to seek for help. If anyone have experienced this or know what did I do wrong please correct me. Thanks !!!
VTK version : 6.2.0
OK. I finally solved the problem. The follows is the quote from vtkPanel.java
/*
*
* Java AWT component that encapsulate vtkRenderWindow, vtkRenderer, vtkCamera,
* vtkLight.
*
* If a vtkInteractor is needed, use vtkCanvas instead. This is necessary when
* Widget and Picker are used.
*
* #author Kitware */
so I changed my
vtkPanel
to
vtkCanvas
&
renderWindowInteractor = new vtkRenderWindowInteractor();
to
renderWindowInteractor = renWin.getRenderWindowInteractor();
and it solves the problem.
Thanks and this is for anyone who are going to face similiar problem as me in the future.
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();
}
}
I want to learn how to write an ActionListener for JLabel. I want to make a label that open a new frame for user when user clicks the label. Maybe MouseListener can work but I do not know how to make it.
I recommend using a JTextField rather than a JLabel for this use.
Being based on a component designed to be focusable, it allows an ActionListener and looks and feels more like an HTML link.
E.G.
That is how it appears when the mouse is hovering over the first link.
LinkLabel
/* License - LGPL
LinkLabel Using the Desktop Class
There are a lot of link labels. This one uses the Java 1.6+
Desktop class for its functionality, and is thereby suitable
for applets, applications launched using JWS, and 'standard'
(non-JWS) desktop applications.
Note that the Desktop class can be used with pre 1.6 JREs. It
is available through JDIC.
https://jdic.dev.java.net/nonav/documentation/javadoc/jdic/org/jdesktop/jdic/desktop/Desktop.html
*/
import java.awt.Desktop;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.border.MatteBorder;
import javax.swing.border.Border;
import java.net.URI;
import java.io.File;
/**
A Java 1.6+ LinkLabel that uses the Desktop class for opening
the document of interest.
The Desktop.browse(URI) method can be invoked from applications,
applets and apps. launched using Java Webstart. In the latter
two cases, the usual fall-back methods are used for sandboxed apps
(see the JavaDocs for further details).
While called a 'label', this class actually extends JTextField,
to easily allow the component to become focusable using keyboard
navigation.
To successfully browse to a URI for a local File, the file name
must be constructed using a canonical path.
#author Andrew Thompson
#version 2008/08/23
*/
public class LinkLabel
// we extend a JTextField, to get a focusable component
extends JTextField
implements MouseListener, FocusListener, ActionListener {
/** The target or href of this link. */
private URI target;
public Color standardColor = new Color(0,0,255);
public Color hoverColor = new Color(255,0,0);
public Color activeColor = new Color(128,0,128);
public Color transparent = new Color(0,0,0,0);
public boolean underlineVisible = true;
private Border activeBorder;
private Border hoverBorder;
private Border standardBorder;
/** Construct a LinkLabel that points to the given target.
The URI will be used as the link text.*/
public LinkLabel(URI target) {
this( target, target.toString() );
}
/** Construct a LinkLabel that points to the given target,
and displays the text to the user. */
public LinkLabel(URI target, String text) {
super(text);
this.target = target;
}
/* Set the active color for this link (default is purple). */
public void setActiveColor(Color active) {
activeColor = active;
}
/* Set the hover/focused color for this link (default is red). */
public void setHoverColor(Color hover) {
hoverColor = hover;
}
/* Set the standard (non-focused, non-active) color for this
link (default is blue). */
public void setStandardColor(Color standard) {
standardColor = standard;
}
/** Determines whether the */
public void setUnderlineVisible(boolean underlineVisible) {
this.underlineVisible = underlineVisible;
}
/* Add the listeners, configure the field to look and act
like a link. */
public void init() {
this.addMouseListener(this);
this.addFocusListener(this);
this.addActionListener(this);
setToolTipText(target.toString());
if (underlineVisible) {
activeBorder = new MatteBorder(0,0,1,0,activeColor);
hoverBorder = new MatteBorder(0,0,1,0,hoverColor);
standardBorder = new MatteBorder(0,0,1,0,transparent);
} else {
activeBorder = new MatteBorder(0,0,0,0,activeColor);
hoverBorder = new MatteBorder(0,0,0,0,hoverColor);
standardBorder = new MatteBorder(0,0,0,0,transparent);
}
// make it appear like a label/link
setEditable(false);
setForeground(standardColor);
setBorder(standardBorder);
setCursor( new Cursor(Cursor.HAND_CURSOR) );
}
/** Browse to the target URI using the Desktop.browse(URI)
method. For visual indication, change to the active color
at method start, and return to the standard color once complete.
This is usually so fast that the active color does not appear,
but it will take longer if there is a problem finding/loading
the browser or URI (e.g. for a File). */
public void browse() {
setForeground(activeColor);
setBorder(activeBorder);
try {
Desktop.getDesktop().browse(target);
} catch(Exception e) {
e.printStackTrace();
}
setForeground(standardColor);
setBorder(standardBorder);
}
/** Browse to the target. */
public void actionPerformed(ActionEvent ae) {
browse();
}
/** Browse to the target. */
public void mouseClicked(MouseEvent me) {
browse();
}
/** Set the color to the hover color. */
public void mouseEntered(MouseEvent me) {
setForeground(hoverColor);
setBorder(hoverBorder);
}
/** Set the color to the standard color. */
public void mouseExited(MouseEvent me) {
setForeground(standardColor);
setBorder(standardBorder);
}
public void mouseReleased(MouseEvent me) {}
public void mousePressed(MouseEvent me) {}
/** Set the color to the standard color. */
public void focusLost(FocusEvent fe) {
setForeground(standardColor);
setBorder(standardBorder);
}
/** Set the color to the hover color. */
public void focusGained(FocusEvent fe) {
setForeground(hoverColor);
setBorder(hoverBorder);
}
public static void main(String[] args) throws Exception {
JPanel p = new JPanel(new GridLayout(0,1));
File f = new File(".","LinkLabel.java");
/* Filename must be constructed with a canonical path in
order to successfully use Desktop.browse(URI)! */
f = new File(f.getCanonicalPath());
URI uriFile = f.toURI();
LinkLabel linkLabelFile = new LinkLabel(uriFile);
linkLabelFile.init();
p.add(linkLabelFile);
LinkLabel linkLabelWeb = new LinkLabel(
new URI("http://sscce.org/"),
"SSCCE");
linkLabelWeb.setStandardColor(new Color(0,128,0));
linkLabelWeb.setHoverColor(new Color(222,128,0));
linkLabelWeb.init();
/* This shows a quirk of the LinkLabel class, the
size of the text field needs to be constrained to
get the underline to appear properly. */
p.add(linkLabelWeb);
LinkLabel linkLabelConstrain = new LinkLabel(
new URI("http://sdnshare.sun.com/"),
"SDN Share");
linkLabelConstrain.init();
/* ..and this shows one way to constrain the size
(appropriate for this layout).
Similar tricks can be used to ensure the underline does
not drop too far *below* the link (think BorderLayout
NORTH/SOUTH).
The same technique can also be nested further to produce
a NORTH+EAST packing (for example). */
JPanel labelConstrain = new JPanel(new BorderLayout());
labelConstrain.add( linkLabelConstrain, BorderLayout.EAST );
p.add(labelConstrain);
LinkLabel linkLabelNoUnderline = new LinkLabel(
new URI("http://java.net/"),
"java.net");
// another way to deal with the underline is to remove it
linkLabelNoUnderline.setUnderlineVisible(false);
// we can use the methods inherited from JTextField
linkLabelNoUnderline.
setHorizontalAlignment(JTextField.CENTER);
linkLabelNoUnderline.init();
p.add(linkLabelNoUnderline);
JOptionPane.showMessageDialog( null, p );
}
}
I want to make a JButton look like a link in HTML. It will still be a button and when I click on it it will open some new JFrame. But I want to change what it looks like. I tried this:
JButton button = new JButton();
button.setText("hi");
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setOpaque(false);
button.setBackground(Color.WHITE);
button.setCursor(Cursor.getPredefinedCursor(12));
But there is still some border around the text of my button. How do we remove the border completely?
But there is still some border around the text of my button
button.setFocusPainted( false );
I recommend using a JTextField rather than a JButton for this use.
E.G.
That is how it appears when the mouse is hovering over the first link.
LinkLabel.java
/* License - LGPL
LinkLabel Using the Desktop Class
There are a lot of link labels. This one uses the Java 1.6+
Desktop class for its functionality, and is thereby suitable
for applets, applications launched using JWS, and 'standard'
(non-JWS) desktop applications.
Note that the Desktop class can be used with pre 1.6 JREs. It
is available through JDIC.
https://jdic.dev.java.net/nonav/documentation/javadoc/jdic/org/jdesktop/jdic/desktop/Desktop.html
*/
import java.awt.Desktop;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.border.MatteBorder;
import javax.swing.border.Border;
import java.net.URI;
import java.io.File;
/**
A Java 1.6+ LinkLabel that uses the Desktop class for opening
the document of interest.
The Desktop.browse(URI) method can be invoked from applications,
applets and apps. launched using Java Webstart. In the latter
two cases, the usual fall-back methods are used for sandboxed apps
(see the JavaDocs for further details).
While called a 'label', this class actually extends JTextField,
to easily allow the component to become focusable using keyboard
navigation.
To successfully browse to a URI for a local File, the file name
must be constructed using a canonical path.
#author Andrew Thompson
#version 2008/08/23
*/
public class LinkLabel
// we extend a JTextField, to get a focusable component
extends JTextField
implements MouseListener, FocusListener, ActionListener {
/** The target or href of this link. */
private URI target;
public Color standardColor = new Color(0,0,255);
public Color hoverColor = new Color(255,0,0);
public Color activeColor = new Color(128,0,128);
public Color transparent = new Color(0,0,0,0);
public boolean underlineVisible = true;
private Border activeBorder;
private Border hoverBorder;
private Border standardBorder;
/** Construct a LinkLabel that points to the given target.
The URI will be used as the link text.*/
public LinkLabel(URI target) {
this( target, target.toString() );
}
/** Construct a LinkLabel that points to the given target,
and displays the text to the user. */
public LinkLabel(URI target, String text) {
super(text);
this.target = target;
}
/* Set the active color for this link (default is purple). */
public void setActiveColor(Color active) {
activeColor = active;
}
/* Set the hover/focused color for this link (default is red). */
public void setHoverColor(Color hover) {
hoverColor = hover;
}
/* Set the standard (non-focused, non-active) color for this
link (default is blue). */
public void setStandardColor(Color standard) {
standardColor = standard;
}
/** Determines whether the */
public void setUnderlineVisible(boolean underlineVisible) {
this.underlineVisible = underlineVisible;
}
/* Add the listeners, configure the field to look and act
like a link. */
public void init() {
this.addMouseListener(this);
this.addFocusListener(this);
this.addActionListener(this);
setToolTipText(target.toString());
if (underlineVisible) {
activeBorder = new MatteBorder(0,0,1,0,activeColor);
hoverBorder = new MatteBorder(0,0,1,0,hoverColor);
standardBorder = new MatteBorder(0,0,1,0,transparent);
} else {
activeBorder = new MatteBorder(0,0,0,0,activeColor);
hoverBorder = new MatteBorder(0,0,0,0,hoverColor);
standardBorder = new MatteBorder(0,0,0,0,transparent);
}
// make it appear like a label/link
setEditable(false);
setForeground(standardColor);
setBorder(standardBorder);
setCursor( new Cursor(Cursor.HAND_CURSOR) );
}
/** Browse to the target URI using the Desktop.browse(URI)
method. For visual indication, change to the active color
at method start, and return to the standard color once complete.
This is usually so fast that the active color does not appear,
but it will take longer if there is a problem finding/loading
the browser or URI (e.g. for a File). */
public void browse() {
setForeground(activeColor);
setBorder(activeBorder);
try {
Desktop.getDesktop().browse(target);
} catch(Exception e) {
e.printStackTrace();
}
setForeground(standardColor);
setBorder(standardBorder);
}
/** Browse to the target. */
public void actionPerformed(ActionEvent ae) {
browse();
}
/** Browse to the target. */
public void mouseClicked(MouseEvent me) {
browse();
}
/** Set the color to the hover color. */
public void mouseEntered(MouseEvent me) {
setForeground(hoverColor);
setBorder(hoverBorder);
}
/** Set the color to the standard color. */
public void mouseExited(MouseEvent me) {
setForeground(standardColor);
setBorder(standardBorder);
}
public void mouseReleased(MouseEvent me) {}
public void mousePressed(MouseEvent me) {}
/** Set the color to the standard color. */
public void focusLost(FocusEvent fe) {
setForeground(standardColor);
setBorder(standardBorder);
}
/** Set the color to the hover color. */
public void focusGained(FocusEvent fe) {
setForeground(hoverColor);
setBorder(hoverBorder);
}
public static void main(String[] args) throws Exception {
JPanel p = new JPanel(new GridLayout(0,1));
File f = new File(".","LinkLabel.java");
/* Filename must be constructed with a canonical path in
order to successfully use Desktop.browse(URI)! */
f = new File(f.getCanonicalPath());
URI uriFile = f.toURI();
LinkLabel linkLabelFile = new LinkLabel(uriFile);
linkLabelFile.init();
p.add(linkLabelFile);
LinkLabel linkLabelWeb = new LinkLabel(
new URI("http://pscode.org/sscce.html"),
"SSCCE");
linkLabelWeb.setStandardColor(new Color(0,128,0));
linkLabelWeb.setHoverColor(new Color(222,128,0));
linkLabelWeb.init();
/* This shows a quirk of the LinkLabel class, the
size of the text field needs to be constrained to
get the underline to appear properly. */
p.add(linkLabelWeb);
LinkLabel linkLabelConstrain = new LinkLabel(
new URI("http://sdnshare.sun.com/"),
"SDN Share");
linkLabelConstrain.init();
/* ..and this shows one way to constrain the size
(appropriate for this layout).
Similar tricks can be used to ensure the underline does
not drop too far *below* the link (think BorderLayout
NORTH/SOUTH).
The same technique can also be nested further to produce
a NORTH+EAST packing (for example). */
JPanel labelConstrain = new JPanel(new BorderLayout());
labelConstrain.add( linkLabelConstrain, BorderLayout.EAST );
p.add(labelConstrain);
LinkLabel linkLabelNoUnderline = new LinkLabel(
new URI("http://java.net/"),
"java.net");
// another way to deal with the underline is to remove it
linkLabelNoUnderline.setUnderlineVisible(false);
// we can use the methods inherited from JTextField
linkLabelNoUnderline.
setHorizontalAlignment(JTextField.CENTER);
linkLabelNoUnderline.init();
p.add(linkLabelNoUnderline);
JOptionPane.showMessageDialog( null, p );
}
}
try this, it should force it to set no border :
setBorder(BorderFactory.createEmptyBorder());
there are only one correct way, to change Look and Feel
or simple example for MetalButtonUI and Windows OS only