Mouse shows color - java

i am trying to make an application which would show which color my mouse is pointing to, i dont mean in my own application but anywhere in windows on any screen, kind of like a tag beside my mouse pointer which shows the exact color.
I am a Java developer but i dont think this could be done in java i am thinking maybe i need some sort of script but i have no idea any help would be really appriciated

The solution consists of two parts:
Part 1: Retrieving the color:
Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
Color color = new Robot().getPixelColor(mouseLocation.x, mouseLocation.y);
Part 2: Getting the color name:
You can get a list of many colors and their names from Wikipedia's List of colors. You can create a mapping in Java given the data on Wikipedia.
Perhaps you can start with a few colors, and provide a generic hex representation for unknown colors, for example #rrggbb.

Here is the runnable example,
import java.awt.AWTException;
import java.awt.Color;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
public class Main {
public static String getHexString(int rgb) {
String hexString = Integer.toHexString(rgb);
hexString = hexString.length() > 1 ? hexString : "0" + hexString;
return hexString;
}
public static void main(String[] a) throws AWTException {
Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
Color color = new Robot().getPixelColor(mouseLocation.x,
mouseLocation.y);
System.out.println(getHexString(color.getRed())
+ getHexString(color.getGreen())
+ getHexString(color.getBlue()));
}
}

Take your pick: http://rosettacode.org/wiki/Color_of_a_screen_pixel
There is a Java/AWT example, an AutoHotKey is a simple scripted option.
The second C example shows the 3 API calls you need GetDC/GetCursorPos/GetPixel and their support code, these can be used from most languages that compile for windows.

Related

BufferedImage TYPE_BYTE_BINARY change color of pixel

I have been struggling to find and answer to this issue. I am trying to change the color of a pixel in a large BufferedImage with the imageType of TYPE_BYTE_BINARY. By default when I create the image it will create a black image which is fine but I cannot seem to be able to change pixel color to white.
This is the basic idea of what I want to do.
BufferedImage bi = new BufferedImage(dim[0], dim[1], BufferedImage.TYPE_BYTE_BINARY);
bi.setRBG(x, y, 255)
This seems weird to me as a TYPE_BYTE_BINARY image will not have RGB color, so I know that that is not the correct solution.
Another idea that I had was to create multiple bufferedImage TYPE_BYTE_BINARY with the createGraphics() method and then combine all of those buffered images into one large bufferedImage but I could not find any information about that when using the TYPE_BYTE_BINARY imageType.
When reading up on this I came across people saying that you need to use createGraphics() method on the BufferedImage but I don't want to do that as it will use up too much memory.
I came across this link http://docs.oracle.com/javase/7/docs/api/java/awt/image/Raster.html specifically for this method createPackedRaster()(the second one). This seems like it might be on the right track.
Are those the only options to be able to edit a TYPE_BYTE_BINARY image? Or is there another way that is similar to the way that python handles 1 bit depth images?
In python this is all that needs to be done.
im = Image.new("1", (imageDim, imageDim), "white")
picture = im.load()
picture[x, y] = 0 # 0 or 1 to change color black or white
All help or guidance is appreciated.
All works. I am able to get a white pixel on the image.
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.awt.Color;
import java.io.File;
public class MakeImage
{
public static void main(String[] args)
{
BufferedImage im = new BufferedImage(100, 100, BufferedImage.TYPE_BYTE_BINARY);
im.setRGB(10, 10, Color.WHITE.getRGB());
try
{
ImageIO.write(im, "png", new File("image.png"));
}
catch (IOException e)
{
System.out.println("Some exception occured " + e);
}
}
}

Compare images with MarvinFramework

