Resizing JFrame on button click to show an image on the JFrame

Dear All,
I have a JFrame which has an empty label. On button click I want to set an icon for the label and want the JFrame to be resized to show that icon. I am using frame.pack() and I am not using any other sizing function. The code that I have right now, prints the image on the panel, but does not resize the frame to show the image. Pleae could someone help.package gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ComponentDemo extends JPanel implements ActionListener,
ItemListener, MouseListener, KeyListener {
     private JTextArea textarea;
     private JButton button;
     private final static String newline = "\n";
     private JLabel imageIcon;
     public ComponentDemo() {
          button = new JButton("JButton welcomes you  to CO2001");
          button.addActionListener(this);
          add(button);
          textarea = new JTextArea(10, 50);
          textarea.setEditable(false);
          addMouseListener(this);
          textarea.addKeyListener(this);
          JScrollPane scrollPane = new JScrollPane(textarea);
          add(scrollPane);
          imageIcon = new JLabel();
          add(imageIcon);
          setBackground(Color.pink);
          new JScrollPane(this);
      * Create the GUI and show it. For thread safety, this method should be
      * invoked from the event-dispatching thread.
     private static void createAndShowGUI() {
          // Create and set up the window.
          JFrame frame = new JFrame("Simple FrameDemo");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          frame.setLocation(700, 200);
          // get the content pane and set the background colour;
          frame.add(new ComponentDemo());
     //     frame.setSize(screenSize);
          // frame.getContentPane().setBackground(Color.cyan);
          // Display the window.
          frame.pack();
          frame.setVisible(true);
          frame.setResizable(true);
     public static void main(String[] args) {
          // Schedule a job for the event-dispatching thread:
          // creating and showing this application's GUI.
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                    createAndShowGUI();
     @Override
     public void actionPerformed(ActionEvent e) {
          // TODO Auto-generated method stub
          if (e.getSource() instanceof JButton) {
               // System.out.println(e.getSource());
               String text = ((JButton) e.getSource()).getText();
               textarea.append(text + newline);
               textarea.setBackground(Color.cyan);
               textarea.setForeground(Color.BLUE);
               textarea.setCaretPosition(textarea.getDocument().getLength());
               imageIcon.setIcon(createImageIcon("SwingingDuke.png",
               "Image to be displayed"));
     @Override
     public void itemStateChanged(ItemEvent arg0) {
          // TODO Auto-generated method stub
     @Override
     public void mouseClicked(MouseEvent arg0) {
          textarea.append("A Mouse click welcomes you to CO2001" + newline);
          textarea.setBackground(Color.green);
          textarea.setCaretPosition(textarea.getDocument().getLength());
     @Override
     public void mouseEntered(MouseEvent arg0) {
          // TODO Auto-generated method stub
     @Override
     public void mouseExited(MouseEvent arg0) {
          // TODO Auto-generated method stub
     @Override
     public void mousePressed(MouseEvent arg0) {
          // TODO Auto-generated method stub
     @Override
     public void mouseReleased(MouseEvent arg0) {
          // TODO Auto-generated method stub
     @Override
     public void keyPressed(KeyEvent e) {
          System.out.println(e.getKeyChar());
          textarea.append("The key " + e.getKeyChar()
                    + " click welcomes you to CO2001" + newline);
          textarea.setBackground(Color.YELLOW);
          textarea.setFont(new Font("Arial", Font.ITALIC, 16));
          textarea.setCaretPosition(textarea.getDocument().getLength());
     @Override
     public void keyReleased(KeyEvent e) {
          System.out.println(e.getKeyChar());
          // textarea.append("The key "+
          // e.getKeyChar()+" click welcomes you to CO2001" + newline);
          // textarea.setBackground(Color.green);
          // textarea.setCaretPosition(textarea.getDocument().getLength());
     @Override
     public void keyTyped(KeyEvent e) {
          // TODO Auto-generated method stub
          System.out.println(e.getKeyChar());
          // textarea.append("The key "+
          // e.getKeyChar()+" click welcomes you to CO2001" + newline);
          // textarea.setBackground(Color.blue);
          // textarea.setCaretPosition(textarea.getDocument().getLength());
     /** Returns an ImageIcon, or null if the path was invalid. */
     protected ImageIcon createImageIcon(String path, String description) {
          java.net.URL imgURL = getClass().getResource(path);
          if (imgURL != null) {
               System.out.println("found");
               return new ImageIcon(imgURL, description);
          } else {
               System.err.println("Couldn't find file: " + path);
               return null;
}

myJPanel.setPerferredSize(new Dimension(new_width, new_hight));
myJFrame.pack();

Similar Messages

  • How do you show thumbnail images for the contacts?

    How do you show thumbnail images for the contacts on the iPod?
    -Thank You

    In another thread I posted a suggestion to try when the iPhoto app in the Application folder will not work:
    after upgrading the OS, iPhotos (and Aperture for that matter) should still be in the Applications folder...
    And running well in 10.10.3.
    If it stops running in a next "update" do not throw it away: most apps will continue running as follows:
    In the Applications folder "rightclick" (CTL+click) the iPhoto app, then "show package contents", then click the MacOs folder open: you see the real app (dark grey), rightclick this and choose "make alias", an alias is made, move this alias to the Applications folder and use it to run iPhoto.
    Same for Aperture.
    In older OS this survived several upgrades....
    Lex

  • Show an Image from the internet

    Hi,
    Im using the iphone sdk.
    I want to show an image on the iphone using the Image View control.
    The image is located on the web server. How do I need to proceed ?
    Thank you.

    You should probably ask this in a developer forum.
    This is a user forum.

  • Can an image in the slideshow widgets be moved around inside the bounding box as can be in a normal image placed into Muse (double clicking on a placed image gives the functionality to move the image around - as per Indesign functionality)

    Can an image in the slideshow widgets be moved around inside the bounding box as can be in a normal image placed into Muse (double clicking on a placed image gives the functionality to move the image around - as per Indesign functionality)

    Can an image in the slideshow widgets be moved around inside the bounding box as can be in a normal image placed into Muse (double clicking on a placed image gives the functionality to move the image around - as per Indesign functionality)

  • Adding .jpg image to the JFrame

    I want to add an image in the JFrame
    My code is as follows:
    import java.awt.*;
    import javax.swing.*;
    public class test extends JPanel
         JProgressBar pb1 = new JProgressBar(JProgressBar.HORIZONTAL,0,100);
    public test(String image)
    ImageIcon imgIco = new ImageIcon(image);
    JLabel imgLbl = new JLabel(imgIco);
    imgLbl.setPreferredSize(new Dimension(500,500));
    JPanel p1 = new JPanel();
    p1.add(pb1);
    setLayout(new GridLayout(1,1));
    add(imgLbl);
    add(p1);
    public void salman()
              int i=0;
              while(i<=100)
                   try
                        pb1.setValue(i);
                        pb1.setForeground(Color.lightGray);
                        pb1.setBackground(Color.blue);
                        pb1.setBorderPainted(true);
                        pb1.setStringPainted(true);
                        Thread.sleep(55);
                   catch(Exception e)
                        System.out.println("Exception Occured!!!");
                   i++;     
    public static void main(String[] args)
    JFrame f = new JFrame();
    test img = new test("pills.jpg");
    f.getContentPane().add(img);
    f.setSize(450,470);
    f.setVisible(true);
    img.salman();
    Thanks for you co-operation.
    Regards
    Salman Pirzada

    you use
    test img = new test("pills.jpg");where it finds pills.jpg????
    try something like this:
    String imageName = "pills.jpg";
    img = Toolkit.getDefaultToolkit().getImage(Test.class.getResource(imageName));And make sure, pills.jpg is in the same directory where Test class is

  • Closing a Jframe on button click

    Dear all,
    Please help me !!!
    I am having a jframe inside which I am having a jbutton. I want to close the jframe on that jbutton click.
    rock

    import javax.swing.JFrame;
    import javax.swing.JButton;
    import javax.swing.JTextField;
    public class Check extends JFrame {
         private javax.swing.JPanel jContentPane = null;
         private JButton jButton = null;
         private JTextField jTextField = null;
         private JButton getJButton() {
              if (jButton == null) {
                   jButton = new JButton();
                   jButton.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent e) {                                                          Check pop = new Check();
                               pop.dispose();  // here I want this frame should be close on clicking this button
              return jButton;
         private JTextField getJTextField() {
              if (jTextField == null) {
                   jTextField = new JTextField();
              return jTextField;
           public static void main(String[] args) {
              Check c = new Check();
         public Check() {
              super();
              initialize();
         private void initialize() {
              this.setSize(300,200);
              this.setContentPane(getJContentPane());
              this.setTitle("JFrame");
              this.setVisible(true);
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(new java.awt.BorderLayout());
                   jContentPane.add(getJButton(), java.awt.BorderLayout.EAST);
                   jContentPane.add(getJTextField(), java.awt.BorderLayout.NORTH);
              return jContentPane;
    }THis is my code I use dispose but it is not working

  • How to make a button click make text appear elsewhere on the screen

    I have a map of the US and  each state has a rollover that changes the color of the state...what i  am trying to figure out is how to click on the state and have text  appear to the side of the US map and have that text stay up until the user clicks on another state. Any help will be greatly appreciated. Thanks

    Good... keep working at it... I was already preparing the following for you, but if you pursue your own solution you will learn more and become more comfortable with working with Flash.
    If you want to look at what I was going to offer to possibly streamline what you end up with, or just have trouble, here it is...
    Select one of your states and give it an instance name in the properties panel... let's say you pick Utah and you name the instance "utah"  For example sake, let's say you also do the same for Ohio (naming it "ohio").
    Create a dynamic textfield where you want the text to be displayed and assign it an instance name, let's say you name it... "stateInfo"
    Create a new layer for actionscript so that you can assign some code for teh states.  In that layer, in the frame where the states are, select the empty keyframe, open the Actions panel, and place all of the following code there...
    var utahInfo = "Whatever text you want to display when you click Utah";
    var ohioInfo = "Whatever text you want to display when you click Ohio";
    utah.addEventListener(MouseEvent.CLICK, showInfo); // assigns a listener to the button
    ohio.addEventListener(MouseEvent.CLICK, showInfo);
    // for the above you will do the same for the rest of the state buttons... they can all share the following event handler function because it uses their names to identify the text variable that will be assigned to the textfield
    function showInfo(evt:MouseEvent):void {
         stateInfo.text = this[evt.currentTarget.name+"Info"];

  • JSON content - click to show another symbol on the stage

    Hi,
    Thanks to Zaxist I have a working code like the one below:
    $.getJSON("content.json",
              function(data){
                        for(var i=0; i<data.length; i++){
                        var s = sym.createChildSymbol("template","content");
                        s.$("title").html(data[i].title);
                        s.$("description").html(data[i].description);
                        s.$("seira").html(data[i].seira);
                        s.$("imageholder").css({"background-image":"url('"+data[i]. image+"')"});
                        s.$("imageholder").data('Large', data[i].largeimage);
                        s.$("imageholder").click("click", function(e){
                                                                sym.getComposition().getStage().$("finte").css({"background-image":"url("+$(this).data('L arge')+")"});
    Now, I am trying on the click function to show specific symbol on the stage, for example when click on the first item the symbol red will appear, if cliked the second item the (previous symbols that was appeared will be hided) and the new symbol blue will appear. An so on with all the other ellements that JSON files has.
    I tried this on the code, but nothing:
    $.getJSON("content.json",
              function(data){
                        for(var i=0; i<data.length; i++){
                        var s = sym.createChildSymbol("template","content");
                        s.$("title").html(data[i].title);
                        s.$("description").html(data[i].description);
                        s.$("seira").html(data[i].seira);
                        s.$("imageholder").css({"background-image":"url('"+data[i]. image+"')"});
                        s.$("imageholder").data('Large', data[i].largeimage);
                        s.$("imageholder").click("click", function(e){
                                                                sym.getComposition().getStage().$("finte").css({"background-image":"url("+$(this).data('L arge')+")"});
                                                                if (data[i]=3) {
                                                                                                                                                                                                                                                                sym.getComposition().getStage().$("red").show();
                                                                else {
                                                                sym.getComposition().getStage().$("red").hide();
                                                                if (data[i]=5) {
                                                                                                                                                                                                                                                                                                                             sym.getComposition().getStage().$("blue").show();
                                                                else {
                                                                sym.getComposition().getStage().$("blue").hide();
    Could you help me?
    Thanks in advanced!

    Zaxist please I need your help again.
    I have this:
    $.getJSON("images1.json",
              function(data){
                        for(var i=0; i<data.length; i++){
                        var s = sym.getSymbol("base").createChildSymbol("template", "content");
                        s.element.attr('id', 'basara'+i)
                                            s.getSymbolElement().css({"background-size":"contain",
                                               "float": "left",
    "margin": "100 125px 125px 100",
    "clearboth":"{ clear: both; }"
                        s.$("description").html(data[i].description);
                        s.$("code").html(data[i].code);
                        s.$("imageholder").css({"background-image":"url('"+data[i]. image+"')",
                                                                                                                                                                     "background-size":"cover"
                        s.$("imageholder").data('myIndex', i);
                                                                          s.$("imageholder").data('Large', data[i].image);
                         s.$("imageholder").click("click", function(e){
                                                                     if ($(this).data("myIndex") == 0){
    sym.getComposition().getStage().getSymbol('holders').$("holder1").css({"background-image": "url("+$(this).data('Large')+")"});
                            else if ($(this).data("myIndex") == 1) {
    sym.getComposition().getStage().getSymbol('holders').$("holder1").css({"background-image": "url("+$(this).data('Large')+")"});
                            else if ($(this).data("myIndex") == 2) {
    sym.getComposition().getStage().getSymbol('holders').$("holder1").css({"background-image": "url("+$(this).data('Large')+")"});
    $.getJSON("images2.json",
              function(data){
                        for(var i=0; i<data.length; i++){
                       var s = sym.getSymbol("podia").createChildSymbol("template", "contentpodia");
                                           s.getSymbolElement().css({"background-size":"contain",
                                               "float": "left"});
                        s.$("description").html(data[i].description);
                        s.$("code").html(data[i].code);
                        s.$("imageholder").css({"background-image":"url('"+data[i]. image+"')",
                                                                                                                                                                     "background-size":"cover"
                        s.$("imageholder").data('myIndex', i);
                                                                          s.$("imageholder").data('Large', data[i].image);
                         s.$("imageholder").click("click", function(e){
                                                                     if ($(this).data("myIndex") == 0){
    sym.getComposition().getStage().getSymbol('holders').$("holder2").css({"background-image": "url("+$(this).data('Large')+")"});
                            else if ($(this).data("myIndex") == 1) {
    sym.getComposition().getStage().getSymbol('holders').$("holder2").css({"background-image": "url("+$(this).data('Large')+")"});
                            else if ($(this).data("myIndex") == 2) {
    sym.getComposition().getStage().getSymbol('holders').$("holder2").css({"background-image": "url("+$(this).data('Large')+")"});
    I want to import symbol podia inside to base to handle it by content2.
    I am writing this:
    var basewithpodia = sym.getSymbol("base").createChildSymbol("podia", "content2");
    it places the symbol inside, without the data of the JSON file.
    How can I make it to work?

  • Make a button hide and show an image

    I want a button to hide and then show an image, basically an on/off switch.  I tried accomplishing this using multipl slides that jump around but even after removing all transitions, you can still tell that the slides are changing instead of just the image appearing and disappearing.  I have seen some posts about advanced actions but it's reading clear as mud.

    Christina,
    If you want a toggle button, that can be done with advanced actions. What did you read already? And which version of Captivate are you using?
    The idea is that:
    You create the image, but set its visibility unchecked in the Properties panel
    You create a user variable, will label it v_visib that has a start value of 0, will be set to 1 when the image is visible
    You create a conditional advanced action, that will check the value of v_visib:
    IF v_visib is equal to 0
        Show Image
         Assign v_visib with 1
    ELSE
        Hide Image
        Assign v_visib with 0
    I blogged several times about toggle buttons:
    http://lilybiri.posterous.com/toggle-shape-buttons      for Captivate 6 only
    http://lilybiri.posterous.com/toggle-button
    Lilybiri

  • Show only images in the selected folder

    Hi All,
    It would be nice if I could show only the images in the selected folder without including images in subfolders. For example a check box next to the folder name could switch between "selected folder only" and "include subfolders" viewing modes.

    Un-check Menu/Library/Include Photos from Subitems.
    It is already there in V1.1.
    Don
    Don Ricklin, MacBook 1.83Ghz Duo 2 Core running 10.4.10 & Win XP, Pentax *ist D
    http://donricklin.blogspot.com/

  • When I send email and attach photos, those are been randomly resized, without asking and I can't resize them back to the original size on the screen and on the email, even if I select them and click on "LARGE SIZE" images on the right top box of the email

    By the way, I've tried to look for the Attachment Tamer box, between the Mail Prefferences but it doesn't even show me this option. So I can't do it.
    I'm using a MacPro.

    Marc Bublitz wrote:
    I thought that originally too, but that's all changed with the pool of apps that are out there now. So now what I'm trying to do is to prove that technology is progressing to the point where a tiny, handheld phone can produce images that are nearly as good as photos taken with much more expensive and bulky equipment. I've got my share of expensive bulky camera equipment, but I'm finding that I'm having much more enjoyment out of using my iPhone from initial capture, to editing, to publishing, and achieving results that are nearly as good.
    I do think you're working under a bit of a handicap. For example, lens quality. Here's an iPhone photo example of some wild turkeys in the neighborhood masked by flare that would be much better controlled on an SLR lens (click to enlarge - the flare is obvious, the turkeys are not):
    At the same time, working under a handicap can definitely spur creativity, similar to the oft-cited example of swapping out your zoom lens for a prime to force yourself to pay attention to composition.
    It's an interesting concept - I wish you luck!

  • When I want to download something like a picture I right click on it "save image as", the Download window appears and then everything freezes for about ten seconds untill the Downloads window closes.

    That happens with anything I try to download, not just images.

    That happens with anything I try to download, not just images.

  • Show image on the form Java WS gets image. Call this WS on button click

    Hi,
    Is there a way to show an image on the form. On the form I have along with the data I have a button that when clicked get and show the image itself on the form. I have a Java WebService that gets the image from the remote location. How can I make the button click event to call this Web Service and show the image on the form itself. Any help is appreciated.
    Thanks

    WHiteSox, are you on client/server or web version.
    which version of forms are you using.
    something i can think of is.
    during the click to call the webservice, copy the image to the local system.
    next step is, using READ_IMAGE_FILE built in which reads the image from the local file system and displayed on the forms image item.

  • I want to do banners ,how can we do  when click the same button (next button)  it must show differen

    i want to do banners ,how can we do  when click the same button (next button)  it must show different images . cam any one help

    Check out my blog with samples on Edgehero.
    http://www.edgehero.com/articles/interactivity

  • How do you fire a button click event on apex page from fancybox iframe that was created by page

    I am trying to fire off the button click event from fancybox iframe. The apex page has a button that launches a fancybox iframe which is loaded with an APEX form. On close of that fancy box, I am trying to fire a click event on the parent page which will refresh a div with html that is created with plsql. The button on the page works as expected when clicked from the page. It will show a debug alert message to prove it was called and then load the div with the correct data. I am unable to fire off this button click from the fancybox iframe when it closes.
    A couple of points:
    I using Plug-in: Execute PL/SQL Code and Return Content ("PLUGIN_MULEDEV.SERVER_REGION_REFRESH") to place the create fancybox statement. It is used to populate a div using plsql.
    The name of the button on the main page is P2020_REFRESH_SECTION_BUILDER_BTN.
    The click dynamic action on the button is calling the plugin to replace the html in the div.
    The data in the form in the fancybox is being saved to the database. On close of the fancybox box I want to refresh the div so the new record is included in the div html.
    Can anyone help. Here is the fancybox code:
      function customProcessOnReadyState4(){
        for (var i=0;i<11;i++){
          $( "#tabs"+i ).tabs();
          $("#createNewExerciseLink"+i).fancybox({
              ''width''         : ''60%'',
              ''height''        : ''70%'',
              ''autoScale''     : true,
              ''transitionIn''  : 200,
              ''transitionOut'' : 200,
              ''type''          : ''iframe'',
              ''onClosed''         : function() {
                                         window.parent.$(''#P2020_REFRESH_SECTION_BUILDER_BTN'').click();
    Here are the dynamic actions assigned to the button:
    5 - Execute JavaScript Code
    alert("Starting refresh");
    10 - Execute PL/SQL Code and Return Content [Plug-in]
    begin
      SCTUI.create_sct_tabs2(:P2020_CREATE_SECTION_LOV, '1');
    end;

    user setActionListener...
    <af:setActionListener from="#{bindings.XXX.inputValue" to="#{backingbean.variable}"
                  <af:inputText value="#{bindings.Email.inputValue}"
                                label="#{bindings.Email.hints.label}"
                                binding="#{backingBeanScope.backing_ShuttlePage.it2}"
                                id="it2">
                    <f:validator binding="#{bindings.Email.validator}"/>
                  </af:inputText>
                  <af:commandButton text="commandButton 2"
                                    binding="#{backingBeanScope.backing_ShuttlePage.cb2}"
                                    id="cb2" action="passing">
                    <af:setActionListener from="#{bindings.Email.inputValue}"
                                          to="#{processScope.detail}"/>
                  </af:commandButton>next jsf page:
                <af:outputText value="#{processScope.detail}"
                               binding="#{backingBeanScope.backing_ProcessScope.ot1}"
                               id="ot1"/>setPropertyListener also should work
    <af:setPropertyListener from="#{bindings.Email.inputValue}" to="#{processScope.detail}" type="action"/>

Maybe you are looking for

  • Abap+java stack, users not mapping to portal role.

    We have the ABAP+java add-on install. The UME is by default ABAP engine. From Portal: 1 I create a portal user, it ALWAYS creates ABAP user in ABAP stack of WAS. 2. I create a portal role, it creates a role in the Portal. 3. When I assign the user th

  • Charger connector play

    My DROID X has a little looseness in the micro USB connection next to the HDMI connector. I have always been careful not to put any strain on it. I note that the HDMI connection male plug fits up snug against the DROID providing its own strain relief

  • How to limit row number per group without change new page in crystal report

    Hi All Expert, Is there any way to limit row number per group without change new page in crystal report 2008. The reason i do that is due to customer using printer EPSON LQ 300 (dot matrix) always will print in landscape if detech my layout in landsc

  • Adobe X Pro editing/ typing in PDF document

    As I begin to edit a PDF document, while typing, the text or screen seems to refresh for long enough intervals (few seconds) that it is making it very difficult to work. Operating system is Windows XP SP2.

  • IdeaCentre B320 - Windows 8 64bit drivers for AMD radeon HD 7450 card

    I have upgraded my recently bought B320 all-in-one to Windows 8 and now have a problem with video card drivers for HD7450 graphics card. Default Win 8's driver (named something like Windows Radeon HD7400 series ) works just fine, but it have no OpenG