Creating graphics object and modifing it

hi every body i would like to create a Graphics object to modify it (by using the method insert string)
but using Graphics g=new Graphics is not possible how can i create it inside other java code.
i 'am trying to create an object and finally to send it to the printer(dot matrix printer ) to be printed but i don't know how to do it. i read in some books that they create a methos (paintComponent) witch automatically receives a graphics object but this method i can not use because i would like to draw string in a while statement.

Post your code and let me see if I can help.
Bemmah

Similar Messages

  • Creating remote objects and passing the retrieved data to modules

    I found at this Adobe tutorial a nice "RemoteService" class that  creates a RemoteObject and contains the functions for handling the  result and fault events. If I wanted to use this approach, how could I  pass the data from the result handler to interfaces that modules from  the main application could use?
    I could put the RemoteService/RemoteObject in the modules, but (in my  opinion- and I could be wrong) the best design seems to be using the  remote calls in the main app and passing the data along to the modules.
    Ultimately, I would like to know what the "best practices" are for creating remote objects and passing the retrieved data to modules
    Thanks!

    public void mouseClicked(MouseEvent e) {
      X x = new X(e.getX(), e.getY());
    }I don't see the difficulty.

  • Error in creating Connection Object and Device Location

    Hi ,
    When i am creating Connection Object and Device Location , system is giving dump . all other object are working fine.
    the error is gievn below :
    Error in reading table TE130.
    i checked this the table , its have no entries ( mainly field ISTYP is blank ) and this is the cause of problem .
    Could you please tell me that how to fill this table before creating Connection object and device location. i think some configuration should be needed for this but i dont know how .
    thanks and regards
    Deepak.

    Hi Deepak,
    You can check standard configuration in client 000.
    Meanwhile you can use this settings:
    ISTYP TPLKZ FLTYP NUMKI NUMKE
    C     AO_GP     A     01     OC
    D     AO_GP     G     02     OC
    This is where you define structure indicator for isu technical location category.
    ISTYP correspond to the type of technical location in ISU, C for connection object and D for device location
    The content of TPLKZ is defined in the following menu in SPRO.
    Plant Maintenance and Customer Service
    Master Data in Plant Maintenance and Customer Service
    Technical Objects
    Functional Locations
    Create Structure Indicator for Reference Locations/Functional Locations
    Hope it helps,
    Regards,
    Daniel Valenzuela
    Edited by: Daniel Valenzuela on Feb 4, 2008 3:22 PM

  • Slow creating ReportDocument object and loading report

    Hi all,
    I realise this question has come up several times before, I've been searching the internet and have found similar problems but non that match my own. Sorry this is a little long winded but I would like to give as much detail as possible.
    I use CR 2008 and VS2010 on my development machine. And I have installed CR 2008 Redist SP3 on the production server.
    My application is a simple console application accepting parameters such as report name, print or export, and of course the report parameters.
    CrystalDecisions.CrystalReports.Engine.ReportDocument rptDoc = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
    rptDoc.Load(sParamDOC); //sParamDOC being the report name passed in via command line
    It has to be like this because it integrates into an old system in the background. Of course it being like this means I can not pre-load dll's on application startup (as I've seen suggested several times).
    All of this is in house, I'm an OU administrator and an administrator on the server. The server is only accessed via remote desktop and the OS is windows server 2003. I installed all of the neccesary software to make this work.
    What is really puzzling me though is that when I use this program via command prompt, logged in as me, it creates the object and loads the report in a matter of seconds. Yet if anybody else runs it (even other administrators of the server) the program can take 30-60 seconds to create the ReportDocument object and the same again to load the report.
    I initially only noticed this for the standard users, which was why I created another admin to test. I don't think it's a problem with the report design because it works quick for me. I read an article about this happening with reports created in Crystal version 9. So I tested with a report made from scratch in 2008 and still get the same result. I also read another article about default printers, 'dissociate printer' option is selected and locally the default printers are set to the same printer also.
    Does anybody have any suggestions as to where I could look next?
    I saw in another article some registry keys you can use to turn on logging for crystal reports, I want to do this but where does it put the log files?
    Oh, one more thing the server orginally had redist 2.3 on when I noticed this issue, updating to SP3 (redist 3.3) if anything made it slower, and a little more inconsistant of load times.
    Thanks
    Gavin

    I figured out what this was. I thought I would come back and post incase anyone else has the same issue... the reason it was slow for the other users is because they could not access the internet. My program doesn't use the internet but the operating system is automatically trying to verify the dll's publishers. you can disable this see the following blog:
    [http://blogs.msdn.com/b/amolravande/archive/2008/07/20/startup-performance-disable-the-generatepublisherevidence-property.aspx|http://blogs.msdn.com/b/amolravande/archive/2008/07/20/startup-performance-disable-the-generatepublisherevidence-property.aspx]
    Regards
    Gav

  • Failed to create Salience object and java.lang.NoClassDefFoundError

    We are getting the below error while trying to use the text enrichment component in Endeca integrator clover server.
    2015-01-26 10:11:59,880 INFO 1343495 [pool-7-thread-1] Creating new Salience object from data paths: '/app/oracle/ofm/TextEnrichment/salience-5.1.1.7349/data'.
    2015-01-26 10:11:59,881 ERROR 1343495 [pool-7-thread-1] Failed to get Salience object from factory
    java.lang.NoClassDefFoundError: com/lexalytics/salience/Salience
      at com.endeca.clover.adapters.salience.SalienceFactory.createSalience(SalienceFactory.java:101)
      at com.endeca.clover.adapters.salience.SalienceFactory.getSalienceInstance(SalienceFactory.java:41)
      at com.endeca.clover.adapters.salience.SalienceRunnable.run(SalienceRunnable.java:92)
      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
      at java.lang.Thread.run(Thread.java:680)
    2015-01-26 10:11:59,891 ERROR 1343495 [WatchDog_1343495] Component [Customer Background:CUSTOMER_BACKGROUND] finished with status ERROR.
    Failed to create Salience object.
    2015-01-26 10:11:59,891 ERROR 1343495 [WatchDog_1343495] Error details:
    org.jetel.exception.JetelRuntimeException: Component [Customer Background:CUSTOMER_BACKGROUND] finished with status ERROR.
      at org.jetel.graph.Node.createNodeException(Node.java:535)
      at org.jetel.graph.Node.run(Node.java:514)
      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
      at java.lang.Thread.run(Thread.java:680)
    Caused by: java.lang.RuntimeException: Failed to create Salience object.
      at com.endeca.clover.adapters.salience.SalienceComponent.execute(SalienceComponent.java:166)
      at org.jetel.graph.Node.run(Node.java:485)
      at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:919)
      ... 1 more
    2015-01-26 10:11:59,930 INFO 1343495 [WatchDog_1343495] Execution of phase [0] finished with error - elapsed time(sec): 0
    2015-01-26 10:11:59,930 ERROR 1343495 [WatchDog_1343495] !!! Phase finished with error - stopping graph run !!!
    2015-01-26 10:11:59,930 INFO 1343495 [WatchDog_1343495] Post-execute finalization of connection:
    2015-01-26 10:11:59,930 INFO 1343495 [WatchDog_1343495] DBConnection driver[org.jetel.connection.jdbc.driver.JdbcDriverImpl@103cdbdc]:jndi[null]:url[jdbc:oracle:thin:@gitvm000212.us.oracle.com:1521:upslstg]:user[upsell_winref] ... OK
    2015-01-26 10:11:59,930 INFO 1343495 [WatchDog_1343495] -----------------------** Summary of Phases execution **---------------------
    2015-01-26 10:11:59,931 INFO 1343495 [WatchDog_1343495] Phase# Finished Status RunTime(sec) MemoryAllocation(KB)
    2015-01-26 10:11:59,930 INFO 1343495 [JobFinalizer_1343495] Finalisation
    2015-01-26 10:11:59,931 INFO 1343495 [WatchDog_1343495] 0 ERROR 0 139976
    2015-01-26 10:11:59,931 INFO 1343495 [WatchDog_1343495] ------------------------------** End of Summary **---------------------------
    2015-01-26 10:11:59,931 INFO 1343495 [WatchDog_1343495] WatchDog thread finished - total execution time: 0 (sec)
    2015-01-26 10:11:59,935 INFO 1343495 [JobFinalizer_1343495] RunTime: 296 ms
    2015-01-26 10:11:59,935 ERROR 1343495 [JobFinalizer_1343495]
    --------------------------------- Error details ----------------------------------
      Component [Customer Background:CUSTOMER_BACKGROUND] finished with status ERROR.
      Failed to create Salience object.
    2015-01-26 10:11:59,935 INFO 1343495 [JobFinalizer_1343495] Finished Status: ERROR
    This happens only on our stage and production instances. On our dev instance it works without problems. All 3 instances are setup the same, although our dev instance was created long time before the stage and prod instances. However, we cannot detect any differences between the machines.
    I've tried the solutions mentioned in the other similar thread: Failed to create Salience object but this doesnt solve the issue since the directory and variables were already correct.
    Anyone can help?

    Given that you are running this in Clover Server, one thing I can recommend is to shut that server down, move/truncate the logs, restart and retest, then look at the first error message you get when attempting to run the graph.  Java classloaders sometimes cache failed class clinit and report future attempts to load that class as a simple NoClassDefFoundError, masking the original/actual root cause.  With any luck you might find another, clearer error - maybe the native binary libraries are not being located.

  • Using PHP Data Services to create an object and accessing that objects data in an unbound way in AS

    Hello,
    I've been able to use the php data services and bind the results of a function to a component. However I am having a hard time figuring out the syntax to use the data services to create an object out of the results, and then use that object as an array of filenames to provide the current index of the filename to a new sound object.
    My problem is obviously in not being able to figure out the specific syntax, I have declared the service and and object of the services returned type and in the creationComplete() function I have assigned object.token = service.getData();
    I've tried various ways of then pulling that data out of the object, with no success.
    Can someone point me in the right direction?
    This code probably looks horrible because it doesn't work yet.
    - Joel
                import flash.media.Sound;
                import flash.media.SoundChannel;
                import mx.controls.Alert;
                var playing:Sound = new Sound();
                var channel:SoundChannel = new SoundChannel();
                var sndIndex:int=0;
                var skpTr:String;
                public function init():void{
                 mp3Array.token = mp3service.getData();
                 currentTrack(mp3Array.lastResult.filename); 
                     trace(mp3Array.lastResult.filename[sndIndex]);
                public function currentTrack(t:String):void{
                    playing = new Sound();
                    playing.load(new URLRequest("mp3/" +t));
                public function skip():void{
                    stop();
                    if (sndIndex != mp3Array.lastResult.length-1){
                        sndIndex++;
                        var skipTr:String=mp3Array.lastResult.filename[sndIndex].data;
                        currentTrack(skipTr);
                        play();
                    } else {
                        sndIndex=0;
                        skipTr=mp3Array.lastResult.filename[sndIndex].data;
                        currentTrack(skipTr);
                        play();
                public function stop():void{
                    channel.stop();
                public function play():void{
                    channel = playing.play();
        <fx:Declarations>
            <s:CallResponder id="mp3Array"/>
            <mp3services:Mp3Service id="mp3service" fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)" showBusyCursor="true"/>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>

    Hello Joel;
    In retrieving your data - what is your php returning to FB, an object, object array, an array?  Either way, I have a brief example below that an object(s) is being returned.  Pull the data from the lastResult in a ResultEvent.  The object instantiated in the resultEvent will contain your data and you can do what you want from there. 
    Also, I always use Network Monitor to see what data (if any) is being returned from the server, you can also see how it is being sent back.
    John
    private function init():void
         mp3Array.token = mp3service.getData();
         mp3Array.addEventListener(FaultEvent.FAULT, faultHandler);
         mp3Array.addEventListener(ResultEvent.RESULT, mp3Array_resultHandler);
    protected function faultHandler(event:FaultEvent):void
         Alert.show("There was a fault error!" + event.message, "Fault Error", Alert.OK);
    protected function mp3Array_resultHandler(event:ResultEvent):void
         // Not sure if your service is sending back an object or an array or ?
        var info:Object = mp3Array.lastResult;
         doSomeFunction(info)
    protected function doSomeFunction(data:Object):void
         trace(info.filename);

  • Create BRF object and call in Webdynpro ABAP

    Hi,
    can you please let me know how can i create BRF obejects and call them in webdynpro ABAP in WDC.
    Thanks,
    Mahesh.Gattu

    Hi Sachin,
    I am new to BRF,and i went through the BRF documents which are provided in Help.sap.Now my requirement is ,I have an webdynpro screen to create a policy number.When i click on Save all the fields should be validated through BRF.Being new to this environment,i need a start up help to achieve this.Please let me know the steps to validate the fields in webdynpro.
    Thanks
    Naresh Bammidi

  • Photoshop Help | Creating 3D objects and animations (Photoshop CS5 Extended)

    This question was posted in response to the following article: http://helpx.adobe.com/photoshop/using/creating-3d-objects-animations-photoshop.html

    Regarding "Create internal constraints from selections, work paths, or text" -- Is it possible to create a constraint on an object created using a preset such as a cylinder or wine bottle?

  • Need help creating custom objects and adding them to an array.

    Hi Everyone,
    So I'm dinking around in Powershell today and I'm failing at creating an array of custom objects.  I want to create a HTML report that builds out after every MDT image update. To do that, I need to collect my data on what's contained in each build.
    Here's my current script in progress -
    function Parse-Dependents($fullname){
    #PARAMETER SWITCHING
    if(!($fullname)){
    $dependents = get-dependents
    if($fullname){
    $dependents = get-dependents -fullname $fullname
    #SPIN THROUGH ARRAY OF GUIDS FROM GET-DEPENDENTS
    foreach($d in $dependents){
    #SPIN THROUGH EACH APP IN APPLICATIONS.XML
    foreach ($app in $apps){
    #IF MATCH THEN ADD OBJECT WITH PROPERTIES
    if($d -match $app.guid){
    #ADD APPLICATION MATCH TO THE ARRAY
    $applications = @{
    'Name' = $app.ShortName;
    'GUID' = $app.Guid;
    'Version' = $app.Version;
    'Last Modified Time' = $app.LastModifiedTime;
    'Last Modified By' = $app.LastModifiedBy;
    'Install Directory' = [string]'\\my\path\to\MDT\' + $app.WorkingDirectory.TrimStart(".","\")
    'CommandLine' = $app.CommandLine;
    new-object -typename PSObject -property $applications
    #RETURN MATCHED ARRAY
    return $applications
    It all works great until I look at my output and see that I get my expected properties and array, but at the end it's created additional empty entries for each of my initial properties I assigned.  So I get my list of apps like this :
    powershell.ex... OrgChart Plugin  \\my\mdt\server\ XX\user                     9/22/2014 5:... {ffee7497-0c...
    And then below it :
                     CommandLine                                                                                    
                     Name                                                                                           
                     Install Direc...                                                                               
                     Last Modified By                                                                               
                     Version                                                                                        
                     Last Modified...                                                                               
                     GUID                                                                                           
    And these are all listed under the Name property.  I'm still pretty new to PS (8 months or so now), and rarely have to create a custom object, but this seems like a case for doing so to create a custom html report.  Any ideas would be greatly appreciated.
    Ryan

    It's not really all that strange.  
    If you look at your script, you're not outputting the hash table until both loops finish.  The values are dependent on the properties of the $app objects enumerated in the inner loop, and only outputting an object if the dependent ($d) matches the $app
    guid property.
    At the end, you're outputting the hash table without that test, so it's going to have values based on the last $app in the loop, regardless of whether the guid matches the dependents or not.
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • Macbook Pro Creating Graphical Errors and Freezing

    My Macbook Pro is just under 2 1/2 years old now. I bought it in August of '06.
    Heres my problem. About 6 months ago, my computer started leaving graphical errors on the screen. For example:
    http://www.andponcho.com/minibus/images//graphicalerror2.jpg
    http://www.andponcho.com/minibus/images//graphicalerror3.jpg
    These errors are from when I minimized a window.
    Not only does it do that, but sometimes there could be a line left up on the screen, this happens especially when I browse on Safari.
    Another error happening is sometimes a triangle may appear on my screen. It may be a cyan, magenta, or a yellow tint. It happens randomly.
    Thats not the worst part. Recently, I played WoW on my computer and it was causing all sorts of graphical errors on my screen. And if that didn't happen, my computer would just randomly freeze. I was unable to play the game. Mind you, 2 years ago, I played WoW on this very same computer and never had any problems while playing.
    This is where it gets frustrating. Like I mentioned above, my computer tends to freeze...about 6 to 7 times a week. I don't know how many times I've been working in Photoshop and my computer would just lock up on me. The worst part is I use Skype everyday and its happens, my screen locks, but the person on the other end can still hear me and I can hear them.
    I've done a bit of research on the web and the only thing I found out that may be causing the errors is my logic board. I first thing I thought of when my computer started to freeze was it may be getting too hot. I downloaded smcFanControl to control my fans to move more heat out. I've also noticed my computer temp could reach 170 degrees Fahrenheit .The fans do seem to help a bit, but I still get errors all the time.
    Is it the logic board? Or is it something else? Could I have caused this? I spent $3000 on this computer. I'm an art student and my computer is my life. I can't afford to replace a $1000 part.

    Welcome to Apple Discussions!
    Have you tried running the extended version of the Apple Hardware Test? It is on Install Disc #1 of the gray discs that originally came with your computer. You boot to it by holding down "D" and follow the instructions on the screen. If you get an error code, it would point to what the problem is. Try running it when your computer is malfunctioning.
    Do you get the same artifacts on an external display? If so, that would indicate a graphics chip problem. If not, then it could be a problem with the built in display or its connections.
    Freezing can have many causes, both hardware and software related. Aside from the logic board, a dying hard drive can also cause freezing. It would be prudent to make a good backup and keep it up to date, just in case your computer stops working altogether some day.
    You can download this utility for free and use it to check out your hard drive:
    S.M.A.R.T. Utility
    http://www.versiontracker.com/dyn/moreinfo/macosx/32454
    It actually sounds more like you logic board and graphics chip, since the problem seems to be heat related and occurs during graphics intense applications. But it wouldn't hurt to eliminate the hard drive as a factor.
    You might try a chill mat and see if that helps with the heat problem.
    Do you by any chance have 3 year Applecare? If so, it's still under warranty and any repairs should be covered.
    Good luck!

  • How to create authority check object and assign to  ztcode which is of modu

    Dear ,
             how to create authority check object and assign to  ztcode which is of custom module pool program.its urgent kindly help points rewarded.

    Manoj,
    You can check with your Basis team to create authorisation object and assigining tcodes to the user profiles.
    K.Kiran.

  • What is matchcode objects and how can we create tthem

    hai to all.
         what is matchcode objects .
         and how can we create matchcode objects
         and how will it works

    Hi
    In which version of SAP are you working?
    Matchcodes are replaced by SEARCH HELPs in latest versions
    see the doc
    1) Elementary search helps describe a search path. The elementary search help must define where the data of the hit list should be read from (selection method), how the exchange of values between the screen template and selection method is implemented (interface of the search help) and how the online input help should be defined (online behavior of the search help).
    2) Collective search helps combine several elementary search helps. A collective search help thus can offer several alternative search paths.
    3)An elementary search help defines the standard flow of an input help.
    4) A collective search help combines several elementary search helps. The user can thus choose one of several alternative search paths with a collective search help.
    5)A collective search help comprises several elementary search helps. It combines all the search paths that are meaningful for a field.
    6)Both elementary search helps and other search helps can be included in a collective search help. If other collective search helps are contained in a collective search help, they are expanded to the level of the elementary search helps when the input help is called.
    CREATION:
    Go to SE11 Tcode
    select search help
    give the 'z' search help name and create
    select the selection method ur table name eg : 'mara'
    dialog module 'display value immediately'.
    add the field whatever u want and lpos = 1 and spos = 1 and check import and export parameter.
    where left position when displaying and spos = search position
    and then save and activate ..
    See the links:
    http://help.sap.com/saphelp_nw04/helpdata/en/cf/21ee38446011d189700000e8322d00/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/cf/21ee45446011d189700000e8322d00/content.htm
    https://forums.sdn.sap.com/click.jspa?searchID=3173469&messageID=2176485
    https://forums.sdn.sap.com/click.jspa?searchID=3173469&messageID=3601619
    pls go through this for search help creation
    http://help.sap.com/saphelp_nw2004s/helpdata/en/41/f6b237fec48c67e10000009b38f8cf/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/cf/21ee2b446011d189700000e8322d00/content.htm
    Search Help Exits:
    Re: dynamic values for search help
    Re: Dynamic search  help
    http://help.sap.com/saphelp_nw04/helpdata/en/cf/21ee52446011d189700000e8322d00/content.htm
    http://www.sapdevelopment.co.uk/dictionary/shelp/shelp_exit.htm
    https://forums.sdn.sap.com/click.jspa?searchID=4390517&messageID=1712818
    Collective search help Combine several elementary search helps. A collective search help thus can offer several alternative search paths.
    A Collective search help provides alternative search
    Paths by combining elementary search helps.
    Only one search help can be attached to a field, table or data element. Several search paths are therefore attached with a collective search help.
    A collective search help also has interface parameters like
    an elementary search help.
    Like an elementary search help, a collective search help has an interface of IMPORT and EXPORT parameters with which the search help exchanges data. Using this interface, the collective search help can be attached to fields, tables and data elements exactly like an elementary search help.
    Parameter assignment needs to be done for each of the
    Included search helps.
    When you define a collective search help, there are no components for describing the dialog behavior and data selection; instead the included search helps are listed here. You must assign the parameters of the collective search help to the interface parameters of the included search help for each inclusion.
    User may choose the tab and thus the elementary
    search maethod.
    When we execute the search help SCUSTOM, we are confronted with a dialog which gives us an option of either restricting
    By 1)Search for customer according to booking
    2)Search for customer according to name.
    These are effectively the elementary search helps (SCUSTOM_BOOK and SCUSTOM_NAME) which have been included in the collective search help SCUSTOM.
    HOT KEY
    The hot key is used to select the elementary search help from the collective search help and to enter the restrictions in the dialog box for restricting values directly from the entry field. If the user often searches for values using the same search help, this procedure can save time.
    Steps to create a Collective Search Help
    1)Enter the search help name and click on create.
    2)Choose Collective search help radio button option as the search help type.
    3)Enter the search help parameters.
    4)Instead of the selection method, we enter the included
    search helps for the collective search help.
    5)We need to assign parameters for each of the included
    search helps.
    6)Complete the parameter assignment by clicking on the push button
    7)Collective search help offers the user to obtain F4 help
    using any of the included search helps.

  • How to change font/ font color etc in a graphic object using JCombobox?

    Hello
    My program im writing recently is a small tiny application which can change fonts, font sizes, font colors and background color of the graphics object containing some strings. Im planning to use Jcomboboxes for all those 4 ideas in implementing those functions. Somehow it doesnt work! Any help would be grateful.
    So currently what ive done so far is that: Im using two classes to implement the whole program. One class is the main class which contains the GUI with its components (Jcomboboxes etc..) and the other class is a class extending JPanel which does all the drawing. Therefore it contains a graphics object in that class which draws the string. However what i want it to do is using jcombobox which should contain alit of all fonts available/ font sizes/ colors etc. When i scroll through the lists and click the one item i want - the graphics object properties (font sizes/ color etc) should change as a result.
    What ive gt so far is implemented the jcomboboxes in place. Problem is i cant get the font to change once selecting an item form it.
    Another problem is that to set the color of font - i need to use it with a graphics object in the paintcomponent method. In this case i dnt want to create several diff paint.. method with different property settings (font/ size/ color)
    Below is my code; perhaps you'll understand more looking at code.
    public class main...
    Color[] Colors = {Color.BLUE, Color.RED, Color.GREEN};
            ColorList = new JComboBox(Colors);
    ColorList.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                     JComboBox cb = (JComboBox)ev.getSource();
                    Color colorType = (Color)cb.getSelectedItem();
                    drawingBoard.setBackground(colorType);
              });;1) providing the GUI is correctly implemented with components
    2) Combobox stores the colors in an array
    3) ActionListener should do following job: (but cant get it right - that is where my problem is)
    - once selected the item (color/ font size etc... as i would have similar methods for each) i want, it should pass the item into the drawingboard class (JPanel) and then this class should do the job.
    public class DrawingBoard extends JPanel {
           private String message;
           public DrawingBoard() {
                  setBackground(Color.white);
                  Font font = new Font("Serif", Font.PLAIN, fontSize);
                  setFont(font);
                  message = "";
           public void setMessage(String m) {
                message = m;
                repaint();
           public void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  //setBackground(Color.RED);
                  Graphics2D g2 = (Graphics2D) g;
                  g2.setRenderingHint             
                  g2.drawString(message, 50, 50);
           public void settingFont(String font) {
                //not sure how to implement this?                          //Jcombobox should pass an item to this
                                   //it should match against all known fonts in system then set that font to the graphics
          private void settingFontSize(Graphics g, int f) {
                         //same probelm with above..              
          public void setBackgroundColor(Color c) {
               setBackground(c);
               repaint(); // still not sure if this done corretly.
          public void setFontColor(Color c) {
                    //not sure how to do this part aswell.
                   //i know a method " g.setColor(c)" exist but i need to use a graphics object - and to do that i need to pass it in (then it will cause some confusion in the main class (previous code)
           My problems have been highlighted in the comments of code above.
    Any help will be much appreciated thanks!!!

    It is the completely correct code
    I hope that's what you need
    Just put DrawingBoard into JFrame and run
    Good luck!
    public class DrawingBoard extends JPanel implements ActionListener{
         private String message = "message";
         private Font font = new Font("Serif", Font.PLAIN, 10);
         private Color color = Color.RED;
         private Color bg = Color.WHITE;
         private int size = 10;
         public DrawingBoard(){
              JComboBox cbFont = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
              cbFont.setActionCommand("font");
              JComboBox cbSize = new JComboBox(new Integer[]{new Integer(14), new Integer(13)});
              cbSize.setActionCommand("size");
              JComboBox cbColor = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbColor.setActionCommand("color");
              JComboBox cbBG = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbBG.setActionCommand("bg");
              add(cbFont);
              cbFont.addActionListener(this);
              add(cbSize);
              cbSize.addActionListener(this);
              add(cbColor);
              cbColor.addActionListener(this);
              add(cbBG);
              cbBG.addActionListener(this);
         public void setMessage(String m){
              message = m;
              repaint();
         protected void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setColor(bg);//set background color
              g2.fillRect(0,0, getWidth(), getHeight());          
              g2.setColor(color);//set text color
              FontRenderContext frc = g2.getFontRenderContext();
              TextLayout tl = new TextLayout(message,font,frc);//set font and message
              AffineTransform at = new AffineTransform();
              at.setToTranslation(getWidth()/2-tl.getBounds().getWidth()/2,
                        getWidth()/2 + tl.getBounds().getHeight()/2);//set text at center of panel
              g2.fill(tl.getOutline(at));
         public void actionPerformed(ActionEvent e){
              JComboBox cb = (JComboBox)e.getSource();
              if (e.getActionCommand().equals("font")){
                   font = new Font(cb.getSelectedItem().toString(), Font.PLAIN, size);
              }else if (e.getActionCommand().equals("size")){
                   size = ((Integer)cb.getSelectedItem()).intValue();
              }else if (e.getActionCommand().equals("color")){
                   color = (Color)cb.getSelectedItem();
              }else if (e.getActionCommand().equals("bg")){
                   bg = (Color)cb.getSelectedItem();
              repaint();
    }

  • Cant do setColor(Color.BLACK); to a graphic object inside a class

    i have a graphic object inside a class:
    JPanel panel = new JPanel();
    Graphic lienzo = areadibujo.getGraphic();
    and then i cant do this:
    lienzo.setColor(Color.BLACK);
    netbeans error:
    <identifier> expected
    i just can do that inside a method from the class...

    HI i found the problem.
    The problem is that when i create the graphic object i do this:
    Graphics lienzo = areadibujo.getGraphics();
    areadibujo.getGraphics(); returns null so when i try to do something like lienzo.drawline(1,1,200,200); it just says nullpointer error, i guess at the time i create graphic object the panel "areadibujo" is not still created because the frame doesnt still shows, i can correct this by copying Graphics lienzo = areadibujo.getGraphics(); inside a actionperfmoded or other event method , but i dont wanna do that, where does the panel object already is created in constructor?.... i dont know if i explain my self well or how can i force areadibujo.getGraphics() to return something...

  • How would i make an object and rotate it?

    ok, i'm trying to get java to make a graphics object, and then create an array of said objects (basically just a bunch of rectangles organized into rows/columns) with the end goal being that i be able to put this collection of rectangles into a JPanel and then move it around and rotate it without changing its dimensions (so each rectangle in the collection retains the same height and width but with a different placement/orientation angle )
    My java textbook (yes, college student) doesn't cover the Graphics2D stuff which SEEMS to be what i would use... but beyond that I'm finding the resources on the topic to be uniformly opaque. i think i just need some starting point to extrapolate from. could anyone reply me a crash course in the above...?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Blocks extends JPanel {
        Block[][] blocks;
        int dx = 2;
        int dy = 2;
        public Blocks() {
            registerKeys();
            setFocusable(true);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(blocks == null) initBlocks();
            g2.setPaint(Color.red);
            for(int j = 0; j < blocks.length; j++)
                for(int k = 0; k < blocks[j].length; k++)
                    blocks[j][k].draw(g2);
        private void initBlocks() {
            int rows = 6;
            int cols = 3;
            Dimension d = new Dimension(200, 200);
            BlockMaker blockMaker = new BlockMaker(rows, cols, d);
            blocks = blockMaker.getBlocks();
        private void registerKeys() {
            getInputMap().put(KeyStroke.getKeyStroke("UP"), "UP");
            getActionMap().put("UP", up);
            getInputMap().put(KeyStroke.getKeyStroke("LEFT"), "LEFT");
            getActionMap().put("LEFT", left);
            getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "DOWN");
            getActionMap().put("DOWN", down);
            getInputMap().put(KeyStroke.getKeyStroke("RIGHT"), "RIGHT");
            getActionMap().put("RIGHT", right);
        private void step(int x, int y) {
            for(int j = 0; j < blocks.length; j++)
                for(int k = 0; k < blocks[j].length; k++)
                    blocks[j][k].move(x, y);
            repaint();
        private Action up = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                step(0, -dy);
        private Action left = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                step(-dx, 0);
        private Action down = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                step(0, dy);
        private Action right = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                step(dx, 0);
        public static void main(String[] args) {
            Blocks blocks = new Blocks();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(blocks);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class BlockMaker {
        Block[][] blocks;
        int PAD = 20;
        public BlockMaker(int rows, int cols, Dimension size) {
            int w = (size.width  - (cols+1)*PAD)/cols;
            int h = (size.height - (rows+1)*PAD)/rows;
            blocks = new Block[rows][cols];
            for(int j = 0; j < rows; j++) {
                int y = PAD + j*(h + PAD);
                for(int k = 0; k < cols; k++) {
                    int x = PAD + k*(w + PAD);
                    blocks[j][k] = new Block(x, y, w, h);
        public Block[][] getBlocks() {
            return blocks;
    class Block {
        int x;
        int y;
        int w;
        int h;
        public Block(int x, int y, int w, int h) {
            this.x = x;
            this.y = y;
            this.w = w;
            this.h = h;
        protected void draw(Graphics2D g2) {
            g2.drawRect(x, y, w, h);
        protected void move(int dx, int dy) {
            x += dx;
            y += dy;
    }

Maybe you are looking for