1

Im trying to display an image upon clicking a JButton but upon execution the image is not displayed when button is clicked.

    import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import java.awt.*;

public class new2 extends JFrame implements ActionListener
{
private boolean b1,b2;  

Container contentPane= getContentPane();
JButton awar=new JButton("@war");
JButton arrow=new JButton("arrow");
private Image image1,image2;

public new2()
    {
    setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane.setLayout(new FlowLayout());

        awar.addActionListener(this);
        contentPane.add(awar).setVisible(true);

        arrow.addActionListener(this);
        contentPane.add(arrow).setVisible(true);

        }

public void init()
    {


    image1=Toolkit.getDefaultToolkit().getImage("@war.jpeg");
    image2=Toolkit.getDefaultToolkit().getImage("arrow.gif");
    }


public void paint(Graphics g)
{

    if(b1==true)
    {
    g.drawImage(image1,0,0,this);
    }
    else if(b2==true)
    {
    g.drawImage(image2,0,0,this);
    }

}

public void actionPerformed(ActionEvent event)
{

        String actionCommand = event.getActionCommand();

    if(actionCommand.equals("@war"))
    {
    b1=true;
    }
    else if(actionCommand.equals("arrow"))
    {
    b2=true;
    }
}

public static void main(String args[])
{
new2 m=new new2();
m.setVisible(true);
}

}

Abhyudaya
  • 13
  • 1
  • 1
  • 5
  • im trying to display an image when a jbutton is clicked by using the above program. but on execution, the buttons are displayed but they do not work as expected on being clicked. pls help. :( – Abhyudaya Aug 27 '11 at 11:47
  • 1
    please post the whole code or better an SSCCE. In particular we should see your actionPerformed method implementation. – Heisenbug Aug 27 '11 at 11:50
  • oh m sorry...guess the whole code wasn't copied.... – Abhyudaya Aug 27 '11 at 11:57
  • never paint in a JFrame `paint(...)` rather add a `JPanel` to the `JFrame` and override its `paintComponent()` – David Kroukamp Oct 01 '12 at 09:02

4 Answers4

4

..display an image upon clicking a JButton but upon execution the image is not displayed when button is clicked.

Use a JToggleButton as shown here.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

The buttons should set the boolean variables, but your paint2 is never called after the action preformed method. Secondly, it doesn't really even paint anything, it never gets graphics and will cause NPEs.

jzd
  • 23,473
  • 9
  • 54
  • 76
  • so how can i make it work?? i mean i first used paint() instead of paint2() as in an applet but it dint seem to work so i modified it to paint2(). are there any changes possinle in above code to make it work?? – Abhyudaya Aug 27 '11 at 12:09
  • You need to force a repaint in your actionPerformed method. Second your need to actually override a paint() method that gives you the Graphics you need to paint on. I would highly suggest reading about painting in Swing. – jzd Aug 27 '11 at 12:11
  • i have studied paint() but unfortunately i haven't covered repaint() as yet...is it possible for you to pls provide me a code that would actually execute my purpose and would be simple to understand? – Abhyudaya Aug 27 '11 at 12:14
  • Follow the Swing tutorials that have pages and pages of working example for each item. – jzd Aug 27 '11 at 12:15
  • i have found and studied examples for displaying images in an applet and in an application,also i have used jbuttons for simple purposes like displaying message box or modifying text field however i couldn't find a single working example of an image being displayed by click of a button and hence finally posted it as a question....:( – Abhyudaya Aug 27 '11 at 12:19
  • @Abhyd get painting of the image working first then try to control it with the button click. – jzd Aug 27 '11 at 12:36
  • @jzd the image and button are working fine as two seperate programs but i can't combine them that is the basic problem...can u pls provid me a code that would do so?? – Abhyudaya Aug 27 '11 at 12:40
1

You should override the JFrame.paint(Graphics g) method. Whenever you want to refresh the content of the JFrame instance call the JFrame.repaint() method.

Ammar
  • 2,387
  • 1
  • 14
  • 12
  • is the edited code correct for overriding? this is my actual code....the one with paint2() was modified one.. – Abhyudaya Aug 27 '11 at 12:19
  • cant the image be displayed in a new frame? i mean, the one with buttons remaining intact so that 2 buttons open two images...that's what im actually trying to do... – Abhyudaya Aug 27 '11 at 12:24
  • you should write something like: @Override public void paint(Graphics g) { // paint operations go here } – Ammar Aug 27 '11 at 12:26
  • @Override public void paint(Graphics g) { if(b1==true) { g.drawImage(image1,0,0,this); } else if(b2==true) { g.drawImage(image2,0,0,this); } } – Abhyudaya Aug 27 '11 at 12:31
  • yet the same result....but overriding or repainting will cause the image to be displayed in the same frame but i want it in a new one... – Abhyudaya Aug 27 '11 at 12:32
1
/**
 * 
 */
package com.samples;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

/**
 * @author
 *
 */
public class MyFrame extends JFrame implements ActionListener {

    private static String SHOW_ACTION = "show";
    private static String HIDE_ACTION = "hide";

    private Image image = null;
    private boolean showImage = false;

    public MyFrame(String filename) {
        setTitle("MyWindow");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(800, 600);

        this.image = new ImageIcon(filename).getImage();

        Container container = getContentPane();
        container.setLayout(new BorderLayout());
        container.add(createControls(), BorderLayout.SOUTH);
    }

    private JPanel createControls() {
        JButton showButton = new JButton("Show");
        showButton.addActionListener(this);
        showButton.setActionCommand(SHOW_ACTION);

        JButton hideButton = new JButton("Hide");
        hideButton.addActionListener(this);
        hideButton.setActionCommand(HIDE_ACTION);

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.CENTER));

        panel.add(showButton);
        panel.add(hideButton);

        return panel;
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        if (showImage) {
            g.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
        }
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        String actionCommand = event.getActionCommand();

        if (SHOW_ACTION.equals(actionCommand)) {
            showImage = true;
        } else if (HIDE_ACTION.equals(actionCommand)) {
            showImage = false;
        }

        repaint();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                MyFrame frame = new MyFrame("resources/image.jpg");
                frame.setVisible(true);
            }
        });
    }
}
Ammar
  • 2,387
  • 1
  • 14
  • 12
  • the program is compiled but does not execute...exception in thread "main" java.lang.NoClassDefFounderror – Abhyudaya Aug 27 '11 at 12:52
  • I have compiled it and executed it successfully. If you are using Eclipse make "Clean Project" then run it as a "Java Application". You can test it using the console. > javac MyFrame.java > java MyFrame – Ammar Aug 27 '11 at 13:16
  • i used it in console only...i do not use eclipse – Abhyudaya Aug 27 '11 at 13:28
  • you have to create the package com.samples. – Ammar Aug 27 '11 at 14:53
  • or you can simply delete the package declaration "com.samples" it must work this time. – Ammar Aug 27 '11 at 14:54