Help in 2d Graphics in Swing

In my program, you click on a JPanel and a picture should display. The code has no errors, it just doesn't work. Here's the code:
private void jPanel100MousePressed(java.awt.event.MouseEvent evt) {
String imageFile = "corn.gif";
Image image = Toolkit.getDefaultToolkit().getImage(imageFile);
int iw = 200;
int ih = 200;
BufferedImage bi = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB);
Graphics2D big = bi.createGraphics();
big.drawImage(image,0,0,this);
I do have a file named "corn.gif" in the same folder as the program, which is in the same folder as the compiler and the runner of the program. But why doesn't my picture display?

The strategy is to first create your BufferedImage, create a component who will draw the image in itself and then control the painting from within your event code.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageDisplay {
  static BufferedImage bi;
  static boolean showBI = true;
  static JPanel panel;
  public static void main(String[] args) {
    String imageFile = "images/cougar.jpg";
    File file;
    Image image = null;
    try {
      file = new File(imageFile);
      image = ImageIO.read(file);
    catch(FileNotFoundException fnf) {
      System.out.println(fnf.getMessage());
    catch(IOException ioe) {
      System.out.println(ioe.getMessage());
    int w = image.getWidth(null);
    int h = image.getHeight(null);
    bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage(image, 0, 0, null);
    g2.dispose();
    panel = new JPanel() {
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int w = getWidth();
        int h = getHeight();
        int biWidth = bi.getWidth();
        int biHeight = bi.getHeight();
        if(showBI)
          g.drawImage(bi, (w - biWidth)/2, (h - biHeight)/2, null);
    panel.setBackground(Color.pink);
    final JButton showButton = new JButton("show image");
    final JButton removeButton = new JButton("remove image");
    ActionListener l = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        JButton button = (JButton)e.getSource();
        if(button == showButton) {
          showBI = true;
          panel.repaint();
        if(button == removeButton) {
          showBI = false;
          panel.repaint();
    showButton.addActionListener(l);
    removeButton.addActionListener(l);
    JPanel southPanel = new JPanel();
    southPanel.add(showButton);
    southPanel.add(removeButton);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(panel);
    f.getContentPane().add(southPanel, "South");
    f.setSize(400,400);
    f.setLocation(400,300);
    f.setVisible(true);
}

Similar Messages

  • 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();
    }

  • Help updating ATI graphics driver in bootcamp Windows 8.1 on iMac (Retina 5K, 27-inch) with 4 GHz Intel core i7, 16 GB 1600 MHz DDR3 and AMD Radeon R9 M295x 4096MB

    Help updating ATI graphics driver in bootcamp Windows 8.1 on iMac (Retina 5K, 27-inch) with 4 GHz Intel core i7, 16 GB 1600 MHz DDR3 and AMD Radeon R9 M295x 4096MB

    Of note there is a new AMD Catalyst Omega driver released earlier in the week that brings 5K resolution to AMD graphics cards. Here is the link (support.ad.com/en-us/download) to the AMD site. But none of these work with my iMac (Retina 5K, 27-inch, Late 2014), Windows 8 bootcamp.
    Please advise.
    Thanks in advace.

  • I need help updating the graphic drivers for my laptop.

    Recently purchasd a new game and I am having some issues with the graphics. Every post I have read suggests it is an issue between HP and amd. I keep trying and seem to be going backwards. I would love to actually talk to someone from hp but they haven their number very well. I have tried every combination between hp and amd and I am obviously missing something. I dont have much hair left to pull out.

    Hi there ,  Thank you for visiting the HP Support Forums and Welcome! This is a great site to get answers and ask questions.  I read your post on the HP Support Forums and you had mentioned that you are looking for help Updating the Graphics Drivers on your HP Pavilion dv7t-6c00 CTO Notebook PC.  I have the actual drivers page for your specific HP Pavilion dv7t-6c00 CTO. It has the AMD Graphic Driver on this page. You could also update the drivers a couple other ways.  1. Using the HP Support Assistant2. Going into the Device Manager, Right click on the AMD Graphic and doing an update.  You had also mentioned that you wanted to actually talk to someone from HP. Please use the following link to create yourself a case number, then call and it may help speed up the call process:
    Step 1. Open link: www.hp.com/contacthp/Step 2. Enter Product number or select to auto detect
    Step 3. Scroll down to "Still need help? Complete the form to select your contact options"
    Step 4. Scroll down and click on: HP contact options - click on Get phone number
    Case number and phone number appear.
    They will be happy to assist you immediately. Let me know how everything goes.  Have a great day!

  • Fancy Graphics in Swing

    Is it possible to make fency graphics in Swing.
    I am refering like moving button in tool bar. Like object scroll on the screen slowly and so on. And would this require a lot of work and processing?

    Thanks for the examples :) ... I tried them bouth, however the one you submited did not seem to do anything.
    However I will go home and check it out better, thanks again for the link :)

  • Representating Hierarchical (Parent-Child) relation graphically using Swing

    Hi,
    I have to represent a hierarchical data which is having Parent-Child relation using Swing. I am not able to upload the image overhere, so I am represnting the data in such a way so that one can understand this problem. If anyone knows how to upload image on Sun forum, please let me know it will be great help for me.
    Parent Root - A
    Child of A - B, C, D
    Child of C - E, F, G
    Child of F - H
    Child of D - J, K
    The data needs to be represented in two formats-
    1. Tabular Format
    I am able to represent data in this format using combination of JTree and JTable. The data is getting represented in tabular format and I am able to expand and collapse the parent nodes to see the childs. The tabular data will look like below structure,
    A
    I_B
    I
    I_C
    I I_E
    I I
    I I_F
    | I |_H
    | I
    I I_G
    I
    I_D
    I
    I_J
    I
    I_K
    2. Graphical Format
    This is the other way in which I need to represent the data. The above shown tabular data needs to represented in graphical form. The end result should look like,
    I A I
    ____________________I__________________________
    ___I___ __I__ __I__
    I  B  I I  C   I I  D   I
    ____________________I____________ ______I________
    ___I___ __I__ __I__ __I__ ___I__
    I  E  I I  F   I I  G   I I  J   I I   K    I
    __I___
    I   H   I
    Each box representing alphabates will be a component (like JPanel) which will have details about the item to be displayed. The parent and child should be connected with each other using line. This representation should be created at runtime using the hierarchical data. Also the parent and child relations should be expandable/collapsible as they are in JTree.
    I am not able to find any component or any solution in Swing which can provide me this graphical representation. It will be great help if anyone can help me out in this.
    Thanks in advance.

    Sorry for inconvinience for the data representaion in graphical form. I don't know how this get jumblled. Please try to figure out the tabular/graphical representation using pen and paper as forum is not providing any help to upload an image.
    Sorry again for inconvinience.
    Thanks
    Manoj Rai

  • How to use Graphics in swings?

    Hi,
    I would like to write a Graphics application in swings, Is it possibel?
    help me.

    Hi,
    I would like to write a Graphics application in
    swings, Is it possibel?
    help me.Yes! a short example using JApplet in swing using graphics.
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.JApplet;
    public class Animate extends JApplet implements Runnable {
        Thread runner;
        boolean notDone;
        int x, y;
        public void init(){
            notDone = true;
            x = 10;
            y = 20;
            setSize(500,100);
            startRunning();
        public void run(){
            while(notDone){
                if(x < 400){
                    x++; repaint();
                    try {
                        Thread.sleep(500); // control the speed
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                } else {
                    x = 10;
        public void startRunning(){
            runner = new Thread(this);
            runner.start();
        public void paint(Graphics g){
            animate(g);
        public void repaint(){
            try{
                Image img = this.createImage(getSize().width , getSize().height);
                Graphics g = img.getGraphics();
                g.setColor(this.getBackground());
                g.fillRect(0, 0, getSize().width, getSize().height);
                g.setColor(this.getForeground());
                paint(g);
                this.getGraphics().drawImage(img, 0, 0, null);
            }catch(NullPointerException e){}
        public void animate(Graphics g){
            g.drawString("Help me -->", x, y);
    }

  • Help with 2D Graphics - How do I send Variable data to paint method?

    I am working on a program that figures mortgage payments and an amortization schedule when a user inputs the principle, APR, and term length in years. After it figures all of those, I want to be able to display a chart that shows the principle and interest amounts for each year. My problem is, how do I get my loan information into my paint method so that I can draw a chart using that data? Any help would be greatly appreciated. The graph class in the code below is called after pressing a "Display Graph" button from my GUI.
    I'm pasting my code below. This does not include my main method or my GUI method. I can post those if necessary. Here is my code so far:
    import java.util.*;
    import java.lang.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.io.*;
    import java.lang.Math;
    public class Graph extends JFrame
         public Graph(double dCurrentBalance, double dMonthlyPmt, double dRate, int iTime)
              final double balance = dCurrentBalance;
              JFrame graphFrame;
              int iCounter = 0;
              int iPmtNumber = 0;
              double dCurrentInt = 0.0;
              double dCurrentPrinciple = 0.0;
              double dMPR = 0.0;
              int yCoordInt = 0;               //integer for Y coordinate for Interest
              int yCoordPrinciple = 0;     //integer for Y coordinate for Principle
              iTime *= 12;               //determine number of months for this loan
              iCounter = iTime;          //set loop counter to number of months for this loan
              dMPR = dRate/12;          //determine monthly periodic rate
              graphFrame = new JFrame ("mCalc Graph");
              graphFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              graphFrame.setSize(800,600);
              graphFrame.setResizable(false);
              // center graphFrame on the screen
         Dimension ScreenSize = Toolkit.getDefaultToolkit().getScreenSize();
         Dimension FrameSize = graphFrame.getSize();
         if (FrameSize.height > ScreenSize.height)
         FrameSize.height = ScreenSize.height;
         if (FrameSize.width > ScreenSize.width)
         FrameSize.width = ScreenSize.width;
         graphFrame.setLocation((ScreenSize.width - FrameSize.width) / 2,
                   (ScreenSize.height - FrameSize.height) / 2);
              //Displays graphFrame
              Graphic graphicPane = new Graphic();
              graphFrame.add(graphicPane);
              graphFrame.setVisible(true);
              //This loops until all payments have been figured
              for (; iCounter > 0; )
         iPmtNumber++;
         dCurrentInt = dCurrentBalance * dMPR;
         dCurrentPrinciple = dMonthlyPmt - dCurrentInt;
         dCurrentBalance = dCurrentBalance - dCurrentPrinciple;
                   if (iPmtNumber%12 == 0)
    //           System.out.println("dCurrentBalance = " + dCurrentBalance);
    //                    System.out.println("Payment # = " + iPmtNumber);
    //                    System.out.println("dCurrentInt = " + dCurrentInt);
    //                    System.out.println("dCurrentPrinciple = " + dCurrentPrinciple);
         iCounter = iCounter-1;
              } //end for loop
         } //end Graph constructor
    /* This class needs to be personalized to include my own variable names,
    *     etc. I also need to find a way to bring in data from the Graph class.
         class Graphic extends JPanel
              public void paintComponent(Graphics comp)
                             int i; // Declare the variables used to generate the chart
    float xLoc = 50; // Location of the X Axis along Y
    float yLoc = 50; // Location of the Y Axis along X
    Line2D.Float LnA; //
    super.paintComponent(comp);
                   // Establish a tie between this subroutine and the Graphic
    Graphics2D comp2D = (Graphics2D) comp;
    // Cast the Graphics named comp to a Graphics2D as comp2D
    comp2D.setColor(Color.white);
    // Set the background color
    comp2D.fillRect(0,0,800,600);
    // Draw the X and Y axis
    comp2D.setColor(Color.black); // Set the pen color to black
    Line2D.Float YAxis = new Line2D.Float(50,50,50,getSize().height - 50); // Define the Y-Axis
    Line2D.Float XAxis = new Line2D.Float(50F,getSize().height - 50F, getSize().width -50F, getSize().height -50F); //Define the X-Axis
    comp2D.draw(YAxis); // Draw the Y-Axis
    comp2D.draw(XAxis); // Draw the X-Axis
    Font font = new Font("Dialog", Font.BOLD, 12); // Set the font for the Axis labels
    comp2D.setFont(font);
    float increment = 15;
    // Draw the line
    xLoc += increment;
    comp2D.setColor(Color.red);
    /* Need to find a way to bring in my own data to use for the
    * yLoc variables.
    for (i=1; i<=45; i++)
    { // Begin making the graph
    if (i < 30)
         yLoc += increment;
    } else {
         yLoc -= increment;
    // Scale the location to the graph height
    LnA = new Line2D.Float( xLoc, getSize().height - 50F , xLoc, yLoc); // Create the line
    comp2D.draw(LnA); // Draw the line
    xLoc += increment;
                             }//end for
                   }//end paintComponent
              } //end class Graphic
    } //end class Graph
    Any help would be GREATLY appreciated! Thanks.
    Message was edited by:
    russedl
    My email address iss [email protected] if you wish to reply privately. I can send my entire program code if that will help. Thanks!

    Hi Deca,
    You can use the CmdExecuteSync method of the DIAdem.TOCommand interface to set the value of a text channel. For example passing the string "CHT(1,1) := 'test'" as a parameter to the CmdExecuteSync method will set the 1st row of the 1st channel to "test". Please refer to the DIAdem help for more documentation on the CHT function.
    I hope this helps! Please post back if I wasn't clear enough in explaining how to do this or if you have any problems getting it to work.
    Regards,
    Sarah Miracle
    National Instruments

  • Help Plz! AWT to Swing Conversion

    Hey everyone, I'm new to java and trying to convert this AWT program to Swing, I got no errors, the menu shows but they dont work !! Could somebody please help me? thanks alot!
    Current Under-Construction Code: (no errors)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class zipaint extends JFrame implements ActionListener,      ItemListener,
    MouseListener, MouseMotionListener, WindowListener {
    static final int WIDTH = 800;     // Sketch pad width
    static final int HEIGHT = 600;     // Sketch pad height
    int upperLeftX, upperLeftY;     // Rectangle upper left corner coords.
    int width, height;          // Rectangle size
    int x1, y1, x2, y2, x3, y3, x4, y4; // Point coords.
    boolean fillFlag = false; //default filling option is empty
    boolean eraseFlag = false; //default rubber is off
    String drawColor = new String("black"); //default drawing colour is black
    String drawShape = new String("brush"); //default drawing option is brush
    Image background; //declear image for open option
    private FileDialog selectFile = new FileDialog( this,
    "Select background (.gif .jpg)",
    FileDialog.LOAD );
    // Help
    String helpText = "Draw allows you to sketch different plane shapes over a " +
    "predefined area.\n" + "A shape may be eother filled or in outline, " +
    "and in one of eight different colours.\n\n" + "The position of the " +
    "mouse on the screen is recorded in the bottom left-hand corner of the " +
    "drawing area. The choice of colour and shape are disoplayed also in the " +
    "left-habnd corner of the drawing area.\n\n" + "The size of a shape is " +
    "determined by the mouse being dragged to the final position and " +
    "released. The first click of the mouse will generate a reference dot on " +
    "the screen. This dot will disapear after the mouse button is released.\n\n" +
    "Both the square and the circle only use the distance measured along the " +
    "horizontal axis when determining the size of a shape.\n\n" + "Upon " +
    "selecting erase, press the mouse button, and move the mouse over the " +
    "area to be erased. releasing the mouse button will deactivate erasure.\n\n" +
    "To erase this text area choose clearpad from the TOOLS menu.\n\n";
    // Components
    JTextField color = new JTextField();
    JTextField shape = new JTextField();
    JTextField position = new JTextField();
    CheckboxGroup fillOutline = new CheckboxGroup();
    JTextArea info = new JTextArea(helpText,0,0/*,JTextArea.JSCROLLBARS_VERTICAL_ONLY*/);
    JFrame about = new JFrame("About Zi Paint Shop");
    // Menues
    String[] fileNames = {"Open","Save","Save as","Exit"};
    String[] colorNames = {"black","blue","cyan","gray","green","magenta","red","white","yellow"};
    String[] shapeNames = {"brush","line","square","rectangle","circle","ellipse"};
    String[] toolNames = {"erase","clearpad"};
    String[] helpNames = {"Help","about"};
    public zipaint(String heading) {
    super(heading);
    getContentPane().setBackground(Color.white);
    getContentPane().setLayout(null);
    /* Initialise components */
    initialiseTextFields();
    initializeMenuComponents();
    initializeRadioButtons();
    addWindowListener(this);
    addMouseListener(this);
    addMouseMotionListener(this);
    /* Initialise Text Fields */
    private void initialiseTextFields() {
    // Add text field to show colour of figure
    color.setLocation(5,490);
    color.setSize(80,30);
    color.setBackground(Color.white);
    color.setText(drawColor);
    getContentPane().add(color);
    // Add text field to show shape of figure
    shape.setLocation(5,525);
    shape.setSize(80,30);
    shape.setBackground(Color.white);
    shape.setText(drawShape);
    getContentPane().add(shape);
    // Add text field to show position of mouse
    position.setLocation(5,560);
    position.setSize(80,30);
    position.setBackground(Color.white);
    getContentPane().add(position);
    // Set up text field for help
    info.setLocation(150,250);
    info.setSize(500,100);
    info.setBackground(Color.white);
    info.setEditable(false);
    private void initializeMenuComponents() {
    // Create menu bar
    JMenuBar bar = new JMenuBar();
    // Add colurs menu
    JMenu files = new JMenu("Files");
    for(int index=0;index < fileNames.length;index++)
    files.add(fileNames[index]);
    bar.add(files);
    files.addActionListener(this);
    // Add colurs menu
    JMenu colors = new JMenu("COLORS");
    for(int index=0;index < colorNames.length;index++)
    colors.add(colorNames[index]);
    bar.add(colors);
    colors.addActionListener(this);
    // Add shapes menu
    JMenu shapes = new JMenu("SHAPES");
    for(int index=0;index < shapeNames.length;index++)
    shapes.add(shapeNames[index]);
    bar.add(shapes);
    shapes.addActionListener(this);
    // Add tools menu
    JMenu tools = new JMenu("TOOLS");
    for(int index=0;index < toolNames.length;index++)
    tools.add(toolNames[index]);
    bar.add(tools);
    tools.addActionListener(this);
    // Add help menu
    JMenu help = new JMenu("HELP");
    for(int index=0;index < helpNames.length;index++)
    help.add(helpNames[index]);
    bar.add(help);
    help.addActionListener(this);
    // Set up menu bar
    setJMenuBar(bar);
    /* Initilalise Radio Buttons */
    private void initializeRadioButtons() {
    // Define checkbox
    Checkbox fill = new Checkbox("fill",fillOutline,false);
    Checkbox outline = new Checkbox("outline",fillOutline,true);
    // Fill buttom
    fill.setLocation(5,455);
    fill.setSize(80,30);
    getContentPane().add(fill);
    fill.addItemListener(this);
    // Outline button
    outline.setLocation(5,420);
    outline.setSize(80,30);
    getContentPane().add(outline);
    outline.addItemListener(this);
    /* Action performed. Detects which item has been selected from a menu */
    public void actionPerformed(ActionEvent e) {
    Graphics g = getGraphics();
    String source = e.getActionCommand();
    // Identify chosen colour if any
    for (int index=0;index < colorNames.length;index++) {
    if (source.equals(colorNames[index])) {
    drawColor = colorNames[index];
    color.setText(drawColor);
    return;
    // Identify chosen shape if any
    for (int index=0;index < shapeNames.length;index++) {
    if (source.equals(shapeNames[index])) {
    drawShape = shapeNames[index];
    shape.setText(drawShape);
    return;
    // Identify chosen tools if any
    if (source.equals("erase")) {
    eraseFlag= true;
    return;
    else {
    if (source.equals("clearpad")) {
    remove(info);
    g.clearRect(0,0,800,600);
    return;
    if (source.equals("Open")) {
    selectFile.setVisible( true );
    if( selectFile.getFile() != null )
    String fileLocation = selectFile.getDirectory() + selectFile.getFile();
    background = Toolkit.getDefaultToolkit().getImage(fileLocation);
    paint(getGraphics());
    if (source.equals("Exit")) {
    System.exit( 0 );
    // Identify chosen help
    if (source.equals("Help")) {
    getContentPane().add(info);
    return;
    if (source.equals("about")) {
    displayAboutWindow(about);
    return;
    public void paint(Graphics g)
    super.paint(g);
    if(background != null)
    Graphics gc = getGraphics();
    gc.drawImage( background, 0, 0, this.getWidth(), this.getHeight(), this);
    /* Dispaly About Window: Shows iformation aboutb Draw programme in
    separate window */
    private void displayAboutWindow(JFrame about) {
    about.setLocation(300,300);
    about.setSize(350,160);
    about.setBackground(Color.cyan);
    about.setFont(new Font("Serif",Font.ITALIC,14));
    about.setLayout(new FlowLayout(FlowLayout.LEFT));
    about.add(new Label("Author: Zi Feng Yao"));
    about.add(new Label("Title: Zi Paint Shop"));
    about.add(new Label("Version: 1.0"));
    about.setVisible(true);
    about.addWindowListener(this);
    // ----------------------- ITEM LISTENERS -------------------
    /* Item state changed: detect radio button presses. */
    public void itemStateChanged(ItemEvent event) {
    if (event.getItem() == "fill") fillFlag=true;
    else if (event.getItem() == "outline") fillFlag=false;
    // ---------------------- MOUSE LISTENERS -------------------
    /* Blank mouse listener methods */
    public void mouseClicked(MouseEvent event) {}
    public void mouseEntered(MouseEvent event) {}
    public void mouseExited(MouseEvent event) {}
    /* Mouse pressed: Get start coordinates */
    public void mousePressed(MouseEvent event) {
    // Cannot draw if erase flag switched on.
    if (eraseFlag) return;
    // Else set parameters to 0 and proceed
    upperLeftX=0;
    upperLeftY=0;
    width=0;
    height=0;
    x1=event.getX();
    y1=event.getY();
    x3=event.getX();
    y3=event.getY();
    Graphics g = getGraphics();
    displayMouseCoordinates(x1,y1);
    public void mouseReleased(MouseEvent event) {
    Graphics g = getGraphics();
    // Get and display mouse coordinates
    x2=event.getX();
    y2=event.getY();
    displayMouseCoordinates(x2,y2);
    // If erase flag set to true reset to false
    if (eraseFlag) {
    eraseFlag = false;
    return;
    // Else draw shape
    selectColor(g);
    if (drawShape.equals("line")) g.drawLine(x1,y1,x2,y2);
    else if (drawShape.equals("brush"));
    else drawClosedShape(drawShape,g);
    /* Display Mouse Coordinates */
    private void displayMouseCoordinates(int x, int y) {
    position.setText("[" + String.valueOf(x) + "," + String.valueOf(y) + "]");
    /* Select colour */
    private void selectColor(Graphics g) {
    for (int index=0;index < colorNames.length;index++) {
    if (drawColor.equals(colorNames[index])) {
    switch(index) {
    case 0: g.setColor(Color.black);break;
    case 1: g.setColor(Color.blue);break;
    case 2: g.setColor(Color.cyan);break;
    case 3: g.setColor(Color.gray);break;
    case 4: g.setColor(Color.green);break;
    case 5: g.setColor(Color.magenta);break;
    case 6: g.setColor(Color.red);break;
    case 7: g.setColor(Color.white);break;
    default: g.setColor(Color.yellow);
    /* Draw closed shape */
    private void drawClosedShape(String shape,Graphics g) {
    // Calculate correct parameters for shape
    upperLeftX = Math.min(x1,x2);
    upperLeftY = Math.min(y1,y2);
    width = Math.abs(x1-x2);
    height = Math.abs(y1-y2);
    // Draw appropriate shape
    if (shape.equals("square")) {
    if (fillFlag) g.fillRect(upperLeftX,upperLeftY,width,width);
    else g.drawRect(upperLeftX,upperLeftY,width,width);
    else {
    if (shape.equals("rectangle")) {
    if (fillFlag) g.fillRect(upperLeftX,upperLeftY,width,height);
    else g.drawRect(upperLeftX,upperLeftY,width,height);
    else {
    if (shape.equals("circle")) {
    if (fillFlag) g.fillOval(upperLeftX,upperLeftY,width,width);
    else g.drawOval(upperLeftX,upperLeftY,width,width);
    else {
    if (fillFlag) g.fillOval(upperLeftX,upperLeftY,width,height);
    else g.drawOval(upperLeftX,upperLeftY,width,height);
    /* Mouse moved */
    public void mouseMoved(MouseEvent event) {
    displayMouseCoordinates(event.getX(),event.getY());
    /* Mouse dragged */
    public void mouseDragged(MouseEvent event) {
    Graphics g = getGraphics();
    x2=event.getX();
    y2=event.getY();
    x4=event.getX();
    y4=event.getY();
    displayMouseCoordinates(x1,y1);
    if (eraseFlag) g.clearRect(x2,y2,10,10);
    else {
    selectColor(g);
    if(drawShape.equals("brush")) g.drawLine(x3,y3,x4,y4);
    x3 = x4;
    y3 = y4;
    // ---------------------- WINDOW LISTENERS -------------------
    /* Blank methods for window listener */
    public void windowClosed(WindowEvent event) {}
    public void windowDeiconified(WindowEvent event) {}
    public void windowIconified(WindowEvent event) {}
    public void windowActivated(WindowEvent event) {}
    public void windowDeactivated(WindowEvent event) {}
    public void windowOpened(WindowEvent event) {}
    /* Window Closing */
    public void windowClosing(WindowEvent event) {
    if (event.getWindow() == about) {
    about.dispose();
    return;
    else System.exit(0);
    Code End
    Thanks again!
    class ziapp {
    /* Main method */
    public static void main(String[] args) {
    zipaint screen = new zipaint("Zi Paint Shop");
    screen.setSize(zipaint.WIDTH,zipaint.HEIGHT);
    screen.setVisible(true);

    First of all use the [url http://forum.java.sun.com/features.jsp#Formatting]Formatting Tags when posting code to the forum. I'm sure you don't code with every line left justified so we don't want to read unformatted code either.
    Hey everyone, I'm new to java and trying to convert this AWT program to SwingInstead of converting the whole program, start with something small, understand how it works and then convert a different part of the program. You can start by reading this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html]How to Use Menus.
    From a quick glance of your code it looks like you are not adding an ActionListener to your JMenuItems. You are adding them to the JMenu.
    Other observations:
    1) Don't mix AWT with Swing components. You are still using CheckBox
    2) Don't override paint(). When using Swing you should override paintComponent();
    3) Use LayoutManagers. Using a null layout does not allow for easy maintenance of the gui. Right now you are using 800 x 600 as your screen size. Most people are probably using at least 1024 x 768 screen sizes. When using LayoutManagers you would suggest component sizes by using setPreferredSize(), not setSize().

  • Urgent Help Needed: ATI Graphics Card install

    Hello All.... I am in need of some urgent help..
    I am trying to install a new graphics card - the ATI Radeon 9600 SE. I currently have a Voodoo3 card. I followed all of the instructions step by step, but when I plug the monitor to the Radeon card and boot up, I do not get any display. I have tried everything I can think of, and yet - I am sure the card is secured in place and the monitor is plug into the card.
    Can anyone help me on this one.. ATI's support is, well - lacking..
    Here is some info on my pc:
    MCI motherboard
    AMD Athlon(tm) XP 2000+ 1.7 GHz
    768 MB
    AMIINT - 10 Version 1.00, 07/10/02
    Could the problem be with switching from a regular PCI card to an AGP card???

    Quote
    Originally posted by southmike
    okay i'll bite what are omega drivers,
    how are they different from cat4.2 drivers
    i was suprised that the voodoo 3 would work in a AMD64 mobo...
    whoops....just read the rest of the post :lol:
    BTW is there an external power connector that needs to be plugged in?

  • HELP! Upgrading Graphics Card on Mac Pro 2009

    Hi all,
    I'm interested in upgrading my current graphics card NVIDIA GeForce GT 120 512 MB to something with more memory.
    I'm having a hard time trying to figure out which brand to go with that'll be compatible with my Mac Pro 2009 model and will work well under OSX Mavericks.
    I really dont want to break the bank. Need a good amount of GDDR5 ram for Adobe Creative Cloud mostly. Would also like to run some gaming on PC Bootcamp drive under Windows 7 (Titanfall, Crysis, Battlefield, etc). However that's all secondary, thanks for your help.

    LOTS of choices, depends if you want ones that will work without fuss (ATI 5770 & 5870 plus Mac edition EVGA 680 and Sapphire 7950) still give you boot screens if you option boot.
    If you don't care about boot screens, you can use almost any recent ATI or Nvidia card. If you only boot into OSX, you can live without boot screens.

  • 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 installing my graphics driver in windows vista via boot camp

    New to mac so first time on forum as well.
    Love the Mac but i also want to get on some old games. C&C The First Decade mainly.
    I am currently using below.
    Mac mini Mid 2011 processor 2.5 GHz Intel Core it
    Memory 4 GB 1333 Mhz DDR3
    Graphics AMD Radeon HD 6630M 256 MB
    Software Mac OS X Lion 10.7.5
    Installing windows vista home premium 32 bit
    I have installed windows vista home premium using boot camp assistant and downloaded the windows drivers as well. After i have installed windows i installed boot camp using my Mac OS X snow leopard which installed boot camp 3 or 3.1 i believe and i eventually got apple updates for 3.2 which is what i am now runnning on vista. I had trouble getting my sound to play through my speakers at first but eventually got them working and now it is my graphics driver that i cannot seem to get working. In vista(I also downloaded service pack 1 and 2) when i go to control panel and check out my device control it shows a yellow exclamation point next to the adapter. I guess i need help in getting my graphics installed correctly on my windows. Is there something i should take off to install the correct driver? Or do i just need the correct driver download? If i have the correct driver how do i upload it onto my windows side in the device control.
    When i try to run c&c generals/zero hour i get a directx 8.1 error, red alert 2 is black but i can hear. i know these games can work i installed the graphics correctly the first time when i did not have sound as this is my second time installing windows so the game did load when i did not have sound.
    Advise?
    I was thinking about saying forget this i can't waste hours of my time anymore but i have to be close to getting everything working if i had graphics before and no sound but sound this time and no graphics. I was also thinking about just buying windows 7 home premium sp1 64bit system builder dvd off amazon and reinstalling windows using windows 7 but i want to make sure i can play these games before i spend the money. I thought my mini couldn't support windows vista and if it did only boot camp 4? how am i getting this far to get things to work?
    What is the driver i need to install to get these games working? What do I need to do or what am I missing???
    Do i need to install a different boot camp off apple and find a driver that will get mine to work in vista?
    Any and all responses will be greatly appreciated i have been at this everyday for hours.

    Also is there something, say maybe a driver, that was installed i do not need that is blocking me from installing the correct drivers? What driver in my boot camp folder do i need to install to get to the correct display to run those games.

  • 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

  • Help for a begginer using swing

    Basically I need help with a program for a school project. i am not looking for a quick answer but rather some pointers in the right direction. This is my first time using swing and my first project is to create a blackJack game. I am having trouble with functionality. there are problems on tab 2 with almost all the buttons. any help would be greatly appreciated. since i didnt have enough room for all my code i posted it online to be accessed at this site: [https://code.google.com/p/blackjackgui-alpha/]

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
    String betString = jTextField2.getText();
    betString = Integer.toString(bet);// TODO add your handling code here:
    total = total - bet;
      private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
        System.exit(0);        // TODO add your handling code here:
      private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        String name = jTextField1.getText();
        String prefix = (String)jComboBox1.getSelectedItem();
        jLabel2.setText("Hello " + prefix + name + " and welcome to blackJack please press the tab labeled BlackJack");
          jLabel3.setText("Welcome to you personal blackJack game " + prefix + name + " your cards are" + card1 + "(" + card1s + ") and " + card2 + "(" +card2s + ")  your hand total is " + handTotal);
        jLabel5.setText("This is where you may see the Dealers information " + prefix + name);
      private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
              handTotal = card1 + card2;
              if(handTotal > 21)
                  jLabel3.setText("You busted press hit");
                  handTotal = 0;
              handTotal = card1+card2;
              dealerHandTotal = 0;
              dealerHandTotal = dealerCard1 + dealerCard2;
              handTotal = handTotal + card3;
          jLabel3.setText("You have hit and recieve " + card3 +   "your total is " + handTotal);
                jLabel5.setText("Dealer hits and recieves " + dealerCard1 + "(" + dealerCard1s + ") and " + dealerCard2 + "(" + dealerCard2s + ")  Dealer total is " + dealerHandTotal);
        if(handTotal > 21)
          jLabel3.setText("I am sorry, you busted with: " + handTotal + "Please press hit to begin a new round");
    handTotal = 0;
          card1=card1;
          card2 = card2;
        else if( handTotal == 21)
              total =  total + (bet*2);
          jLabel3.setText("BLACKJACK!!! your total is now: " + total);
          handTotal = 0;
          dealerHandTotal = 0;
        else if(handTotal == dealerHandTotal)
            jLabel3.setText("PUSH ...house automatically wins");
                       jLabel5.setText("PUSH ...house automatically wins");
                       handTotal = 0;
                       dealerHandTotal = 0;
        else if(dealerHandTotal < 17 || handTotal > dealerHandTotal) {
                    dealerHandTotal = dealerHandTotal + dealerCard1;
        else if(dealerHandTotal == 21)
            jLabel5.setText("DEALER GETS BLACKJACK!!")
                    dealerHandTotal = 0;
            dealerHandTotal = dealerCard1+dealerCard2;
            handTotal = 0;
            handTotal = card1 + card2;
      private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        jLabel3.setText("You have stood at " + handTotal);   // TODO add your handling code here:
      private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        jLabel3.setText("You have folded at your total of: " + handTotal);
        jLabel5.setText("You have folded at you total of:" + handTotal)
        handTotal = 0;
        dealerHandTotal = 0;
      }                  Sorry i thought it would be more convenient for the code to be on another page..my bad
    Edited by: rightWingNutJob on Mar 4, 2010 2:07 PM
    Edited by: rightWingNutJob on Mar 4, 2010 2:30 PM

Maybe you are looking for