I am trying to determine differences between two images during an integration test. After doing some research on the web, I stumbled over the MarvinProject and tried to create a UnitTest with it, see below.
As far as I understood the plugin DifferentRegions, it will fill the passed ImageMask differenceMask with the regions that contain the differences. The two images I pass for the test do differ, so it should print out something.
Unfortunately it does not.
I have written other tests that compare those two images byte-wise and those succeed. For those who want to try the problem, I have created a repository on GitHub and here is the ImageCompareTest.
#Test
public void tryMarvinProject() {
// init images
String root = "src/test/resources/";
MarvinImage assertedImg = MarvinImageIO.loadImage(root + "image1.bmp");
MarvinImage actualImg = MarvinImageIO.loadImage(root + "image2.bmp");
// init diff-regions plugin
DifferentRegions regions = new DifferentRegions();
regions.load();
regions.setAttribute("comparisonImage", assertedImg);
int width = assertedImg.getWidth();
int height = assertedImg.getHeight();
int type = assertedImg.getType();
// process the images and retrieve differences from the ImageMask
MarvinImageMask differenceMask = new MarvinImageMask();
regions.process(
actualImg,
new MarvinImage(new BufferedImage(width, height, type)),
new MarvinAttributes(),
differenceMask,
false);
// should contain the differences, but does not
System.out.println(differenceMask.getMaskArray());
assertNotNull(differenceMask.getMaskArray());
}
The plug-in DifferentRegions was developed for real-time video processing. The idea is to find the regions in the scene which are changing in a sequence of video frames, as shown in this Example
For image-to-image comparison, you should try DifferenceColor plug-in. Basically, it compare the two images analysing the color intensity of pixels in the same position. If the difference of two given pixels is higher than the attribute colorRange, the two pixels are considered distinct in color. The plug-in renders the different pixels in a different color to show them in the output image. If you pass an MarvinAttributes object in the process(...) method, you can get the number of different pixels, stored in the key total.
Example:
MarvinAttributes attrOut = new MarvinAttributes();
MarvinImagePlugin diff = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.difference.differenceColor");
diff.process(imageA, imageB, attrOut);
System.out.println("Distinct pixels:"+attrOut.get("total"));
PS: In order to use MarvinPluginLoader you must configure the development environment following the instructions presented here.
However, since you are trying to use image comparison for Unit Testing, you should take a look at MarvinTestCase class. It extends JUnit TestCase and provide methods to compare MarvinImage objects.
Input:
The source code below implements two test cases, one comparing imageA to imageB, and the other comparing imageA to imageC.
import marvin.image.MarvinImage;
import marvin.io.MarvinImageIO;
import marvin.test.MarvinTestCase;
public class UnitTesting extends MarvinTestCase {
private MarvinImage imageA, imageB, imageC;
public UnitTesting(){
imageA = MarvinImageIO.loadImage("./res/penguin.jpg");
imageB = MarvinImageIO.loadImage("./res/penguin.jpg");
imageC = MarvinImageIO.loadImage("./res/penguin_dark.jpg");
}
public void testSameImage(){
assertEquals(imageA, imageB);
}
public void testDistinctImages(){
assertEquals(imageA, imageC);
}
}
Using Eclipse or another IDE, run the class above as a JUnit Test. Below the output in the JUnit tab on Eclipse.

change font in JOptionPane.showInputDialog

I'm writing a program in java language and I want to make some changes in one part of my JOptionPane.showInputDialog. My dialog is this :
JOptionPane.showInputDialog("Total Amount Deposited:\t\t" +
totalAmount + "\n Enter Coin Value \n" + "(Enter 1 to stop)");
and I want to make the part that is saying (Enter 1 to stop) a little bit smaller than the other parts.
I'm beginner in java language (roughly 2 months :D) and don't have any other experience. so, please keep your answers simple. thanks in advance.
A JOptionPane will display the text in a JLabel, which supports basic HTML. So you will need to wrap your text string in HTML, then you can use different fonts, colors or whatever.
Simple example:
String text = "<html>Normal text <b>and bold text</b></html>";
JOptionPane.showInputDialog(text);
You can also use Font.pointSize() or Font.size() from java.awt.Font.
Create a String = "the text"
put in a label pa
use setFont();
Quick example :
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Test extends JFrame {
public static void main(String[] args)
{
String a = "(enter 1 to stop)";
JLabel pa = new JLabel();
JFrame fr = new JFrame();
fr.setSize(200,200);
pa.setText(a);
pa.setFont(pa.getFont().deriveFont(11.0f)); //change the font size from here
fr.add(pa);
fr.setVisible(true);
}
}
For JDK 8.x, I find the following works to enlarge the font size of most portions of the built-in JOptionPane.showInputDialog, especially buttons, textboxes and comboboxes.
It is mostly generic, except for the two parts I want to be bold font.
It even allows for exceptions (think of it as an "all except" strategy) when you want to enlarge 99% of the pieces of an input dialog, except for one or two pieces.
Sorry for the bad formatting, but the "Code Sample" tool messed up everything and I don't have time to fix it.
import java.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.swing.*;
/**
* Changes the font size used in JOptionPane.showInputDialogs to make them more
* ADA section 508 compliant by making the text size larger, which is very nice
* for older people and anyone else with vision problems.
*
* #param fontSize
* - size of the font in pixels
*/
private static void makeDialogsEasierToSee(int fontSize)
{
// This next one is very strange; but, without it,
// any subsequent attempt to set InternalFrame.titleFont will
// be ignored, so resist the temptation to remove it.
JDialog.setDefaultLookAndFeelDecorated(true);
// define normal and bold fonts that we will use to override the defaults
Font normalFont = new Font(Font.MONOSPACED, Font.PLAIN, fontSize);
Font boldFont = normalFont.deriveFont(Font.BOLD);
// get a list of objects that we can try to adjust font size and style for
List<Map.Entry<Object, Object>> entries = new ArrayList<>(UIManager.getLookAndFeelDefaults().entrySet());
// System.out.println(entries.size());
// remove anything that does NOT involve font selection
entries.removeIf(filter -> filter.getKey().toString().indexOf(".font") == -1);
// System.out.println(entries.size());
// Define a list of font sections of the screen that we do NOT want to
// enlarge/bold.
// The following is specific to jKarel so we do not obscure the display of
// "beeper piles" on the maps.
List<String> exempt = Arrays.asList("Panel.font");
// remove anything on the exempt list
entries.removeIf(filter -> exempt.contains(filter.getKey().toString()));
// System.out.println(entries.size());
// optional: sort the final list
Collections.sort(entries, Comparator.comparing(e -> Objects.toString(e.getKey())));
// apply normal font to all font objects that survived the filters
for (Map.Entry<Object, Object> entry : entries)
{
String key = entry.getKey().toString();
// System.out.println(key);
UIManager.put(key, normalFont);
}
UIManager.put("Label.font", boldFont);
UIManager.put("InternalFrame.titleFont", boldFont);
}
You basically have two straightforward options - Switch to JDialog or use HTML.
JOptionPane is intended for simple messages or interaction with the users. JDialog is a better choice if you want to break out of the canned use cases, and as you get more complex you will probably eventually have to switch to it.
To meet your immediate use case, you can send in an html message. The rules are:
You must begin and end with <html></html> tags. Put them in the middle and nothing happens.
You must remove all "\n"'s in your code. They don't work in html
anyway and the JPanel tries to use each line, as defined by \n's as a
separate html doc. Switch to
int totalAmount = 345; //for testing
String message = "<html>"
+ "Total Amount Deposited: " + totalAmount
+ "<br> Enter Coin Value "
+ "<br><span style='font-size:10'>(Enter 1 to stop)</span>"
+ "</html>";
JOptionPane.showInputDialog(message);

