473,799 Members | 2,837 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trying to change the color of a graphics object

1 New Member
I have a Jframe using a menubar to determine the color and shape of a graphics2d object, at the moment the color stays red no matter what. I think the problem is in the itemListener in the inner class myShape, but I dont know what it is.

Heres the code:
Expand|Select|Wrap|Line Numbers
  1. import java.awt.*;
  2. import javax.swing.*;
  3. import java.awt.event.*;
  4. import java.awt.Graphics2D.*;
  5. import java.awt.geom.*;
  6.  
  7.  
  8. /** A menu class that gives the option to display a circle or a rectangle
  9.  * that is either Green, Yellow, or Blue, it makes a text field to display
  10.  * which is shape/color is present
  11.  * @author Thomas Capranica
  12.  *
  13.  */
  14. public class menu implements ActionListener, ItemListener {
  15.     JMenuBar menuBar;
  16.     JMenu menu, submenu;
  17.     JMenuItem menuItem;
  18.     JCheckBoxMenuItem Yellow, Blue;
  19.     JRadioButtonMenuItem Rect, Circ;
  20.     JMenu firstMenu, secondMenu;
  21.     JTextField field = new JTextField(30);
  22.     JTextField field2 = new JTextField(30);
  23.     String color = "Red";
  24.     String shape = "Square";
  25.     boolean yellow = false;
  26.     boolean blue = false;
  27.  
  28.     public static void main(String[] args){
  29.         menu j = new menu();
  30.     }
  31.     public menu(){
  32.         JFrame frame = new JFrame("JMenus");
  33.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  34.  
  35.         field.setEditable(false);
  36.         field2.setEditable(false);
  37.  
  38.         field.setText("The Color is " + color);
  39.         field2.setText("The Shape is a " + shape);
  40.  
  41.         menuBar = new JMenuBar();
  42.         JPanel north = new JPanel();
  43.         north.setLayout(new GridLayout(1,2));
  44.         north.add(field);
  45.         north.add(field2);
  46.         frame.add(north,BorderLayout.NORTH);
  47.  
  48.         ButtonGroup Sgroup = new ButtonGroup();
  49.  
  50.         Yellow = new JCheckBoxMenuItem("Yellow");
  51.         Blue = new JCheckBoxMenuItem("Blue");
  52.         Yellow.addItemListener(this);
  53.         Blue.addItemListener(this);
  54.         Yellow.addItemListener(new myShape());
  55.  
  56.         Rect = new JRadioButtonMenuItem("Rectangle");
  57.         Circ = new JRadioButtonMenuItem("Circle");
  58.  
  59.         Sgroup.add(Circ);
  60.         Sgroup.add(Rect);
  61.  
  62.         firstMenu = new JMenu("Colors");
  63.         firstMenu.getAccessibleContext().setAccessibleDescription("" +
  64.                 "Sets the Colrors of the Object");
  65.         firstMenu.add(Yellow);
  66.         firstMenu.add(Blue);
  67.         firstMenu.addSeparator();
  68.  
  69.         secondMenu = new JMenu("Shapes");
  70.         secondMenu.add(Rect);
  71.         secondMenu.add(Circ);
  72.         firstMenu.add(secondMenu);
  73.         menuBar.add(firstMenu);
  74.  
  75.         frame.add(new myShape());
  76.         frame.setJMenuBar(menuBar);
  77.         frame.setSize(300,200);
  78.         frame.setVisible(true);
  79.     }
  80. //Checks to see which radioButton is selected, sets the shape accordingly (not done)    
  81.     public void actionPerformed(ActionEvent e){
  82.         field2.setText("Its A " + shape); 
  83.     }
  84.  
  85. // Checks to see which checkBoxes are checked, changes the color accordingly
  86.     public void itemStateChanged(ItemEvent e){
  87.  
  88.         JMenuItem source = (JMenuItem)(e.getSource());
  89.         String select = ((e.getStateChange() == ItemEvent.SELECTED) ?
  90.                 "selected":"unselected");
  91.         String which = source.getText();
  92.         if(which.equals("Yellow") && select.equals("selected"))
  93.             yellow = true;
  94.         else if(which.equals("Yellow") && select.equals("unselected"))
  95.             yellow = false;
  96.         else if(which.equals("Blue") && select.equals("selected"))
  97.             blue = true;
  98.         else if(which.equals("Blue") && select.equals("unselected"))
  99.             blue = false;
  100.  
  101.          if(blue == true  && yellow == false)
  102.              color = "Blue";
  103.          else if(yellow == true  && blue == false)
  104.              color = "Yellow";
  105.          else if(yellow == true && blue == true)
  106.              color = "Green";
  107.          else if(yellow == false && blue == false)
  108.              color = "Red";
  109.  
  110.          field.setText("The Color is " + color); 
  111.     }
  112.     class myShape extends JPanel implements ItemListener {
  113.         Graphics2D g2;
  114.         Color c;
  115.         public void paintComponent(Graphics g){
  116.             super.paintComponent(g);
  117.             g2 = (Graphics2D) g;
  118.             g2.setColor(c);            
  119.             g2.fill(new Rectangle(125,50,50,50));            
  120.         }        
  121.         public void itemStateChanged(ItemEvent e){
  122.             JMenuItem source = (JMenuItem)(e.getSource());
  123.             String select = ((e.getStateChange() == ItemEvent.SELECTED) ?
  124.                     "selected":"unselected");
  125.             String which = source.getText();
  126.             if(which.equals("Yellow") && select.equals("selected"))
  127.                 yellow = true;
  128.             else if(which.equals("Yellow") && select.equals("unselected"))
  129.                 yellow = false;
  130.             else if(which.equals("Blue") && select.equals("selected"))
  131.                 blue = true;
  132.             else if(which.equals("Blue") && select.equals("unselected"))
  133.                 blue = false;
  134.  
  135.              if(blue == true  && yellow == false)
  136.                  c = Color.BLUE;
  137.              else if(yellow == true  && blue == false)
  138.                  c = Color.YELLOW;
  139.              else if(yellow == true && blue == true)
  140.                  c = Color.GREEN;
  141.              else if(yellow == false && blue == false)
  142.                  c = Color.RED;
  143.              repaint();   
  144.         }
  145.     }
  146. }
