Need help with using graphics in swing components

Hi. I'm new to Java and trying to learn it while also developing an application for class this semester. I've been following online tutorials for about 2 months now, though, and so I'm not sure my question counts as a "new to Java" question any more as the code is quite long.
Here is the basic problem. I started coding the application as a basic awt Applet (starting at "Hello World") and about a month in realized that Swing components offer better buttons, panels, layouts, etc. So I converted the application, called BsfAp, to a new JApplet and started adding JPanels and JComponents with layout managers. My problem is, none of the buffered graphics run in any kind of JPanel, only the buttons do. I assume the buffered graphics are written straight to the JApplet top level container instead but I'm not entirely sure.
So as to not inundate the forum with code, the JApplet runs online at:
http://mason.gmu.edu/~dho2/files/sensor.html
The source code is also online at:
http://mason.gmu.edu/~dho2/files/BsfAp.java
What I would like to do is this - take everything in the GUI left of the tabbed button pane and put it into a JScrollPane so that I can use a larger grid size with map display I can scroll around. The grid size I would like to use is more like 700x1000 pixels, but I only want to display about 400x400 pixels of it at a time in the JScrollPane. Then I could also move this JScrollPane around with layout manager. I think this is possible, but I don't know how to do it.
I'm sure the code is not organized or optimized appropriately to those of you who use Java every day, but again I'm trying to learn it. ;-)
Thanks for any help or insight you could provide in this.
Matt

