Farben in Variablen speichern

kpj

Mitglied
Hi,
ich habe ein Problem bei der Eingabe eines Nutzers, der eine Farbe selber bestimmen soll:

Java:
String farbe=meinLeser.liesZeichenkette();
            myColor=Color.farbe;

"meinLeser" und "liesZeichenkette" sind schon vorgegeben, um einen String auszulesen.
Wie kriege ich es nun hin, dass ich "myColor" z.B. bei "g.setColor(myColor);" benutzen kann?
Danke schonmal im Vorraus,
kpj
 
Dazu musst du deine Farbe als "Color" speichern:
Java:
java.awt.Color myColor = new Color(100,100,100);
 
Deklariert hatte ich sie ja schon mit
Java:
private Color myColor=Color.blue;

Aber jetzt will ich ja, dass man sie durch Eingaben des Benutzers verändern kann.
kpj

PS: danke für deine schnelle Antwort trotzdem^^
 
Hm,
habt ihr vll eine Idee wie ich dem Rechteck, das zuerst die Farbe blau hatte
Java:
private Color myColor=Color.blue;
g.setColor(myColor);
g.fillRect(waagerecht, senkrecht, 20, 20);
eine andere Farbe geben könnte?
kpj

Edit:
oder

if (string.equals("red")) {
color = Color.RED;
} else if ..
...
Ups zu früh geschrieben^^Danke für den Tipp
Wenn das Gegenteil für "==", "!=" wäre,
was wäre dann das Gegenteil zu "string.equals("text")" ?
 
Zuletzt bearbeitet:
Java:
g.setColor(myColor);
g.fillRect(waagerecht, senkrecht, 20, 20);

// und dan dort wo due die Farbe änderst
myColor = Color.GREEN;
repaint();

EDIT:
In der Annahme, dass das ganze g... Zeugt in der paintComponent-Methode drin ist, was auch sein sollte.
 
klar, füge folgende Befehle aus:

g.setColor(andereColor);
g.fillRect(waagerecht, senkrecht, 20, 20);

ansonsten kannst du einmal gezeichnetes nicht mehr beeinflussen, das ist kein fassbares Objekt,
sondern 400 Pixel von x000, die zufällig eine bestimmte Farbe haben

was anderes wäre es, wenn man seine Daten als Objekte der Klasse Recheckt usw. in einer Liste speichert,
die kann man leicht in ihrer Farbe ändern (und dann immer noch neuzeichen)
 
ein kleines Beispiel:
Java:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class JFSize {

	private static Color color = Color.GREEN;
	
	private static final int SIZE = 200;

	public static void main(String[] args) {
		JFrame frame = new JFrame("Foo");
		frame.setPreferredSize(new Dimension(SIZE, SIZE));
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());
		
		final JPanel drawPanel = new JPanel() {
			@Override
			public void paintComponent(Graphics g) {
				super.paintComponent(g);
				g.setColor(color);
				g.fillRect(0, 0, 100, 100);
			}
		};

		JButton button = new JButton("OK");
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(color == Color.GREEN) {
					color = Color.RED;
					drawPanel.repaint();
				} else {
					color = Color.GREEN;
					drawPanel.repaint();
				}
			}
		});
		panel.add(button, BorderLayout.SOUTH);
		panel.add(drawPanel, BorderLayout.CENTER);
		frame.getContentPane().add(panel);
		
		frame.pack();
		frame.setVisible(true);
	}
}
 
So ähnlich mit dem "if-else"-Prinzip hab ichs auch gemacht
Java:
if(antwort==1)
        {        
            write("Mögliche Farben: red, blue, green, yellow, cyan, white^^",50);
            String farbe=meinLeser.liesZeichenkette();
            if(farbe.equals("red"))
            {
                myColor=Color.red;
            }
            if(farbe.equals("blue"))
            {
                myColor=Color.blue;
            }
            if(farbe.equals("green"))
            {
                myColor=Color.green;
            }
            if(farbe.equals("yellow"))
            {
                myColor=Color.yellow;
            }
            if(farbe.equals("cyan"))
            {
                myColor=Color.cyan;
            }
            if(farbe.equals("white"))
            {
                myColor=Color.white;
            }
        }

kpj
 
alternativ könnte man eine Map benutzen:
Java:
Map<String, Color> colorMap = new HashMap<String, Color>();
colorMap.put("red", Color.RED);
colorMap.put("blue", Color.BLUE);
colorMap.put("green", Color.GREEN);

System.out.println(colorMap.get("red"));
System.out.println(colorMap.get("green"));

//EDIT:
Color color = colorMap.get("idontknow");
if(color == null) {
	color = Color.BLACK;
}
System.out.println(color);
;-)
 
Schon länger her, da schrieb ich mal eine Erweiterte Color-Klasse, um standard HTML-Farben (Strings wie z.B. "#9afde4", "rgb(10%, 20%, 30%)", "rgb(45, 34, 56)" oder "maroon") zu parsen um eine entsprechende Farbe zu bekommen. Hier mal ein Auszug:
Java:
import java.awt.color.ColorSpace;