Feb 27 '08 #1
2 7475
BigDaddyLH
1,216 Recognized Expert Top Contributor
Please enclose your posted code in [code] tags (See How to Ask a Question).

This makes it easier for our Experts to read and understand it. Failing to do so creates extra work for the moderators, thus wasting resources, otherwise available to answer the members' questions.

Please use [code] tags in future.

MODERATOR
Feb 27 '08 #2
BigDaddyLH
1,216 Recognized Expert Top Contributor
Very close! You wrote:
Expand|Select|Wrap|Line Numbers
  1. frame.add(new myShape());
which meant you never had a change to teach your component to listen to the menu items. Replace that with:
Expand|Select|Wrap|Line Numbers
  1. myShape component = new myShape();
  2. Yellow.addItemListener(component);
  3. Blue.addItemListener(component);
  4. frame.add(component);
  5.  
My the way, there is a strong convention in Java to give classes (and interfaces) names that start with capital letters: Menu and MyShape, and all other names start with lower case letters.
Feb 27 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

1
4122
by: Robert W. | last post by:
In my Winforms app I'm trying to get an image's background to appear transparent on a form that has a gradient background. So I added a PictureBox and then attempted to add a custom paint command for the PictureBox. But it's not working. Here's the code I've written: public void InitializeLinearGradients() { this.Paint += new PaintEventHandler(PaintClient); this.SizeChanged += new EventHandler(SizeClient); pictureLogo.Paint += new...
4
2161
by: K.N.Ranjit | last post by:
Hi, This is the 4th mail I'm sending regarding this problem. I'm really not been able to sort this problem out.I'm not been able to change my starting position of my cordinates from top-left to bottom-left of my form.Thrice I got the reply but unfortunately it did'nt work.Here is my coding. private sub form_load(...) dim y as integer y=me.height location.y = 0-y
3
15147
by: Roger | last post by:
Is this an easy thing to change? I want to put an option button on a form and want to dynamically change the color (Red, Yellow, Green) for showing a status. I figured it would be an easy task, but am finding it a little difficult as there isn't a simple property to set. Thanks, Rog
4
1450
by: Thief_ | last post by:
I'm trying to create many squares on a form and for every new square, change the background colour to the next colour. I'm trying to create a colour palette showing all available colours and their colour name. My problem is that I can not figger out how to create a new panel at specific intervals across and down the form. Here's the code I have so far: Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles...
3
2232
by: Brad Rogers | last post by:
All, Being immersed in vb.net and trying CSharp after almost a year I forgot the differences. I like vb fixing the uppercase/lowercase names and seeming to be more flexible to code entry. But while trying to insert a text box to see when a method is used, and putting a counter to bump some variable? The textbox sits there unchanged. I put a breakpoint at the text write
1
2411
by: kCura | last post by:
First off, I'm sorry if this isn't the write thread to post this message but I couldn't find one dedicated to System.Drawing. I'm developing an intranet application in VB.NET that uses a Hosted Windows Form (HWF) dedicated to image manipulation. This HWF is also supposed to allow the user to print an image to their default printer. I'm using a System.Drawing.Printing.PrintDocument object to initiate printing, and everything works locally...
0
1441
by: Kristian Frost | last post by:
Hi, I'm just getting started with VB.Net, and I'm having trouble getting the routing around of some of the data straight in my mind, which has led me to the following problem. Basically, I'm trying to create an object that will monitor the status of some switches. I created a User Control to put into a form, on which I want to have five graphical representations of LEDs, which I've got working, light up and turn off when the...
13
2305
by: Joe | last post by:
does anyone know why this source code throws an error?? Dim myBitmap As System.Drawing.Bitmap Dim myGraphics As Graphics myBitmap = New System.Drawing.Bitmap(fileName:="C:\test.tif") myGraphics = PictureBox1.CreateGraphics Dim expansionRectangle As New Rectangle(25, 550, 1000, 350) Dim destRectangle1 As New Rectangle(0, 0, 1000, 350) myGraphics.DrawImage(myBitmap, destRectangle1, expansionRectangle,
3
29320
by: CSharper | last post by:
Is it possible to selectivly change the color of an item in text. I saw ForeColor option, but it changes the color of all the items. If it is not possible, is there any other control list listbox where we can see more than one item and change the color during run time. Thanks.
0
9687
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9541
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10482
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10225
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10027
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9072
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7564
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.