Retrieving color information from ColorPickerDialog.java

I'm currently using the ColorPickerDialog.java provided by Google. I can get it to load properly, and I can successfully choose a color, press the middle circle to confirm, and it will store it's information properly.
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/ColorPickerDialog.html
Since the dialog uses Canvas to draw its elements and the Paint class to color everything, is there a way to retrieve the RGB float value from the selection? I don't know if it's simple and I'm just missing it, but I'm not fully acquainted with Android yet.
If it helps to visualize what I'm trying to achieve, I'm using the ColorPickerDialog.java to let the user select a color, and I want to use that color to tint some things in OpenGL (so I need float r, float g, float b)
The Color class can handle these conversions. The integer you are handed back is a bitwise version usually encoded as ARGB but there are functions to split it up.
import android.graphics.Color;
public class ColorComponents implements OnColorChangedListener {
void colorChanged(int color) {
final int red = Color.red(color);
final int green = Color.green(color);
final int blue = Color.blue(color);
}
}

How to prevent JComboBox drop-down list from exceeding vertical screen size

I use a JComboBox with many entries (hundreds). I want to limit the size of its drop-down list to the vertical size of the screen. Using a fixed size does not work out properly for different look&feels and screen resolutions.
I am using Java 6u25 on Windows 7.
If I set the maximum row count to a value (e.g. 100) that exceeds the number of list items (=rows) that fit on the screen (75), the drop-down list seems to be drawn in full size but the lowest entries are never visible.
Here is a screenshot for illustation (thanks for the SSCCE by #trashgod). The sceenshot was taken in a virtual machine on XP.
I also tested the code on another PC, so I think I can rule out some driver issues.
What I like to have is a drop-down list that fits on screen where I can scroll down completely to the very last value (and see that value). The other way round, I would like to see the scroll down button of the scrollbar.
Is the only possibility to render a cell of the list and use this in my calculations? Manipulation of height parameters of the combobox did not work.
Any ideas how to solve this?
What puzzles me is that I did not find any reference to that problem whatsoever. I assume that I am either missing something obvious here or that I am using the wrong keywords for my search. If any of the latter two, my apologies please give me a hint.
Thanks.
I find this description hard to believe. Can you back it up with an SSCCE?
Your skepticism is well founded; my description was based on a distant memory of a remote implementation. With the sscce below, I see a scroll bar and the truncation reported by #uhm; I can only select from among the last, half-dozen, hidden entries by using the keyboard. I get similar results on these platforms:
Mac OS X: [Aqua Look and Feel for Mac OS X - com.apple.laf.AquaLookAndFeel]
Ubuntu: [The Java(tm) Look and Feel - javax.swing.plaf.metal.MetalLookAndFeel]
Windows: [The Java(tm) Look and Feel - javax.swing.plaf.metal.MetalLookAndFeel]
import java.awt.EventQueue;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
/** #see http://stackoverflow.com/questions/8270256 */
public class TallCombo extends JPanel {
private static final int N = 128;
public TallCombo() {
final JComboBox combo = new JComboBox();
for (int i = 0; i < N; i++) {
combo.addItem("Item " + Integer.valueOf(i));
}
combo.setMaximumRowCount(N / 2);
this.add(combo);
}
private void display() {
JFrame f = new JFrame("TallCombo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
System.out.println(UIManager.getLookAndFeel());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new TallCombo().display();
}
});
}
}
I found this example: http://www.javaprogrammingforums.com/awt-java-swing/11457-jcombobox-scroll-bars.html (at the bottom)

Categories