public final class Color
extends java.awt.Color
{
	/**
	 * serial version uid
	 */
	private static final long serialVersionUID = 6674118578427330427L;

	/*
	 * 16 predefined colors. Theese colors are considered to be html
	 * standard colors. Therefore some colors own the same names as
	 * in "java.awt.Color", but doesn't have the same values.
	 */
	@SuppressWarnings("hiding")
	public static final Color black = new Color(0, 0, 0);
	public static final Color maroon = new Color(128, 0, 0);
	@SuppressWarnings("hiding")
	public static final Color green = new Color(0, 128, 0);
	public static final Color olive = new Color(128, 128, 0);
	public static final Color navy = new Color(0, 0, 128);
	public static final Color purple = new Color(128, 0, 128);
	public static final Color teal = new Color(0, 128, 128);
	public static final Color silver = new Color(192, 192, 192);
	@SuppressWarnings("hiding")
	public static final Color gray = new Color(128, 128, 128);
	@SuppressWarnings("hiding")
	public static final Color red = new Color(255, 0, 0);
	public static final Color lime = new Color(0, 255, 0);
	@SuppressWarnings("hiding")
	public static final Color yellow = new Color(255, 255, 0);
	@SuppressWarnings("hiding")
	public static final Color blue = new Color(0, 0, 255);
	public static final Color fuchsia = new Color(255, 0, 255);
	public static final Color aqua = new Color(0, 255, 255);
	@SuppressWarnings("hiding")
	public static final Color white = new Color(255, 255, 255);
	@SuppressWarnings("hiding")
	public static final Color BLACK = black;
	public static final Color MAROON = maroon;
	@SuppressWarnings("hiding")
	public static final Color GREEN = green;
	public static final Color OLIVE = olive;
	public static final Color NAVY = navy;
	public static final Color PURPLE = purple;
	public static final Color TEAL = teal;
	public static final Color SILVER = silver;
	@SuppressWarnings("hiding")
	public static final Color GRAY = gray;
	@SuppressWarnings("hiding")
	public static final Color RED = red;
	public static final Color LIME = lime;
	@SuppressWarnings("hiding")
	public static final Color YELLOW = yellow;
	@SuppressWarnings("hiding")
	public static final Color BLUE = blue;
	public static final Color FUCHSIA = fuchsia;
	public static final Color AQUA = aqua;
	@SuppressWarnings("hiding")
	public static final Color WHITE = white;

	/**
	 * Parses html color strings like "#9afde4", "marron" aso.
	 * @param value
	 * @return instance of color
	 */
	public static Color parseColor(String value)
	{
		Color rc = null;
		value = value.trim();
		int rgb;
		if(value.startsWith("#")) {
			rgb = Integer.parseInt(value.substring(1, 7), 16);
			rc = new Color(rgb, false);
		} else if(value.startsWith("rgb")) {
			value.substring(4,value.length() - 1);
			String tmp[] = value.split(",");
			rgb = 0;
			for(int i = 0; i < tmp.length; i++) {
				rgb <<= 8;
				rgb |= (tmp[i].indexOf("%") <= 0)?
					(int) (Float.parseFloat(tmp[i].substring(0, tmp[i].length() - 1).trim()) * 2.55f)
					: Integer.parseInt(tmp[i].trim());
			}
			rc = new Color(rgb, false);
		} else {
			if(value.equalsIgnoreCase("black")) rc = black;
			if(value.equalsIgnoreCase("maroon")) rc = maroon;
			if(value.equalsIgnoreCase("green")) rc = green;
			if(value.equalsIgnoreCase("olive")) rc = olive;
			if(value.equalsIgnoreCase("navy")) rc = navy;
			if(value.equalsIgnoreCase("purple")) rc = purple;
			if(value.equalsIgnoreCase("teal")) rc = teal;
			if(value.equalsIgnoreCase("silver")) rc = silver;
			if(value.equalsIgnoreCase("gray")) rc = gray;
			if(value.equalsIgnoreCase("red")) rc = red;
			if(value.equalsIgnoreCase("lime")) rc = lime;
			if(value.equalsIgnoreCase("yellow")) rc = yellow;
			if(value.equalsIgnoreCase("blue")) rc = blue;
			if(value.equalsIgnoreCase("fuchsia")) rc = fuchsia;
			if(value.equalsIgnoreCase("aqua")) rc = aqua;
			if(value.equalsIgnoreCase("white")) rc = white;
		}
		if(rc == null) {
			throw new IllegalArgumentException("unkown color description \"" + value + "\"");
		}
		return rc;
	}

	public Color(ColorSpace cspace, float[] components, float alpha)
	{
		super(cspace, components, alpha);
	}

	public Color(float r, float g, float b, float a)
	{
		super(r, g, b, a);
	}

	public Color(float r, float g, float b)
	{
		super(r, g, b);
	}

	public Color(int rgba, boolean hasalpha)
	{
		super(rgba, hasalpha);
	}

	public Color(int r, int g, int b, int a)
	{
		super(r, g, b, a);
	}

	public Color(int r, int g, int b)
	{
		super(r, g, b);
	}

	public Color(int rgb)
	{
		super(rgb);
	}
}
 
Zuletzt bearbeitet von einem Moderator:
Ich hätte noch eine Frage:
Momentan arbeite ich mit BlueJ.
Wenn ich dann ein Programm schreibe, welches Konsole und ein GUI benutzt ist dies kein Problem.
Wenn ich mein Projekt als .jar exportiere, habe ich erstmal nur das GUI.
Kann ich die Konsole auf irgendeinem anderen Weg bekommen?
kpj
 

Zurück
Oben