java paint applet - need help adding action on radio buttons - java

I need to make a java applet that allows the user to paint with the mouse. When the applet is launched, a second window opens that allows the user to select one of 6 different colors to paint with.
First, I wrote code to construct a toolbar window which contains a getcurrentcolor method. I can't seem to link the button press with the color change.
If I launch the applet, the toolbarwindow opens successfully and I'm able to paint in black, so my only problem is selecting a color on the toolbar window and painting in that color.
toolbar code:https://gist.github.com/anonymous/3c053c69112f46d17440
painting applet code: https://gist.github.com/anonymous/aca7929dbcfc08008f30

I gave an approach here for 3 buttons, you can add the rest. The idea is that you keep a currently selected color field and update it each time a button is selected via the ActionListener. A map from the button to the color it represents is not necessary, but makes the code more manageable.
public class ToolBarWindow extends JFrame {
private static Map<JRadioButton, Color> colors = new HashMap<>();
private static Color currentColor = Color.BLACK;
public static void main(String[] args) {
ToolBarWindow frame = new ToolBarWindow();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Colors");
frame.setVisible(true);
}
public ToolBarWindow() {
JPanel jpRadioButtons = new JPanel();
jpRadioButtons.setLayout(new GridLayout(3, 1));
// put the other colors
JRadioButton red = new JRadioButton("red");
JRadioButton black = new JRadioButton("black");
JRadioButton magenta = new JRadioButton("magenta");
red.addActionListener(new MyActionListener());
black.addActionListener(new MyActionListener());
magenta.addActionListener(new MyActionListener());
jpRadioButtons.add(red);
jpRadioButtons.add(black);
jpRadioButtons.add(magenta);
colors.put(red, Color.RED);
colors.put(black, Color.BLACK);
colors.put(magenta, Color.MAGENTA);
add(jpRadioButtons, BorderLayout.WEST);
ButtonGroup bg = new ButtonGroup();
bg.add(red);
bg.add(black);
bg.add(magenta);
}
Color getCurrentColor() {
return currentColor;
}
private class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
currentColor = colors.get(e.getSource());
}
}
}

I get the feeling your professor wants you to make your own. Here is an example I threw together in 10 minutes or so. its very rough and lacking good coding style but if you need to know what is involved, it should be useful. The example code prints out the color whenever you have selected it.
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
public class MyColorChooser extends Component
{
private Color[] colors;
private Color selectedColor;
public MyColorChooser(Color ... colors)
{
this.colors = colors;
this.selectedColor = colors[0];
this.addMouseListener
(
new MouseAdapter()
{
#Override public void mouseClicked(MouseEvent e)
{
int tileWidth = MyColorChooser.this.getWidth();
tileWidth /= MyColorChooser.this.colors.length;
int index = e.getX()/(tileWidth);
MyColorChooser.this.selectedColor = MyColorChooser.this.colors[index];
}
}
);
}
#Override public void paint(Graphics renderer)
{
int width = this.getWidth()/this.colors.length;
int height = this.getHeight();
for(int i = 0; i < this.colors.length; i++)
{
renderer.setColor(this.colors[i]);
renderer.fillRect(width*i,0,width,height);
}
}
public Color getSelectedColor()
{
return this.selectedColor;
}
public static void main(String ... args) throws Throwable
{
JFrame f = new JFrame();
f.setSize(200,100);
f.getContentPane().setLayout(null);
MyColorChooser chooser = new MyColorChooser
(
Color.RED,
Color.GREEN,
Color.BLUE,
Color.YELLOW,
Color.WHITE,
Color.BLACK
);
f.getContentPane().add(chooser);
chooser.setBounds(0,0,200,50);
f.setVisible(true);
Color lastColor = chooser.getSelectedColor();
for(;;)
{
if(!chooser.getSelectedColor().equals(lastColor))
{
lastColor = chooser.getSelectedColor();
System.out.printf("Selected Color:%s\n",lastColor.toString());
}
Thread.sleep(100);
}
}
}

Related

Changing Image by pressing jbutton java