Couple of recs:
* Don't override paint and paint directly on the JApplet. Paint on a JPanel and override paintComponent.
* The simplest way to display a graphic is to put an image into an ImageIcon and show this in a JLabel. This can then easily go inside of the JScrollPane.
* You can also create a graphics JPanel that overrides the paintComponent, draw the image in that and show that inside of the JScrollPane.
* don't call paint() directly. Call repaint if you want the graphic to repaint.
Here's a trivial example quickly put together:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class BsfCrap extends JApplet
    private JPanel mainPanel = new JPanel();
    private JScrollPane scrollPane;
    private JPanel graphicsPanel = new JPanel()
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;
            RenderingHints rh = new RenderingHints(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHints(rh);
            Paint gPaint = new GradientPaint(0, 0, Color.blue,
                40, 40, Color.magenta, true);
            g2d.setPaint(gPaint);
            g2d.fill(new Ellipse2D.Double(0, 0, 800, 800));
    public BsfCrap()
        mainPanel.setPreferredSize(new Dimension(400, 400));
        mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        graphicsPanel.setPreferredSize(new Dimension(800, 800));
        graphicsPanel.setBackground(Color.white);
        scrollPane = new JScrollPane(graphicsPanel);
        scrollPane.setPreferredSize(new Dimension(300, 300));
        mainPanel.add(scrollPane);
    public JPanel getMainPanel()
        return mainPanel;
    @Override
    public void init()
        try
            SwingUtilities.invokeAndWait(new Runnable()
                public void run()
                    setSize(new Dimension(400, 400));
                    getContentPane().add(new BsfCrap().getMainPanel());
        catch (InterruptedException e)
            e.printStackTrace();
        catch (InvocationTargetException e)
            e.printStackTrace();
}

Similar Messages

  • Need help with my graphic calculator!!!

    Hello everybody!! I need help with my little program I made.... The problem is that I am unable to use to calculate but it is possible to compile the code!! What should I do?? Thanks in advance.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Aritmetik extends JFrame implements ActionListener{
         private JLabel l1 = new JLabel("Tal1: ", JLabel.LEFT);
         private JLabel l2 = new JLabel("Tal2: ", JLabel.LEFT);
         private JLabel l3 = new JLabel("Resultat",JLabel.LEFT);
         private JLabel l4 = new JLabel(" ", JLabel.RIGHT);
         private JTextField t1 = new JTextField(" ",10);
         private JTextField t2 = new JTextField(" ",10);
         private JButton b1 = new JButton("+");
         private JButton b2 = new JButton("-");
         private JButton b3 = new JButton("*");
         private JButton b4 = new JButton("/");
         public Aritmetik(){
              Container v = getContentPane();
              v.setLayout(new GridLayout(5,2));
              v.add(l1);
              v.add(t1);
              v.add(l2);
              v.add(t2);
              v.add(b1);
              v.add(b2);
              v.add(b3);
              v.add(b4);
              v.add(l3);
              v.add(l4);
              b1.addActionListener(this);
              b2.addActionListener(this);
              b3.addActionListener(this);
              b4.addActionListener(this);
              pack();
              setVisible(true);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         public void actionPerformed(ActionEvent e){
              int tal1 = Integer.parseInt(t1.getText());
              int tal2 = Integer.parseInt(t2.getText());
                   if(e.getSource() == b1){
              if(t1.getText().equals("") || t2.getText().equals(""))
                                       JOptionPane.showMessageDialog(null, "Mata in tal!");
                   else{
                        l3.setText("Resultat ");
                   l4.setText(" " + (tal1+tal2));
                   else if(e.getSource() == b2){
                        int sub = tal1-tal2;
                        l4.setText(" " + (sub));
                   else if(e.getSource() == b3){
                        int multi = tal1*tal2;
                        l4.setText(" " + (multi));
                   else if(e.getSource() == b4){
                        int div = tal1/tal2;
                        l4.setText(" " + (div));
                   public static void main(String[] arg){
                   Aritmetik A =new Aritmetik();

    Here is your problem:
    public void actionPerformed(ActionEvent e){
      int tal1 = Integer.parseInt(t1.getText().trim());  // add the trim()
      int tal2 = Integer.parseInt(t2.getText().trim());  // add the trim()
      if(e.getSource() == b1){
        if(t1.getText().equals("") || t2.getText().equals(""))
          JOptionPane.showMessageDialog(null, "Mata in tal!");
        else{
          l3.setText("Resultat ");
          l4.setText(" " + (tal1+tal2));
      }... Better ...
    public void actionPerformed(ActionEvent e)  throws NumberFormatException {
      String tala = t1.getText().trim();
      String talb = t2.getText().trim();
      if ( tala == null  ||  "".equals(tala)  ||  talb == null  ||  "".equals(talb) ) {
        JOptionPane.showMessageDialog(null, "Mata in tal!");
        return();
      int tal1 = Integer.parseInt(tala);
      int tal2 = Integer.parseInt(talb);
      if(e.getSource() == b1){
        l3.setText("Resultat ");
        l4.setText(" " + (tal1+tal2));
      else if(e.getSource() == b2){
        int sub = tal1-tal2;
        l4.setText(" " + (sub));
      else if(e.getSource() == b3){
        int multi = tal1*tal2;
        l4.setText(" " + (multi));
      else if(e.getSource() == b4){
        int div = tal1/tal2;
        l4.setText(" " + (div));
    }Message was edited by:
    abillconsl

  • Need help with buying graphics card and ram for MSI 865PE NEO 2-V

    Hi,
    I want to buy 1GB of ram for motherboard MSI 865PE NEO 2-V I need help with finding correct parts.
    I also want to buy 512Mb or 1GB graphics card.
    as i said before i need help with finding correct ones so they match motherboard, I would appreciate if any one would post link to cheap and fitting parts.
    I found graphics card allready, i just need to know if it will fit.
    the card is
    NVIDIA GeForce 7600 GS (512 MB) AGP Graphics Card
    Thanks for help.

    here you can see test reports for your mobo:
    http://www.msi.com/product/mb/865PE-Neo2-V.html#?div=TestReport

  • Need help with using Solaris FLAR across disparate platforms

    All,
    I need help with what needs to be done to use solaris Flash for disaster recovery between the disparate Server platforms listed below.
    I am concerned about the platform specific files that would be missing?
    Note: All our servers are installed with the SUNWCprog cluster through Custom jumpstart and We use disksuite for mirroring the operating system drives.
    Primary Server     Recovery Server
    Sun Fire 6800     Sun Fire E2900
    Sun Fire E2900     Sun Fire 6800
    Sun Fire-880     Sun Fire-V440
    Sun Fire-V440     Sun Fire-880
    Sun Fire 4800     Sun Fire-880
    Sun Fire-V890     Sun Fire 4800          
    Me

    jds2n,
    Is it possible to get around installing the Entire Distribution + OEM and include only the platform specific files?
    Just a thought
    Example:
    I would like to create a Flash Archive of a E2900 server which i plan to use to recover a 6900.
    The 2900 was installed with a developer cluster.
    When creating the Flash archive of the 2900 is it possible to add the 6900 platform specific files and drivers
    from the Solaris CD?
    Thanks

  • Not exactly iweb - need help with a graphic for my site

    This doesn't fit anywhere so dumping it here. I drew by hand a graphic I want to use with iweb to put on my site as my site's logo. Main problem is that getting the background transparent isn't working well as when it was scanned the scanner didn't back the background "pure" white. I have tried adjusting the whitepoint and setting the color depth down, but still no good. I don't know a ton about graphic program use. I have an older copy of graphic converter that came on this powerbook when i got it. I would be fine having the graphic loose the marker look and have solid fill colors - just I am not good enough with computer drawing tools to do it on the computer! So I either need to get a volunteer to help me out, or some help with some detailed instructions to get this to work out... (also I am broke so no cost/shareware is only option here)
    many thanks!!!!
    I can get you a scanned jpg of the pic if needed.

    THANK YOU/___sbsstatic___/migration-images/migration-img-not-avail.png so the tolerance makes it not care so much about the gradations in color? what else is tolerence good for?
    I have a cleaner copy now after someone suggested GIMP, so played with it last night - though couldn't figure out transparency - that was clear on converter- just not cooperative till these wonderful directions.
    So now I know how to do it without messing with the pic, and with messing with it - both good lessons and got a bit brighter color out of the deal.
    many thanks for the straightforward and clear directions, they worked perfectly/___sbsstatic___/migration-images/migration-img-not-avail.png extra strars for you/___sbsstatic___/migration-images/migration-img-not-avail.png

  • Need Help with Corrupted Graphics

    I need help real bad. I have spent the last 2 weeks trying to find the reason for crashing in game (not blue screening but corrupted graphics) where the whole screen goes like a television that isn't tuned in, and then after anywhere between 2 to 5 mins my computer will reboot. I'm wondering if anyone has a similar issue, and if there is a fix. I'll list my system specs and a couple of things I have done that hasn't fixed it.
    AMD64 3200+ 939 90mn
    MSI K8N Neo2 - 1.4 bios
    2 x 512mb Geil UltraX
    Leadtek 6800u
    Audigy
    SuperFlower 14cm 500watt
    I haven't started to overclock my machine yet as I have yet to fix this problem. Everything is running stock. I'm finding that its random. I can play Prince of Persia Warrior Within for hours on end without a problem. Then play Counterstrike Source and it will go to  after about 5 mins. I decided to try benchmarks and 3dmark01 will do the same thing randomly. Even Battle Field will play for about 10 mins and it will just go to the fuzzy screen. I even heard that some Soundblaster Cards cause problems and have tried using the onboard sound, with no effect. I have also disabled AGP SideBand and AGP Fastwrite in the bios, as also this can cause some issues, to no effect. I thought maybe the video card maybe the problem, and threw a crappy 5700 LE in my machine, still with no effect. CPU temp is around 36c (water cooled) and GPU is around 48c. Does anyone have any idea as to why the screen craps out in just about every game I play. I'm running Winxp Pro SP2 with DX9.0c, with the latest Drivers for everything I'm running (mainboard, vga, sound, etc). If you can suggest something, please let me know.

    X-((Well, This sorta sounds like what just happened to me.
    My graphics card decided to take a dump on me. When I was playing a game the graphics went all garbled and everything froze. System rebooted a couple times, and yes it seems the cards fan stoped rotating and it fried.
    So to me, it sounds like your video. But you say you tried changing video cards with no effect.
    Dang.  Sorry I cant think of anything. But on the bright side, your post was bumped.  

  • I have a hp a6814y computer and need help with a graphics card

    okay i wanna upgrade my hp with an actual graphics card, so i can play games without it lagging. i mainly play rts games, like command and conquer generals, etc and about to get company of heros. now i need to know what kind of card i can put in this computer. i would like to put this one in 
    http://www.newegg.com/Product/Product.aspx?Item=N82E16814102824
    i hear people say the min is 300watts and some say 450watts. but then idk, if this card can hook up to my power supplie.
    i just need help getting a very good card for this computer without updating the power supplie

    Hi,
    Check with Athena as they maintain a PC Cross Reference list and see if the power supply that you have selected is compatible with your PC.
    HP DV9700, t9300, Nvidia 8600, 4GB, Crucial C300 128GB SSD
    HP Photosmart Premium C309G, HP Photosmart 6520
    HP Touchpad, HP Chromebook 11
    Custom i7-4770k,Z-87, 8GB, Vertex 3 SSD, Samsung EVO SSD, Corsair HX650,GTX 760
    Custom i7-4790k,Z-97, 16GB, Vertex 3 SSD, Plextor M.2 SSD, Samsung EVO SSD, Corsair HX650, GTX 660TI
    Windows 7/8 UEFI/Legacy mode, MBR/GPT

  • Need help with using Email Activation Agent

    Hi,
    please, help me with using E-mail Activation Agent.
    I used email activation agent to start business processes by email, but after that letter disappear from email-server.
    Where letter was located?
    Can I get and read letter for processing?

    Mail/Preferences/General - do you have Unibox set as your default e-mail application?

  • Need help with using new ipod as hard drive. please!

    Hi. Has anyone had any problems using the ipod as a hard drive between two systems? I have an old 4th generation ipod which I used on my PC. That ipod worked great between macs and pcs as a hard drive. But recently it is completely screwed up. Anyway, I got a new Mac book pro and a 5th generation 60gb ipod.
    Now, I'm trying to get some stuff off my pc and transfer it into my mac. In my pc it comes up in "my computer" but keeps asking me to format the hard drive whenever I do the drag and drop of files into it. I've already formatted it for my mac, but haven't put anything on it yet. So I guess I could just do that for the transfer and reformat it for the mac and then put my music on it.
    I just want to know, it worked so well between mac and pc as a hard drive when originally formatted for my pc. will it not work the other way around? Will I have to keep reformatting it for the pc every time and then lose any information and all my music if I want to use it in that way? Or is there something I'm doing wrong? I would really appreciate any help at all that anyone could give me. Who really needs a 60gb anyway, if not to be able to transfer files back and forth between home and work, right?
    Dell Dimension 4400/MacBook Pro   Mac OS X (10.4.9)   Windows XP on the PC

    Thank you for your reply. It cleared up a lot of confusion for me. But I have one more question.
    See, I looked both of those software applications up, and it seems those are to be installed on the windows operating system. My plan is to eventually stop using my PC and give it away to goodwill, however, for work purposes- which is freelance- I'd need to use the ipod as a nice small portable hard drive- I'm a photographer, and work with big files, so I need the larger space that a flash drive can't give me.
    So, is there any type of mac formatting on the ipod that can also be read by the pc? Or is there a 3rd party software that can be installed on the ipod that will enable it to be read on the pc and mac while retaining its mac formatting?
    If not I guess I'll just have to go back to the old and extremely inconvenient way of doing things. I really wish mac would have mentioned these things before in all their descriptions.

  • NEED HELP WITH USING STATIC METHOD - PLEASE RESPOND ASAP!

    I am trying to set a value on a class using a static method. I have defined a servlet attribute (let's call it myAttribute) on my webserver. I have a serlvet (let's call it myServlet) that has an init() method. I have modified this init() method to retrieve the attribute value (myAttribute). I need to make this attribute value accessible in another class (let's call it myOtherClass), so my question revolves around not knowing how to set this attribute value on my other class using a static method (let's call it setMyStuff()). I want to be able to make a call to the static method setMyStuff() with the value of my servlet attribute. I dont know enough about static member variables and methods. I need to know what to do in my init() method. I need to know what else I need to do in myServlet and also what all I need in the other class as well. I feel like a lot of my problems revolve around not knowing the proper syntax as well.
    Please reply soon!!! Thanks in advance.

    class a
    private static String aa = "";
    public static setVar (String var)
    aa = var;
    class b
    public void init()
    a.aa = "try";
    public static void main(String b[])
    b myB = new b ();
    b.init();
    hope this help;
    bye _drag                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Need help with using cd templates

    I'm very new to Photoshop and trying to figure out how to use and edit templates for a 2 panel cd insert and the Tray Card template (back cover of the cd).  I want to just use pictures for the 2 panel but the Tray card needs to just have a color or design background with text.  I seem to have gotten a project started using the tray card template but I'm having trouble figuring out how to get going with it and add a color background and I'm assuming I'll need to use the layers function?  If anyone has any advice or can help me get started, I would really appreciate it!!  Thanks!!

    jds2n,
    Is it possible to get around installing the Entire Distribution + OEM and include only the platform specific files?
    Just a thought
    Example:
    I would like to create a Flash Archive of a E2900 server which i plan to use to recover a 6900.
    The 2900 was installed with a developer cluster.
    When creating the Flash archive of the 2900 is it possible to add the 6900 platform specific files and drivers
    from the Solaris CD?
    Thanks

  • I need help with using Tags in mavericks.

    When i tag a file(for example i tag it RED) than i go to the Finder and click on RED, i will not be shown any of the files or stuff i tag.
    How do i solve this issue.
    Your help would be gratefully appreaciated.

    Hello Alfred. Thanks for reaching out. Yes, all the individual files are created -- whether 1 or 50. Here is the gist of my workflow
    1. Find Finder items
    This searches a specific folder for a PDF file (I previously placed the multi-page file I needed split into this folder)
    I verified this step works
    2. Rename Finder Items
    This renames the PDF file from Step 1 to a specific name
    I verified this step works
    3. Get Specified Finder Items
    This gets the file from Step 2.
    I verified this step works
    4. Split PDF
    This splits the file from Step 3 to single-page files and places them on the desktop.
    It replaces any similar named files on the Desktop.
    I verified this step works
    5. Launch Application
    This step launch the Mail app
    I verified this step works
    6. Open Finder Items
    This step should attach each file created in Step 4 in a separate email.
    This is where a few emails are created and the workflow stops.
    The original PDF file I am using has 9 sheets. I verified all 9 single-page files were created and placed on the Desktop. I also verified each file was a valid PDF file. The workflow created 6 emails with the first 6 single-page PDF files then stopped.
    The error message I receive in Automator is:
    Open finder items failed - 1 error
       Mail.app Application can not open file /Users/myname/Desktop/filename-page7.pdf
    After these steps, I get each file and move them to the trash. I haven't verified these steps as the workflow stops at Step 6.
    This all worked fine in Mavericks but not in Yosemite.
    Please let me know if you need any further info.
    Best,
    Aram

  • Need help with using Zen V Plus in a

    I have a Zen V plus 2GB and I'd like to use it in my car with a FM transmitter/charger combination. The one I bought says it works with Creative zen MP3 players, but will not charge the player even though it has a USB with 5 VDC as output. It does play the player through the FM reciever just fine. I also noticed that I can only charge the player through the very same USB port on my computer where I first connected it when I was setting it up. Any other of the USB ports will not charge the player. Does this have something to do with this problem?

    Hello al9spike,
    Welcome to Creative forums!
    I'm not sure when you said "reset and play while plugged in" is the same as resetting the device by inserting a paper clip in the reset hole while plugged in. If not, then you can try this. There is a also a similar thread here with the same problem your experiencing right now. Maybe this could help you. Otherwise, if the unit is still not turning on, I suggest you contact support for further assistance.
    Best of luck,

  • Need help with "pie" graphic

    Hi, I'm trying to create a background that has a circular pie kind of effect that's popular these days where each slice of the pie is a slightly different color to create a cool background. This isn't the greatest example but check the red and dark red sun ray effect here ...
    http://gainesvillesuzuki.com/images/ad_one.jpg
    My question is, what is the easiest way to create this in illustrator?? I've been creating one slice with the pen tool, copying it while I rotate it with the rotate tool after I change the rotate axis to the middle , but doing that like 30-40 times gets really tedious, plus the pie slices never fit exactly together at the end (because the slices aren't divisions of 360).
    If anyone knows a better way I'm all ears, thanks!

    This kind of pie graph is easy. Double-click on the graph tool and select the pie graph. Drag a square. Then enter as many digits as you need (always the same digit) in the top line of the data spreadsheet. Use the right arrow key to hop between boxes. You will need to fill in as many boxes as you need slices in the pie graph.
    When you are satisfied with the number of slices, copy/drag the graph and ungroup it. Now you can colour the slices as you wish.
    It's a good idea to keep the original grouped graph in case you need to add slices in the data spreadsheet.

  • Need help with adding graphics to NSTextView

    I am looking for information on adding graphics to NSTextView so that the graphic is linked to a point in the text and will move with it as the window is resized. I understand that a subclass of NSTextContainer is needed to define the line lengths, etc. for NSLayoutManager. What I cannot figure out is how to know what text is being processed when the message to specify line positions is received by the subclass.
    What I really need is a sample program that shows how to link a graphic to the text.

    I did that bad it's not there and doesn't give me to option to click on it

Maybe you are looking for

  • Dynamic Archiving in File-Proxy Interface

    Hi Experts, My scenario is File -> Proxy which updates certain data in the target SAP system. The logic in the receiver side is that, if the update fails, then the input file must be placed in Folder A. Else if the update is successful, then the file

  • Hi, I have a Beolit12, which stutters using airplay with my Imac

    Hi Everyone I hope some can please help I have a Bang & Olufsen Beolit 12, which plays perfectly using Airplay from Ipad and Iphone 5, but stutters every 30 seconds or so from my Imac Any ideas please!!!!!!

  • Command Query using UNION

    Hello, I may be barking up the wrong tree and asking this question in the wrong forum so please accept my apologies if this is the case. I have access to a MYSql database through a ODBC connection and would like to create a report based on four table

  • Image not aligning

    hi... can you please check why the heading named INTERactive not alingning with the bottom edge of the navegation menu like in the rest of the pages??? this is the link http://www.alexcas.com/interactive.html

  • First time using PSCS5 since updating to 10.9.1 from 10.8.5

    Files are opening very slow. Probably five times slower than with Mountain Lion, which was slower than Tiger. Maybe I should reboot, but I have enough free RAM that it shouldn't be a problem. By slow I mean more than a minute to open a RAW and at lea