I used code from http://svn.openstreetmap.org/applications/viewer/jmapviewer/src/org/openstreetmap/gui/jmapviewer/Demo.java to get a map up and running for my swing application.
I added a few MapMarkerDot to indicate some points in my map and used how can i get the mouse click position from my JMapViewer world map to identify whether a point has been selected but how can I actually show that a particular MapMarkerDot has been selected? I want to add some kind of border similar to http://bikes.oobrien.com/london/#zoom=14&lon=-0.1155&lat=51.4992 but so far I have not seen successful.
Any suggestions/ references are well appreciated. Thanks!
The MapMarkerDot parent implementation of paint() in MapMarkerCircle ignores the Stroke specified in Style, but you can extend MapMarkerCircle to use a larger radius and render anything at all. In the example below, the Update button listener shows how to alter a custom marker's background color dynamically.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import org.openstreetmap.gui.jmapviewer.Coordinate;
import org.openstreetmap.gui.jmapviewer.JMapViewer;
import org.openstreetmap.gui.jmapviewer.MapMarkerCircle;
import org.openstreetmap.gui.jmapviewer.MapMarkerDot;
import org.openstreetmap.gui.jmapviewer.Style;
/**
* #see http://stackoverflow.com/a/33857113/230513
*/
public class London {
private static final Random r = new Random();
private void display() {
JFrame f = new JFrame("London");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMapViewer map = new JMapViewer() {
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
};
Coordinate london = new Coordinate(51.5072, -0.1275);
map.setDisplayPosition(london, 16);
MyMarker dot = new MyMarker("", london);
map.addMapMarker(dot);
map.addMapMarker(new MapMarkerDot("London", london));
f.add(map);
f.add(new JButton(new AbstractAction("Update") {
#Override
public void actionPerformed(ActionEvent e) {
Style style = dot.getStyle();
style.setBackColor(Color.getHSBColor(r.nextFloat(), 1f, 1f));
style.setColor(Color.red);
map.repaint();
}
}), BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static class MyMarker extends MapMarkerCircle {
public MyMarker(String name, Coordinate coord) {
super(null, name, coord, 12, STYLE.FIXED, getDefaultStyle());
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new London()::display);
}
}
Related
I made a program to displace a random number of rectangles on the screen with buttons to make fewer or more with either doubles or halves the number of rectangles. Then I was asked to modify the program to add a slider instead of buttons to the program to control the amount of rectangle on the screen. I am having some trouble.
I am getting a few errors. My professor insists on using IntelliJ IDE for the development environment, which I am not too familiar with. It's asking me to move package c16 and also to make public class Random Rectangles to main or not public any help would be good.
package c16;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class RandomRectangles extends JFrame {
private int rectangle_count=1;
private Random random = new Random();
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
public void run() {
RandomRectangles r = new RandomRectangles();
r.setTitle("Rectangles");
r.setSize(new Dimension(500, 500));
r.setVisible(true);
}
});
}
public RandomRectangles()
{
super();
setLayout(new BorderLayout());
#SuppressWarnings("unused")
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 500, 1);
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
rectangle_count = slider.getValue();
RandomRectangles.this.repaint();
}
});
/*
On clicking SHRINK(FEWER),
half the number of rectangles in the RectangleArea
with different co-ordinates.
*/
JPanel rectangleArea = new JPanel()
{
public void paintComponent(Graphics g) //in-built function.
{
super.paintComponent(g);
g.setColor(Color.BLUE);
/*Get the random co-ordinates for Rectangle.*/
for(int i=0;i<rectangle_count;i++){
int a= (int)Math.floor(random.nextDouble()*getWidth());
int b=(int)Math.floor(random.nextDouble()*getHeight());
int c = (int)Math.floor(random.nextDouble()*(getWidth()-a));
int d = (int)Math.floor(random.nextDouble()*(getHeight()-b));
g.drawRect(a,b,c,d);
}
}
};
/*Add the buttons and the panel to the BorderLayout
so that they are visible for demo.
*/
add(slider,BorderLayout.NORTH);
add(rectangleArea,BorderLayout.CENTER);
}
}
I am new to Java and Java swing.
I need to extract only the color pane and get the color from that pane in my own window.
Basically, I want to remove other unnecessary components in the default ColorPanel.
I am successful in removing the other panels and sliders. But not further.
JColorChooser
It's difficult and requires some AWT/Swing hacks (like Robot class), but possible. I would not advise you to use this code, but if it's required...
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
/**
* <code>ChooserTryout</code>.
*/
public class ChooserTryout {
public static void main(String[] args) {
try {
Robot robot = new Robot();
SwingUtilities.invokeLater(() -> new ChooserTryout().startUI(robot));
} catch (AWTException e) {
e.printStackTrace();
}
}
public void startUI(Robot robot) {
JFrame frm = new JFrame("Color test");
JColorChooser chooser = new JColorChooser();
JLabel label = new JLabel("Here is your actual color");
label.setOpaque(true);
List<JComponent> comps =
getAllChildrenOfClass(chooser, JComponent.class, c -> c.getClass().getName().contains("DiagramComponent"));
JComponent c = comps.get(3);
c.setPreferredSize(new Dimension(300, 300));
c.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
Point p = c.getLocationOnScreen();
p.translate(e.getX(), e.getY());
Color color = robot.getPixelColor(p.x, p.y);
System.out.println("You've clicked color: " + color);
label.setForeground(color);
};
});
frm.add(c);
frm.add(label, BorderLayout.SOUTH);
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
/**
* Searches for all children of the given component which are instances of the given class and satisfies the given condition.
*
* #param aRoot start object for search. May not be null.
* #param aClass class to search. May not be null.
* #param condition condition to be satisfied. May not be null.
* #param <E> class of component.
* #return list of all children of the given component which are instances of the given class. Never null.
*/
public static <E> List<E> getAllChildrenOfClass(Container aRoot, Class<E> aClass, Predicate<E> condition) {
final List<E> result = new ArrayList<>();
final Component[] children = aRoot.getComponents();
for (final Component c : children) {
if (aClass.isInstance(c) && condition.test(aClass.cast(c))) {
result.add(aClass.cast(c));
}
if (c instanceof Container) {
result.addAll(getAllChildrenOfClass((Container) c, aClass, condition));
}
}
return result;
}
}
Okay, so here is the problem.
g.setColor(Color.WHITE);
g.drawString("all your base belong to us",x,y);
The follow code makes it so that the string displayed is white and fully white.
My aim is to make a certain section of the string, say for example, I want the word "base" in that string to be a different color, yellow in this case.
The code that I would most likely use would be:
g.drawString("all your #ffd700base belong to us",x,y);
That code attempts to set the text to be yellow from 'base' all the way to the end of the sentence.
Though the output of that is:
http://i.stack.imgur.com/lB2WC.png
Ignore the background, just look at the string. The "#ffd700" becomes a part of the string which is then displayed.
This doesn't work, I cannot find a solution that does.
Same problem is solved here. Please have a look at below posts:
Swing HTML drawString
Sample code after some changes in code mentioned at above link:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.CellRendererPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PaintComponentTest extends JPanel {
private static final String s = "<html>all your <font color=\"#ffd700\">base</font> belong to us</html>";
private JLabel renderer = new JLabel(s);
private CellRendererPane crp = new CellRendererPane();
private Dimension dim;
public PaintComponentTest() {
this.setBackground(Color.lightGray);
dim = renderer.getPreferredSize();
this.add(crp);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
renderer.setForeground(Color.WHITE);
crp.paintComponent(g, renderer, this, 10, 10, dim.width, dim.height);
}
private void display() {
JFrame f = new JFrame("PaintComponentTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(this);
f.pack();
f.setSize(200, 70);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new PaintComponentTest().display();
}
});
}
}
screenshot:
I'm wondering if any of you know how to display a nice looking progress bar in Java, mostly using Swing, although I don't mind using third-party libraries.
I've been looking at JProgressBar tutorials but none of them refer to styling the bar. Reading the API I found a getUI method that returns ProgressBarUI object but I don't see many ways to customize that one.
What I want is to add rounded corners, change background and foreground color, width, lenght, the usual.
Thanks!
If you don't want to replace the user's chosen Look & Feel, you can just replace the UI delegate with one derived from BasicProgressBarUI.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.plaf.basic.BasicProgressBarUI;
/** #see http://stackoverflow.com/questions/8884297 */
public class ProgressBarUITest extends JPanel {
public ProgressBarUITest() {
JProgressBar jpb = new JProgressBar();
jpb.setUI(new MyProgressUI());
jpb.setForeground(Color.blue);
jpb.setIndeterminate(true);
this.add(jpb);
}
private static class MyProgressUI extends BasicProgressBarUI {
private Rectangle r = new Rectangle();
#Override
protected void paintIndeterminate(Graphics g, JComponent c) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
r = getBox(r);
g.setColor(progressBar.getForeground());
g.fillOval(r.x, r.y, r.width, r.height);
}
}
private void display() {
JFrame f = new JFrame("ProgressBarUITest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ProgressBarUITest().display();
}
});
}
}
The easiest way to do that would be to change the LookAndFeel or maybe even create your own class that extends off of one of the default L&Fs and just changes the UI for the progress bar...
I've got some very old code which uses a Box to list some information. I create it like so:
Box patterns = Box.createVerticalBox();
Very (very) often, new items are added and old items are removed eg:
label = new JLabel("xyz");
patterns.add(label);
and later
patterns.remove(label);
whenever something is added ore removed I have to have it repaint, so I call:
patterns.revalidate();
patterns.repaint();
Problem is, since this happens very often it chokes up the UI. I think I need a better implementation in order to make it more efficient.
I know I could maintain a list of the active items in the background and then intermittently update the actual UI (batch update) but...
Can someone suggest a more efficient alternative approach?
Why don't you just use a JList and implement a cell renderer?
Or more flexibility with a JTable and implement a table cell renderer (returns a Component instead)?
Based on this example, the following code loafs doing 16 labels at 10 Hz.
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
/** #see https://stackoverflow.com/questions/6605554 */
public class ImageLabelPanel extends Box implements ActionListener {
private static final int N = 16;
private final List<JLabel> list = new ArrayList<JLabel>();
private final Timer timer = new Timer(100, this);
ImageLabelPanel() {
super(BoxLayout.Y_AXIS);
BufferedImage bi = null;
try {
bi = ImageIO.read(new File("image.jpg"));
} catch (IOException e) {
e.printStackTrace(System.err);
}
for (int r = 0; r < N; r++) {
int w = bi.getWidth();
int h = bi.getHeight() / N;
BufferedImage b = bi.getSubimage(0, r * h, w, h);
list.add(new JLabel(new ImageIcon(b)));
}
createPane();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setVisible(true);
timer.start();
}
private void createPane() {
this.removeAll();
for (JLabel label : list) {
add(label);
}
this.revalidate();
}
#Override
public void actionPerformed(ActionEvent e) {
Collections.shuffle(list);
createPane();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ImageLabelPanel();
}
});
}
}