Hello I am having trouble with my code and I have been trying to figure out what is wrong for a few days and looked at somewhat relevant programs for help and can not figure it out. The program is supposed to change the the image of a traffic light based on what button you press: red, yellow, or green. There are 3 classes. I am running the program in eclipse.
CLass 1 trafficLight that contains the main method:
import javax.swing.*;
import java.awt.*;
public class trafficLight
{
//-----------------------------------------------------------------
// Creates and displays the main program frame.
//-----------------------------------------------------------------
public static void main(String[] args)
{
JFrame frame = new JFrame("CHANGE TRAFFIC LIGHT");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
trafficLightPanel lights = new trafficLightPanel();
trafficLightControls controls = new trafficLightControls(lights);
JPanel panel = new JPanel();
panel.setBackground(Color.blue);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(Box.createRigidArea (new Dimension (0, 20)));
panel.add(lights);
panel.add(Box.createRigidArea (new Dimension (0, 10)));
panel.add(controls);
panel.add(Box.createRigidArea (new Dimension (0, 10)));
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
The second class trafficLightPanel that contain the imageicons part:
import java.awt.*;
import javax.swing.*;
public class trafficLightPanel extends JPanel
{
public int count, redCount, yellowCount, greenCount;
private ImageIcon none, red, yellow, green;
private JLabel imageLabel;
//-----------------------------------------------------------------
// Constructor: Sets up the images and the initial state.
//-----------------------------------------------------------------
public trafficLightPanel()
{
none = new ImageIcon("nonePic.png");
red = new ImageIcon("redPic.png");
yellow = new ImageIcon("yellowPic.png");
green = new ImageIcon("greenPic.png");
setBackground(Color.black);
redCount = 1; yellowCount = 2; greenCount = 3;
imageLabel = new JLabel(none);
add(imageLabel);
}
//-----------------------------------------------------------------
// Paints the panel using the appropriate image.
//-----------------------------------------------------------------
public void paintComponent(Graphics page)
{
super.paintComponent(page);
if (count == redCount)
{
imageLabel.setIcon(red);
}
if (count == yellowCount)
{
imageLabel.setIcon(yellow);
}
if (count == greenCount)
{
imageLabel.setIcon(green);
}
}
//-----------------------------------------------------------------
// Sets the status of the traffic light.
//-----------------------------------------------------------------
public void setCount(int newCount)
{
count = newCount;
}
}
The third class trafficLightControls containing the jbuttons:
//********************************************************************
// Represents the control panel for the traffic light program.
//********************************************************************
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class trafficLightControls extends JPanel
{
private trafficLightPanel lights;
private JButton red, yellow, green;
//-----------------------------------------------------------------
// Sets up the traffic light control panel.
//-----------------------------------------------------------------
public trafficLightControls(trafficLightPanel lightPanel)
{
lights = lightPanel;
red = new JButton("RED");
red.addActionListener(new redListener());
yellow = new JButton("YELLOW");
yellow.addActionListener(new yellowListener());
green = new JButton("GREEN");
green.addActionListener(new greenListener());
setBackground(Color.black);
add(red);
add(yellow);
add(green);
}
//*****************************************************************
// Represents the listener for the red button.
//*****************************************************************
private class redListener implements ActionListener
{
//--------------------------------------------------------------
// sets count to redCount and repaints the lights panel.
//--------------------------------------------------------------
public void actionPerformed(ActionEvent event)
{
lights.setCount(lights.redCount);
lights.repaint();
}
}
//*****************************************************************
//Represents the listener for the yellow button.
//*****************************************************************
private class yellowListener implements ActionListener
{
//--------------------------------------------------------------
//sets count to yellowCount and repaints the lights panel.
//--------------------------------------------------------------
public void actionPerformed(ActionEvent event)
{
lights.setCount(lights.yellowCount);
lights.repaint();
}
}
//*****************************************************************
//Represents the listener for the green button.
//*****************************************************************
private class greenListener implements ActionListener
{
//--------------------------------------------------------------
//sets count to green count and repaints the lights panel.
//--------------------------------------------------------------
public void actionPerformed(ActionEvent event)
{
lights.setCount(lights.greenCount);
lights.repaint();
}
}
}
Each time I click a button it is supposed to set the count in the trafficLightPanel object, lights, to the count that corresponds to the color, then based on the count the image is supposed to be replaced by the corresponding image. The components are all put together with a box layout.
For some reason only red will work... It starts out displaying the nonePic, the one without any light, and when I click red it displays redPic. If I click on any before or after clicking RED button, the others do not display. If I click one of the others first then RED button, red can still display for some reason. All images are in the root folder(is this the correct name?), the one containing the src and bin folders.
I thought maybe something was wrong with the count, and I tried doing something like adding a jLabel that would display the count each time into the program with the box layout but it does not display anything(this attempt is not in the code). I also tried putting the jLabel into the trafficLightControls class and adding it along with the add(red) add(yellow).... but it would not display anything. Another thing I tried was to change the text of the buttons each time to displaying the color with the count as an alternative to the jLabel attempt. I tried using .setText("") method like red.setText("") in the listener class for red. I would appreciate it if anyone could explain how to add a jLabel and change the text of the button as I have described in this particular little paragraph, as it is something I would like to know how to do to for future reference, though it is not necessary to solving my problem so its ok to not help out with this little paragraph.
Thank you very much for any help anyone offers!
edit: (I am sorry I left in remnants of my attempts at making jLabels to test the code but I removed them, though they did not affect the code I believe, I attempted to use them because of my problem. I am very sorry if this confused anyone)
There's no need to call repaint() and you shouldn't override paintComponent if all you're doing is swapping ImageIcons. Simply call setIcon(...) on your JLabel is all that is needed. The model will trigger a repainting of the view itself.
Getting rid of your paintComponent override and changing setCount to something as simple as this could work:
public void setCount(int newCount) {
count = newCount;
Icon icon = null;
switch (count) {
case 1:
icon = red;
break;
case 2:
icon = yellow;
break;
case 3:
icon = green;
break;
default:
icon = null;
break;
}
imageLabel.setIcon(icon);
}
For example, my MCVE, one that uses an enum and a Map to simplify the code a bit.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class Traff2 extends JPanel {
public Traff2() {
Traff2LightPanel lightPanel = new Traff2LightPanel();
Traff2LightControlsPanel controlsPanel = new Traff2LightControlsPanel(lightPanel);
setLayout(new BorderLayout());
add(lightPanel, BorderLayout.CENTER);
add(controlsPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
Traff2 mainPanel = new Traff2();
JFrame frame = new JFrame("Traffic");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
enum Light {
NONE(""), RED("Red"), YELLOW("Yellow"), GREEN("Green");
private String text;
private Light(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
#SuppressWarnings("serial")
class Traff2LightPanel extends JPanel {
private Map<Light, Icon> lightColorMap = new EnumMap<>(Light.class);
private JLabel imageLabel = new JLabel();
private Light light = Light.NONE;
public Traff2LightPanel() {
// fill the map
lightColorMap.put(Light.NONE, new ImageIcon("nonePic.png"));
lightColorMap.put(Light.RED, new ImageIcon("redPic.png"));
lightColorMap.put(Light.YELLOW, new ImageIcon("yellowPic.png"));
lightColorMap.put(Light.GREEN, new ImageIcon("greenPic.png"));
imageLabel.setIcon(lightColorMap.get(Light.NONE));
add(imageLabel);
}
// when changing the light field,
// also set the ImageIcon
public void setLight(Light light) {
this.light = light;
imageLabel.setIcon(lightColorMap.get(light));
}
public Light getLight() {
return light;
}
}
#SuppressWarnings("serial")
class Traff2LightControlsPanel extends JPanel {
private Traff2LightPanel lightPanel;
public Traff2LightControlsPanel(Traff2LightPanel lightPanel) {
this.lightPanel = lightPanel;
for (Light light : Light.values()) {
if (light == Light.NONE) {
continue;
}
add(new JButton(new LightAction(light)));
}
}
// use an AbstractAction...
// like an ActionListener on "steroids"
private class LightAction extends AbstractAction {
private Light light;
public LightAction(Light light) {
super(light.getText());
this.light = light;
}
#Override
public void actionPerformed(ActionEvent e) {
lightPanel.setLight(light);
}
}
}

JPanel not showing label when its set to an array of icons, but will show when its a single icon

Current code
ThreeColorButton class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ThreeColorButton {
private static CompositeIcon icons = new CompositeIcon();
private static JPanel panel = new JPanel();
private static JFrame frame = new JFrame();
private static JLabel label = new JLabel();
public static void main(String[] args) {
//create rgb buttons
JButton redButton = new JButton("Red");
JButton greenButton = new JButton("Green");
JButton blueButton = new JButton("Blue");
//add rgb buttons to panel
panel.add(redButton);
panel.add(greenButton);
panel.add(blueButton);
//add action listeners to buttons
redButton.addActionListener(buttonListener(40, Color.red));
greenButton.addActionListener(buttonListener(40, Color.green));
blueButton.addActionListener(buttonListener(40, Color.blue));
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.NORTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private static ActionListener buttonListener(final int size,final Color color) {
return new ActionListener() {
public void actionPerformed(ActionEvent event) {
SquareIcon icon = new SquareIcon(size, color);
icons.addIcon(icon);
label.setIcon(icons);
frame.add(label, BorderLayout.SOUTH);
frame.repaint();
frame.pack();
}
};
}
}
CompositeIcon code
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class CompositeIcon implements Icon{
private ArrayList<Icon> icons;
private int size;
public CompositeIcon() {
icons = new ArrayList<Icon>();
}
public void paintIcon(Component c, Graphics g, int x, int y) {
int position = x;
for(Icon z : icons) {
z.paintIcon(c,g,position,y);
position = position + z.getIconWidth();
}
}
public int getIconHeight() {
return size;
}
public int getIconWidth() {
int total = 0;
for(Icon z : icons) {
total = total + z.getIconWidth();
}
return total;
}
public void addIcon(Icon z) {
icons.add(z);
}
}
SquareIcon class is only a simple little class that creates a square of a single color with a given size.
My question is, in my ThreeColorButton class, when I run it, it doesn't show any icons when I press either of the RGB buttons. However, in the buttonListener method, if I set label.setIcons(icons) to label.setIcons(icon), it shows a single square and it doesnt place it side by side.
I can't seem to figure out whats causing this behavior. Is there a problem with displaying an array of icons using JLabel?
There is nothing to paint in the label since the height of your Icon is 0, since you never set the size.
I would suggest code something like:
#Override
public int getIconHeight()
{
int size = 0;
for(Icon z : icons)
{
size = Math.max(size, z.getIconHeight());
}
return size;
}
You may want to check out Compound Icon. Similar to your class but it has more features. It supports horizontal/vertical/stacked icon and icon alignment options.
It doesn't support dynamically adding Icons so you would need to change that. I might looking adding that feature myself (when I get time) :)
I can't seem to figure out whats causing this behavior. Is there a problem with displaying an array of icons using JLabel?
Yes, as #mKorbel mentioned, there is a problem. A JLabel can only display a single icon. If you want to display n icons, you will need n JLabel instances.

How to use JColorChooser given Color in other classes?

I have been learning Java just a few weeks so bear that in mind.. I have managed to solve many issues myself until this one:
What I am trying to achieve is using JComponent in a tabbed view so that in one tab you're able to pick a colour (my println shows it actually gets an sRGB value). Then in another class I should be able to get this value and use it in coloring JPanels.
Can I just pass the Color object or what is the best way to achieve. What I am trying here is not working too well. Sorry for the messy code - I am a newbie...
Here is the main part of the color chooser:
public class Colors extends JPanel implements ChangeListener {
private JColorChooser jcc = null;
protected JLabel title;
static Color newColor;
public Colors() {
super(new BorderLayout());
//Set up the banner at the top of the window
title = new JLabel();
//Set up color chooser for setting text color
jcc = new JColorChooser(title.getForeground());
jcc.getSelectionModel().addChangeListener(this);
jcc.setBorder(BorderFactory.createTitledBorder(
"Choose New Color"));
AbstractColorChooserPanel[] panels=jcc.getChooserPanels();
for(AbstractColorChooserPanel p:panels) {
String displayName = p.getDisplayName();
switch (displayName) {
case "HSV":
jcc.removeChooserPanel(p);
break;
case "HSL":
jcc.removeChooserPanel(p);
break;
case "CMYK":
jcc.removeChooserPanel(p);
break;
case "RGB":
jcc.removeChooserPanel(p);
break;
}
}
add(jcc, BorderLayout.PAGE_END);
}
public void stateChanged(ChangeEvent e) {
Color newColor = jcc.getColor();
title.setForeground(newColor);
System.out.println("color = " + newColor);
}
public static Color getNewCol() {
System.out.println("this now =" + newColor);
return newColor;
}
public static Component createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Color Selector");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new Colors();
return newContentPane;
}
}
And then I am trying to get hold of the chosen color in the Main.Java class in this way (which is likely wrong). I also note that the value seems to remain always null - probably I am instantiating in a wrong way (value gets lost?)
a.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Click add");
value++;
if (value < 21) {
JButton jb1 = new JButton();
//How to get the COLOR from the JColorChooser class?
Color box = Colors.getNewCol();
jb1.setBackground(box);
jb1.setOpaque(true);
//FOR TEST ONLY jb1.setBackground(Color.BLUE);
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.add(jb1);
panel.setVisible(true);
//window.add(paneeli);
window.pack();
d = new Dimension(700, 500);
window.setSize(d);
Probably the answer is too obvious but I just can't see it at the moment.
I'd get take your static newColor variable and make it non-static. In my ChangeListener I'd fire the JPanel's innate PropertyChangeSupport so that listeners can be notified. The key is to use an observer design pattern -- For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
import javax.swing.event.*;
#SuppressWarnings("serial")
public class TestColors extends JPanel {
private JTabbedPane tabbedPane = new JTabbedPane();
private Colors colors = new Colors();
private JPanel colorDisplayPanel = new JPanel();
public TestColors() {
tabbedPane.add("Colors", colors);
tabbedPane.add("Color Display", colorDisplayPanel);
setLayout(new BorderLayout());
add(tabbedPane);
// add a PropertyChangeListener to our Colors isntance.
colors.addPropertyChangeListener(Colors.NEW_COLOR,
new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
Color color = (Color) evt.getNewValue();
colorDisplayPanel.setBackground(color);
}
});
}
private static void createAndShowGui() {
JFrame frame = new JFrame("TestColors");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestColors());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class Colors extends JPanel implements ChangeListener {
public static final String NEW_COLOR = "new color";
private JColorChooser jcc = null;
protected JLabel title;
private Color newColor = null;
public Colors() {
super(new BorderLayout());
// Set up the banner at the top of the window
title = new JLabel("This is my Banner!", SwingConstants.CENTER);
// Set up color chooser for setting text color
jcc = new JColorChooser(title.getForeground());
jcc.getSelectionModel().addChangeListener(this);
jcc.setBorder(BorderFactory.createTitledBorder("Choose New Color"));
add(jcc, BorderLayout.CENTER);
add(title, BorderLayout.PAGE_START);
}
public void stateChanged(ChangeEvent e) {
// Color newColor = jcc.getColor();
Color oldValue = newColor;
newColor = jcc.getColor();
// fire a notification to the Colors JPanel's property change support
// object. Any listeners will be notified of the color change
firePropertyChange(NEW_COLOR, oldValue, newColor);
title.setForeground(newColor);
}
public Color getNewCol() {
System.out.println("this now =" + newColor);
return newColor;
}
}

How to add start button to Simon Says Game in Java?

I want to draw an inscribed circle. A circle that is empty with no fill but making it have a full stroke. My code :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package simon;
import java.awt.*;
import java.awt.event.*; //This allows us to detect user input
import java.awt.image.BufferedImage;
import javax.swing.*; //This allows us to use graphical elements, colors, etc.
/**
*
* #author User
*/
public class SimonA {
//First, we create all the elements of our program
//Here are the variables...
public static int score = 0;
public static int color = 0; //0 = yellow, 1 = red, 2 = blue, 3 = green
public static Boolean flash = false; //This is used to make the panel blink
public static Boolean running = false;
//Here are the widgets (objects)....
public static JFrame frame = new JFrame();
public static JPanel buttons = new JPanel();
public static JPanel buttons1 = new JPanel();//These buttons will all be square (the default). Different packages can be used to change the shape
public static JPanel controls = new JPanel();
public static JButton red = new JButton();
public static JButton yellow = new JButton();
public static JButton green = new JButton();
public static JButton blue = new JButton();
public static JButton toggle = new JButton("Start"); //Click this button to see a sample flash
public static JLabel scoreTxt = new JLabel("Score: " + score, SwingConstants.CENTER); //This object (a label element) displays the score variable's value
public static Timer blink = new Timer(600,new Ticker()); //This is used to time the duration of the flash
public static BufferedImage img = new BufferedImage(400, 400, BufferedImage.TYPE_INT_ARGB);
public static Graphics2D g = img.createGraphics();
public static JLabel space = new JLabel();
JPanel panelBgImg = new JPanel() {
public void paintComponent(Graphics g){
g.setStroke(new BasicStroke(8));
g.fillOval(0, 0, 400, 400);
}
};
/*Timers are important for any program in which something "moves" at set durations. In this case, every tenth of
a second, the timer will generate an event. In this case, we are using it to determine that the active tile
will flash for 600ms, or 6/10 of a second. Obvously, then, 1000 makes the timer generate an event once-per-second. */
public static void main (String[] args)
{
frame.setBackground(Color.gray);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //This means that when we close the window with [x] the program ends
frame.setSize(new Dimension(400,400));
frame.setForeground(Color.black);
frame.setTitle("Simon");
frame.setLayout(new BorderLayout()); //Remember this from the LayoutManager test?
buttons.setLayout(new GridLayout(1,2));
buttons1.setLayout(new GridLayout(1,2));//The buttons are placed in this panel, which is set as a 2x2 grid
yellow.setBackground(Color.yellow);
yellow.addActionListener(new YellowPressed()); //This triggers the "procedure" that runs when the yellow button is pressed
yellow.setPreferredSize(new Dimension(200,200));
//Note, the other buttons will take their cue for size from the above statement, since they are all in the same grid
//We do not need to specify dimensions again
red.setBackground(Color.red);
red.addActionListener(new RedPressed());
red.setPreferredSize(new Dimension(200,200));
blue.setBackground(Color.blue);
blue.addActionListener(new BluePressed());
green.setBackground(Color.green);
green.addActionListener(new GreenPressed());
green.setPreferredSize(new Dimension(200,200));
//Adding the four buttons to the panel called "buttons"
buttons1.add(yellow);
buttons.add(red);
buttons.add(green);
buttons1.add(blue);
//The control panel on the bottom is a gride of one row and two columns
controls.setLayout(new GridLayout(2,1));
controls.add(scoreTxt);
controls.add(toggle);
toggle.addActionListener(new ToggleOn());
//We now add the panels to the frame according to the border layout
frame.add(buttons,BorderLayout.NORTH);
frame.add(controls,BorderLayout.CENTER);
frame.add(buttons1,BorderLayout.SOUTH);
//This .pack() method removes any excess whitespace around your elements
//Sometimes it results in a better look, and sometimes not.
frame.pack();
frame.setVisible(true);
}
public static class ToggleOn implements ActionListener {
public void actionPerformed(ActionEvent event)
{
//This toggles the main button between Start and Stop
//If it's running, stop it from running
//If it's not running, start it running
running = !running;
if (running)
{
toggle.setText("Stop");
//To demonstrate how the code might work, a sample flash
color = 3; //Change the color to "active"
blink.start(); //Starts the 6/10 second timer
score += 10;
scoreTxt.setText("Score: " + score);
}
else
{
toggle.setText("Start");
}
}
}
public static class YellowPressed implements ActionListener {
public void actionPerformed(ActionEvent event)
{
//Right now, the buttons just print to the screen
//The "real" program would implement other instructions here
System.out.println("Yellow");
}
}
public static class RedPressed implements ActionListener {
public void actionPerformed(ActionEvent event)
{
System.out.println("Red");
}
}
public static class BluePressed implements ActionListener {
public void actionPerformed(ActionEvent event)
{
System.out.println("Blue");
}
}
public static class GreenPressed implements ActionListener {
public void actionPerformed(ActionEvent event)
{
System.out.println("Green");
}
}
public static class Ticker implements ActionListener {
public void actionPerformed(ActionEvent event)
{
//When the timer triggers, if a button is active,
//set it back to its original color 6/10 of a second later
flash = !flash;
if (flash) //If the button is to be lit, turn it white
{
if (color == 0)
yellow.setBackground(Color.white);
else if (color == 1)
red.setBackground(Color.white);
else if (color == 2)
blue.setBackground(Color.white);
else if (color == 3)
green.setBackground(Color.white);
}
else //Otherwise, change it back to its original color
{
if (color == 0)
yellow.setBackground(Color.yellow);
else if (color == 1)
red.setBackground(Color.red);
else if (color == 2)
blue.setBackground(Color.blue);
else if (color == 3)
green.setBackground(Color.green);
blink.stop();
}
}
}
}
Here is what I am using to create the circle, for some reason it does not create the circle:
JPanel panelBgImg = new JPanel() {
public void paintComponent(Graphics g){
g.setStroke(new BasicStroke(8));
g.fillOval(0, 0, 400, 400);
}
};
First of all, you're never (in the code provided) adding the panelBgImg to any component, so nothing is going to show it (you have to add it to a frame or another panel somewhere).
You should also change your paintComponent method though...
JPanel panelBgImg = new JPanel() {
public void paintComponent(Graphics g){
//Call super method to draw background
super.paintComponent(g);
//Cast to Graphics2D to use setStroke
Graphics2D g2d = (Graphics2D) g;
//Set the color of the circle you want to draw
g2d.setColor(Color.RED);
g2d.setStroke(new BasicStroke(8));
//g2d.fillOval(0, 0, 400, 400);
//Use drawOval instead of fillOval (otherwise it will be filled with the color)
g2d.drawOval(0, 0, 400, 400);
}
};

how to draw colors

Ok so I have my main class which got some buttons one for a triangle and the other for an
oval and boxes.
And i got a button for ColorChooser I want to click on it and ColorChooser show up. I have
the class for the oval and triangles and ColorChooser and i set each one of them to a mode
in my main program.
So this is my main program with only the boxes and ColorChooser:
As you can see im using modes for each button and i set mode 4 for ColorChooser
If you want me to add the box class or the ColorChooser class i will if it is not making
sense. I just dont want it to be any longer.
This is my main program:
import java.awt.*;
import java.util.ArrayList;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
public class Kaleidescope extends JFrame implements MouseListener, ActionListener,
MouseMotionListener
{
Box b;
ArrayList<Box> boxes; // list of boxes
ColorChooser oo;
ColorChooser[] colors;
int colorCount;
// Buttons
JButton boxButton;
JButton ColorButton;
int x1, y1; // mousePressed
int w1, z1; // mouseEntered
int mode =1; // 1 = line, 2= boxes, 3 = oval, 4= text, 5 = SG, twoLines = 7.
public static void main( String[] args )
{
System.out.println("hi there.");
new Kaleidescope();
}
public Kaleidescope()
{
setDefaultCloseOperation( EXIT_ON_CLOSE );
addMouseListener(this);
addMouseMotionListener(this);
boxes = new ArrayList<Box>();
colors = new ColorChooser[20];
colorCount = 0;
setLayout( new FlowLayout() );
boxButton = new JButton("Boxes");
add(boxButton);
boxButton.addActionListener( this );
ColorButton = new JButton("Color Chooser");
add(ColorButton);
ColorButton.addActionListener( this);
setSize( new Dimension(500,500) );
setVisible(true);
}
// returns a random color
public Color randomColor()
{
int red = (int)(Math.random()*255);
int green = (int)(Math.random()*255);
int blue = (int)(Math.random()*255);
return new Color(red,green,blue);
}
public void mouseClicked( MouseEvent e )
{
// box
if ( mode == 2)
{
boxes.add(new Box(e.getX(), e.getY(), randomColor()));
}
repaint();
}
//action performed
public void actionPerformed( ActionEvent e )
{
if ( e.getSource()==TriangleButton ) { mode = 1;}
else if ( e.getSource()==boxButton ) { mode = 2;}
else if ( e.getSource()==ovalButton) { mode = 3;}
else if ( e.getSource()==ColorButton) { mode = 4;}
//clear all
else if (e.getSource() == clearButton)
{
boxes.clear();
triangles.clear();
ovals.clear();
}
repaint();
}
public void mouseEntered( MouseEvent e ) { }
public void mousePressed( MouseEvent e ) { }
public void mouseExited( MouseEvent e ) { }
public void mouseReleased( MouseEvent e ) {}
public void mouseMoved( MouseEvent e ) {}
public void mouseDragged( MouseEvent e ){ }
}
public void paint( Graphics g )
{
//draw/paint box triangle and oval
super.paint(g);
for (Box box : boxes)
{
box.drawMe(g);
}
}
}
here is my colorChooser class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.colorchooser.*;
public class ColorChooser extends JPanel implements ChangeListener
{
public static final long serialVersionUID = 1L;
public JColorChooser tcc;
public JLabel banner;
public ColorChooser()
{
super(new BorderLayout());
banner = new JLabel("",JLabel.CENTER);
banner.setOpaque(true);
banner.setPreferredSize(new Dimension(100, 65));
JPanel bannerPanel = new JPanel(new BorderLayout());
bannerPanel.add(banner, BorderLayout.CENTER);
bannerPanel.setBorder(BorderFactory.createTitledBorder("Banner"));
//Set up color chooser for setting text color
tcc = new JColorChooser(banner.getForeground());
tcc.getSelectionModel().addChangeListener(this);
tcc.setBorder(BorderFactory.createTitledBorder("Choose Text Color"));
add(bannerPanel, BorderLayout.CENTER);
add(tcc, BorderLayout.PAGE_END);
}
public void stateChanged(ChangeEvent e)
{
Color newColor = tcc.getColor();
banner.setForeground(newColor);
}
private static void createAndShowGUI()
{
//Create and set up the window.
JFrame frame = new JFrame("ColorChooserDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new ColorChooser();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
Start by taking a look at How to Write an Action Listener and How to Use Color Choosers
Basically, attach a ActionListener to the JButton you want to activate the JColorChooser and when the actionPerformed method is called, use inbuilt functionality to show the default chooser window, for example (from the linked tutorial)...
Color newColor = JColorChooser.showDialog(
ColorChooserDemo2.this,
"Choose Background Color",
banner.getBackground());
Updated
Start by adding a Color instance variable to Kaleidescope, this will allow you to maintain a reference to the last chossen color
private Color currentPaintColor = Color.BLACK;
Next, when the ColorButton is pressed, you will want to create some kind of dialog to show the chooser in, this will allow you to wait until the user chooses a color and get the resulting color...
} else if (e.getSource() == ColorButton) {
ColorChooser chooser = new ColorChooser();
int result = JOptionPane.showConfirmDialog(this, chooser, "Color Chooser", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
currentPaintColor = chooser.getChoosenColor();
}
} //clear all
You'll also want to change the stateChanged method in ColorChooser to make it more meaningful...
public void stateChanged(ChangeEvent e) {
Color newColor = tcc.getColor();
banner.setBackground(newColor);
}
Now, the question is, what do you want to do with this new color? Do you want to apply it to all the current shapes you are painting? If so you need to set the color before painting the shapes...
public void paint(Graphics g) {
//draw/paint box triangle and oval
super.paint(g);
g.setColor(currentPaintColor);
for (Box box : boxes)
{
box.drawMe(g);
}
}
Or do you only want to apply the color to new objects added after the change?
You should avoid overriding paint of top level containers, lots of reason, they aren't double buffered, which will cause flickering when they are updated and you will be painting over the top of everything else on the frame and you can potentially paint under the frame borders...
Instead you should use something JPanel and override it's paintComponent method, take a look at Performing Custom Painting for more details
You need to clarify just what you expect a mode = 4 will do with your program. I can understand using JButton presses to set shape modes (object state) that will alter the behavior of your MouseListener, but I don't see how a color chooser will fit into this model, and in fact believe that it likely won't. I don't have the rest of your code, nor do I have the specifics of your assignment, but I'm going to make some recommendations based on guesses, and thus these will necessarily be weak recommendations.
I'm guessing that you want to have a JColorChooser dialog displayed when the color button is pressed.
And that the user then can select a Color that will be the color of the drawn shapes.
If so, then likely you shouldn't have the color chooser button (which should be named colorChooserButton) set a numeric node. Rather, it should open your color choosing dialog, and after the user has selected a color, then you should set a Color field in your drawing class, not the mode value.
Rather the modes should only be used to select an appropriate shape that the MouseListener will use to determine what shape to draw.
Myself, I wouldn't use numeric modes but rather an enum to define this state, but that is probably something you'll learn later in your programming education.
If my assumptions are incorrect, then please clarify them.
As an aside, note that you should not draw in a paint(Graphics g) method, and should not draw directly in the JFrame. Rather you should draw in the paintComponent(Graphics g) method override of a JPanel or JComponent.
Here's a runnable example of how JColorChooser can be used to set the color for different tasks. Feel free to ask questions if you are unclear about anything.
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.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ColorChooserPaintExample {
private Color color = Color.BLUE;
private ColorPanel colorPanel = new ColorPanel();
public ColorChooserPaintExample() {
final JFrame frame = new JFrame("My Color Chooser Demo");
JButton chooseColor = new JButton("Change Color of Panel");
chooseColor.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
color = JColorChooser.showDialog(frame, "Choose a Color for Panel", color);
colorPanel.repaint();
}
});
frame.add(colorPanel);
frame.add(chooseColor, BorderLayout.SOUTH);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private class ColorPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.fillRect(0, 0, getWidth(), getHeight());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new ColorChooserPaintExample();
}
});
}
}

Categories

Resources