JLabel needs resizing in JDialog

I have a subclass of JDialog that shows messages to the user, kind of like JOptionPane, but with a bit more processing for my own purposes. I have a JLabel in the dialog that I set the message text on. The message is almost always HTML with some formatting, and frequently the text causes the size of the label to be higher than it was when laid out in NetBeans. If I just show the dialog that way, the label will adjust it's height but will push items below it (like my MMButtons) off the bottom of the dialog. The code calls pack() and validate() immediately before setVisible(true).
If I use a SwingWorker to schedule another pack() and validate() 500ms after showing the dialog, then that pack/validate cause the dialog to resize as it needs to.
Note: the text is set on the JLabel after the entire dialog has been created and layed out.
Question: how can I get the dialog to resize properly the first time it shows, so that there is not a delay before the full contents will show?
I'm using GroupLayout in my dialog. The layout code is shown below.
<pre>
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pnlButtons, javax.swing.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
.addComponent(lblMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
.addComponent(txtText, javax.swing.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE))
.addContainerGap())
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(lblMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pnlButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
</pre>

Why? Because the { code } tag was not documented in the help box on the right side, nor is there a button for it in the tool bar.
Anyway, here is the layout code again:
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(pnlButtons, javax.swing.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
          .addComponent(lblMessage, javax.swing.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
          .addComponent(txtText, javax.swing.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE))
        .addContainerGap())
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(lblMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(txtText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(pnlButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap())
    );

Similar Messages

  • Problem resizing the JDialog???

    hi,
    I have a JDialog to which I am adding a JTable and JButton to search.
    Based on search condition the table gets populated.
    Problem here is
    I give search condition 1 and puplate the table after that I resize the JDialog
    Now i again serach it.Now the JDialog's size goes to the previous thing it does'nt take the resized size.
    in the end of my seacrh action listner I am doing
    this.pack();
    this.setVisible(true);
    this.setResizable(true);While running in debug mode I noticed once it execute this.pack();
    the resizing is gone.but if I remove this.pack() the JTable is not shown...
    Any idea about this problem??
    thnx
    neel

    The pack() method lays it out according to the preferred size of the content.
    You need to either only pack it when you first create it, or note the actual size before packing and if it's non-null and non-zero then restore it after packing.

  • Detecting Resizing of JDialog

    Hey all,
    I have a JComponent added to a JDialog that is the size of the JDialog in question. When I resize my JDialog by dragging around the edge of the JDialog window, I want my JComponent to be resized DURING the resizing of the JDialog. Currently, it seems to be that when the resizing is done, my Layout Manager(FlowLayout by default right?) resizes my JComponent for me AFTER the event. Is there anyway to resize the component DURING the resizing of the JDialog? Resize Event listeners under the ComponentListener(componentResized) does not work, it only detects resizing at the end of the event, like I said, I am looking for something that works DURING the event!
    Any and all help is appreciated!
    Rob

    I tried to do this before and I would recommend against it. The resize events are posted to the end of the thread queue. I think in order to do this you would have to muck around with the base class. Ugly stuff. If possible I would try to rework the design so you don't need to do this.

  • Dynamic resizing in JDialog using setSize not working properly on solaris

    can anyone help..
    Dynamic resizing in JDialog using setSize is not working properly on solaris, its work fine on windows.
    i have set Jdialog size to setSize(768,364),
    when i dynamically resizing it to setSize(768,575); it doesn't get change but when i move dialog using mouse it gets refreshed.
    this problem is only happening on solaris not on windows.

    Hi,
    It's only an approach but try a call of validate() or repaint() after re-setting the size of your dialog.
    Cheers, Mathias

  • Image NOT displaying in JLabel in Jpanle in JDialog

    Hi I have been facing this problem all day long, and cant find the right thing to do, already red many posts on this but got stuck.
    In my client application I`ve got a JDialog tha is intended to show data from users and a picture of them. the dataBase issues are (I think) solved but as i am beginning with this that isnt tested yet, right now i am dealing with showing an image in a Jpanel, i have seen many posts adding a Jlabel to the Jpanel but this code doesn`t show the image on my project.
    some code:
    private void jTBtnCambiarLogoMouseReleased(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
             *aca hay que agregar un formulario de carga de imagen.
            Debug.print("miPerfil.jTBtnCambiarLogoMouseReleased(java.awt.event.MouseEvent evt)");
            FileDialog loadFotoDiag = new FileDialog(this,"Escoja una imagen en su sistema de archivos.",FileDialog.LOAD) ;
            loadFotoDiag.setVisible(true);
            try {
                Image foto = Archivos.getImageFromFile(loadFotoDiag.getDirectory()+loadFotoDiag.getFile());
                if (foto != null){
                    JPfoto.setBackground(Color.green);
                    JPfoto.add(new JLabel(new ImageIcon("/root/Desktop/UTN/Cliente/pesado/NetBeans_Projects/Tenasiuspesado1/java_logo.gif")));
                    JPfoto.paintComponents(JPfoto.getComponent(0).getGraphics());
                    //JPfoto.revalidate();
                }else{
            } catch (Exception e) {
                System.err.println("miPerfil.jTBtnCambiarLogoMouseReleased(java.awt.event.MouseEvent evt) Exception Inesperada!");
                System.err.println(e.getMessage());
            } I can see than even without using .revalidate() the backgroundcolor changes from red (as set in the NetBeans IDE) to green. but cant show the image.
    Pleace I someone can throw a hint I would appreciate it.

    SOLVED! :) I steel don`t know how to make the previous code work (and everybody does this that way :S) but in the example provided by the tutorial that camickr recommended me i saw that it wasn't necessary to use JPanel, with JLabel is fairly enough.
    CODE:
        private void jTBtnCambiarLogoMouseReleased(java.awt.event.MouseEvent evt) {
            // TODO add your handling code here:
             *aca hay que agregar un formulario de carga de imagen.
            Debug.print("miPerfil.jTBtnCambiarLogoMouseReleased(java.awt.event.MouseEvent evt)");
            FileDialog loadFotoDiag = new FileDialog(this,"Escoja una imagen en su sistema de archivos.",FileDialog.LOAD) ;
            loadFotoDiag.setVisible(true);
            try {
                Image foto = Archivos.getImageFromFile(loadFotoDiag.getDirectory()+loadFotoDiag.getFile());
                if (foto != null){
                    jLfoto.setIcon(new ImageIcon(Imagen.getScaledImage(foto,149,102)));
                 }else{
                    System.err.println("miPerfil.jTBtnCambiarLogoMouseReleased(java.awt.event.MouseEvent evt) :");
                    System.err.println("    Image foto = Archivos.getImageFromFile(loadFotoDiag.getDirectory()+loadFotoDiag.getFile());");
                    System.err.println("    Devuelve null");
            } catch (Exception e) {
                System.err.println("miPerfil.jTBtnCambiarLogoMouseReleased(java.awt.event.MouseEvent evt) Exception Inesperada!");
                System.err.println(e.getMessage());
            }As u see I stoled a method from the example and inserted it into my Util.Imagen class:
          public static Image getScaledImage(Image srcImg, int w, int h){
            BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = resizedImg.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2.drawImage(srcImg, 0, 0, w, h, null);
            g2.dispose();
            return resizedImg;
        }In order to resize the images.

  • 1st webpage in DW in 10+ yrs (need resizing help)

    Hello guys, I just did a intro page and I have it up on my test site http://webuildcmssites.com/compassion/Intro.htm everything looks great and full screen on most browsers I test thus far, but if I take the browser and start to resize the window the images move.
    1. background was added via properties/html/page properties/background image
    2. I 1st tried adding my images via Ap Div but I didn't like that much so I'm using tables
    3. when you resize the window the images are moving and I would like it to be fluid or whichever you guys think would be best
    If you don't want to go to the website here's the code
    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Welcome to Compassion Ministries</title>
    <style type="text/css">
    body {
              background-image: url(Images/cmbackground.jpg);
              background-repeat: no-repeat;
              margin: auto;
              background-position: center center;
              height: auto;
              width: auto;
              background-attachment: scroll;
    #apDiv1 {
              position:absolute;
              width:200px;
              height:115px;
              z-index:1;
              left: 756px;
              top: 62px;
    #apDiv2 {
              position:absolute;
              width:249px;
              height:181px;
              z-index:1;
              left: -495px;
              top: -981px;
    #apDiv3 {
              position:absolute;
              width:200px;
              height:129px;
              z-index:2;
              left: 753px;
              top: 81px;
    #apDiv4 {
              position:absolute;
              width:200px;
              height:129px;
              z-index:3;
              left: 492px;
              top: 80px;
    #apDiv5 {
              position:absolute;
              width:200px;
              height:129px;
              z-index:4;
              left: 227px;
              top: 81px;
    #apDiv6 {
              position: absolute;
              width: 721px;
              height: 58px;
              z-index: 5;
              left: 226px;
              top: 304px;
    #apDiv7 {
              position:absolute;
              width:200px;
              height:115px;
              z-index:6;
              left: 425px;
              top: 466px;
    #apDiv8 {
              position:absolute;
              width:116px;
              height:41px;
              z-index:1;
    #apDiv9 {
              position:absolute;
              width:120px;
              height:42px;
              z-index:7;
              left: 750px;
              top: 321px;
    #apDiv10 {
              position:absolute;
              width:120px;
              height:40px;
              z-index:8;
              left: 493px;
              top: 322px;
    </style>
    <script type="text/javascript">
    function MM_preloadImages() { //v3.0
      var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
        var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
        if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
    function MM_swapImgRestore() { //v3.0
      var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
    function MM_findObj(n, d) { //v4.01
      var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
      if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
      for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
      if(!x && d.getElementById) x=d.getElementById(n); return x;
    function MM_swapImage() { //v3.0
      var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
       if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
    </script>
    </head>
    <body onLoad="MM_preloadImages('Images/boarderchester.png','Images/borderoak.png','Images/borde rcomp.png')">
    <p> </p>
    <table width="746" height="159" border="0" align="center" cellpadding="2">
    <tr>
      <td width="249" height="155" align="center"> </td>
    </tr>
    </table>
    <p> </p>
    <table width="746" height="147" border="0" align="center" cellpadding="2">
      <tr>
        <td width="253" height="143" align="left"><img src="Images/bwcompborder.jpg" name="oakgray" width="198" height="130" id="oakgray"></td>
        <td width="249" align="left"><img src="Images/bwoakborder.jpg" name="phillygray" width="185" height="130" id="phillygray"></td>
        <td width="214"><img src="Images/bwchesterboarder.jpg" name="chestergray" width="198" height="130" id="chestergray"></td>
      </tr>
    </table>
    <p> </p>
    <p> </p>
    <table width="746" height="147" border="0" align="center" cellpadding="2">
    <tr>
      <td width="253" height="143" align="left"><table width="719" height="56" border="0" cellpadding="1">
        <tr>
          <td width="258" align="left"><a href="http://www.philly.compassion-ministries.com/"><img src="Images/visitphilly.png" name="visitphilly" width="119" height="40" id="visitphilly" onMouseOver="MM_swapImage('phillygray','','Images/bordercomp.png',1)" onMouseOut="MM_swapImgRestore()"></a></td>
          <td width="260"><a href="http://www.oakeola.compassion-ministries.com/"><img src="Images/visitoak.png" name="visitoak" width="119" height="40" id="visitoak" onMouseOver="MM_swapImage('oakgray','','Images/borderoak.png',1)" onMouseOut="MM_swapImgRestore()"></a></td>
          <td width="187"><a href="http://www.chester.compassion-ministries.com/"><img src="Images/visitchester.png" name="visitchester" width="119" height="40" id="visitchester" onMouseOver="MM_swapImage('chestergray','','Images/boarderchester.png',1)" onMouseOut="MM_swapImgRestore()"></a></td>
        </tr>
      </table></td>
    </tr>
    </table>
    <p> </p>
    <p> </p>
    <div id="apDiv6"></div>
    </body>
    </html>

    LONG TERM SOLUTION:  Don't use positioning in primary layouts.  It doesn't work well, here's why:  http://www.apptools.com/examples/pagelayout101.php
    Learn to use CSS margins, padding and floats to align elements on screen.
    http://alt-web.com/DEMOS/3-CSS-boxes.shtml
    Finally, don't use tables for layouts.  You don't need them.  Tables are for tabular data only.  Learn to use CSS layouts instead.  You'll find a whole bunch of pre-built CSS layouts in Dreamweaver.
    Got to File | New > Blank page > HTML > Layouts. 
    Select a 2 or 3-col layout.
    Hit Create button
    Nancy O.

  • Smooth animated moving/resizing of JDialog

    Greetings all,
    I'm not sure if this belongs here or in the Java 2D subforum, but whatever. I'm working on a Swing desktop application whose main frame is laid out in a 3x3 GridLayout. Some of the panels in this grid have JLists with very long entries in them, and our users frequently complain that these panels are too small, so we'd like to implement the ability for them to "pop out" into bigger panels temporarily. We did this by simply removing the panel from the grid and dropping it in a JDialog of suitable size.
    Now, it may seem pedantic, but I'm interested in making this as pretty as technologically possible. My approach thus far has been to make the JDialog undecorated and initially position it directly where the original panel was, then animate it growing by having a Timer call SetBounds with increasing parameters until the desired maximum size is reached. This looks pretty nice, but it's kind of jaggy and flickery. Is there a better way of doing this that takes advantage of Java's graphics capabilities?
    Thanks!

    We did this by simply removing the panel from the grid and dropping it in a JDialog of suitable size.It would probably be better to simply grab the model from the list and use it to create a new JList that you add to the dialog, that way you don't need to worry about replacing the list after the dialog is closed, because a component can only have a single parent.
    then animate it growing by having a Timer call SetBounds with increasing parameters until the desired maximum size is reached. This looks pretty nice, but it's kind of jaggy and flickerySounds reasonable to me, I don't see why it would be jaggy and flickery.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • Can I resize undecorated JDialog with mouse?

    Hi all,
    I use a undecorated JDialog as a message panel in my application, but I can't resize it with my mouse. Can this be achieved?

    It's not like Photoshop resizing at all - Flash is a vector
    engine, not a
    bitmap engine. Depending on the image and how much you are
    scaling it, it
    can look OK scaled, but it'll never be as good as in Pshop.
    Dave -
    www.offroadfire.com
    Head Developer
    http://www.blurredistinction.com
    Adobe Community Expert
    http://www.adobe.com/communities/experts/

  • Resizing a JDialog

    Hello,
    I was trying to disable the resizing option for a JDialog. I've set the
    initial size of the dialog by using myDialog.setSize(...) but I'm still able
    to resize the dialog once it pops up. I want to restrict that. It should be
    of fixed size and the user should not be able to modify it.
    Could anybody please tell me how do I do it. I heard there is a function
    called resizable(boolean false)..!!
    Thanks a lot.
    -Amitabh

    Do you know a way to disable the resizing feature while diplaying the ICONs? I've implemented a ComponentAdapter but there is nothing I can do from the componentResized() method! The resizing seems to happen before the event is passed to me! How can I do this!
    Thanks.

  • Explain plan needs resize columns best-fit

    Is there an easy way to resize columns in the explain plan grid? They are difficult to resize if the values in them are long, especially the access and filter columns at the end.

    There is only one way to resize these right now (and thats the one you are using).

  • Help needed: Resizing a whole video track

    Hello everyone
    For starters, forgive my poor english syntaxis
    Recently i have filmed a concert with several Gopro cameras (in 1280x960) and a 7D (in 1920x1080).
    Now i want to edit all this in Premiere, with a final format of 1280x720. I'll have bits of gopro film and bits of 7d film.
    What i want to do is have, for example, a Gopro track with my gopro bits and a 7D track with all my 7D bits. My gopro bits fit perfectly in the comp, since they have the good width (it crops the height, but that's what i want), but the 7D clips are too big (1920x1080 instead of 1280x720). I could resize each one of my clips in the properties, but since they are WAY too many of them, i would like to scale down the whole 7D track. Is there a way to do that?
    Thank you!
    Ricardo.

    I thought about editing the whole 7D track in a dedicated sequence, but it would mean jumping back and forth the main sequence and this one to edit the movie... Not very pratical.
    But the 'scale to frame size' is almost perfect. Should have thought about that. Thanks!
    Anyway, there should be a global track effects/transform control, not only for size but also color correction, rotation, position, etc without having to precomp everything. Don't you think?

  • Dynamic resizing in JDialog using setSize not working properly

    Hi,
    I have a dialog in which i have two radio buttons.
    As i click on other radio button the size of the dialog should change.
    I did so using setSize.
    As i change the size from smaller dialog to a bigger one then newly created portion is not painted properly. Although the size is increased but the painting of the new portion is not done fine.
    Any ideas?
    Is this is a Java bug?
    Here is the code snippet:
    public MyDialog() {
         Container contentPane = this.getContentPane();
         JPanel radioPanel = new JPanel();
    ButtonGroup radioGroup = new ButtonGroup();
    mInstancesButton = new JRadioButton("Instances");
    mActivitiesButton = new JRadioButton("Activities");
    mInstancesButton.setBounds(100,0,100,25);
    mActivitiesButton.setBounds(200,0,100,25);
    mInstancesButton.addItemListener(this);
    mActivitiesButton.addItemListener(this);
    radioGroup.add(mInstancesButton);
    radioGroup.add(mActivitiesButton);
    radioPanel.setLayout(null);
    radioPanel.add(mInstancesButton);
    radioPanel.add(mActivitiesButton);
    radioGroup.setSelected(mInstancesButton.getModel(), true);
         contentPane.add(radioPanel);
         this.setSize(600,300);
    public void itemStateChanged(ItemEvent ie) {
    Container contentPane = this.getContentPane();
    if(ie.getSource().equals(mInstancesButton) && ie.getStateChange() == ie.SELECTED) {
    this.setSize(600,300);
    else if(ie.getSource().equals(mActivitiesButton) && ie.getStateChange() == ie.SELECTED) {
    this.setSize(600, 500);

    Hi,
    It's only an approach but try a call of validate() or repaint() after re-setting the size of your dialog.
    Cheers, Mathias

  • Win98 need to resize applet viewer to see forms client

    Is there any work around that will aliviate the problem of needing resize the applet viewr (JInitiator) manually to see the java applet?
    This is consistent bug and it seems to appear on all of our Win98 clients (WinNT works fine) in both IE 5.0 and Netscape 4.0

    There is a work around for this problem by using the resize_window(FORMS_MDI_WINDOW, height, width) you can force the refresh of the applet window. The ability to use the resize_window on the MDI window web deployed was supposedly just made available with patch 5. I had the same problem and this fixed it for me.

  • IMAGE NOT DISPLAYED OVER JButton ON JDialog

    Hi,
    I am trying to display an image over a JButton inside a JDialog(pops up on button click from an applet). But it is invisible. But I am sure that it is drawn on the ContentPane since when i click partially/half at the position
    of the JButton I could see the JButton with the image. Actualy I am resizing the JDialog since I have two buttons, one to minimise and the other two maximise the size of the JDailog.
    All the buttons are in place but not visible neither at the first place nor when the JDialog is resized.
    The code is as follows:
    package com.dataworld.gis;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import javax.swing.*;
    public class PrintThisPolygon extends JDialog {
         protected Image image;
         protected JButton print;
         protected JButton resize;
         protected JButton desize;
         private int pX=0, pY=0, pWidth=0, pHeight=0;
         public PrintThisPolygon(JFrame parent, Viewer viewer) {
              super(parent, "Print Polygon", true);
              this.setModal(false);
              getContentPane().setLayout(null);
              image = this.viewer.getScreenBuffer();
              pane = new Panel();
              print = new JButton("print", new ImageIcon("images/print.gif"));
              print.setBounds(0,5,50,20);
              print.setEnabled(true);
              print.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        print();
              resize = new JButton("+", new ImageIcon("images/print.gif"));
              resize.setBounds(55,5,50, 20);
              resize.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        resizePlus();
              desize = new JButton("-", new ImageIcon("images/print.gif"));
              desize.setBounds(105,5,50, 20);
              desize.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        resizeMinus();
              getContentPane().add(print);
              getContentPane().add(resize);
              getContentPane().add(desize);
    public String getAppletInfo() {
         return "Identify Polygon\n"
    public void paint(Graphics g){
         System.out.println("Paint : pX " + pX + " pY :" + pY);
         g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
    protected void print() {
         ImagePrint sp = new ImagePrint(this.viewer);
    public void resizeMinus(){
         repaint();
    public void resizePlus(){
         repaint();
    Can anybody has any clue. Can anybody help me out.
    Thanx

    I added resize code for those buttons and ended up with repaint problems too. When you manually resized the window everything was fine again. After a bit of digging around I found you need to call validate on the dialog and then things work.
    IL,
    There is the new scaling version of the code I modified above:package forum.com.dataworld.gis;
    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.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class PanelPaintFrame extends JFrame {
         public static void main(String[] args) {
              PanelPaintFrame frame = new PanelPaintFrame ();
              frame.setVisible (true);
         public PanelPaintFrame ()  {
              setBounds (100, 100, 600, 600);
              setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              JButton showPrintDialogButton = new JButton ("Show Print Dialog...");
              JPanel buttonPanel = new JPanel ();
              buttonPanel.add (showPrintDialogButton);
              getContentPane ().add (buttonPanel);
              showPrintDialogButton.addActionListener (new ActionListener ()  {
                   public void actionPerformed (ActionEvent e)  {
                        PrintThisPolygon printDialog = new PrintThisPolygon (PanelPaintFrame.this);
                        printDialog.show();
              pack ();
         public class PrintThisPolygon extends JDialog {
              protected ImageIcon myOrigonalImage = null;
              protected Image image;
              protected JButton print;
              protected JButton resize;
              protected JButton desize;
              private int pX=0, pY=0, pWidth=0, pHeight=0;
              JPanel pane = null;
              public PrintThisPolygon(JFrame parent/*, Viewer viewer*/) {
                   super(parent, "Print Polygon", true);
    //               this.setModal(false);
                   getContentPane().setLayout(null);
                   //  Substitute my own image
                   myOrigonalImage = new ImageIcon (PrintThisPolygon.class.getResource ("images/MyCoolImage.jpg"));
                   //  Start off full size
                   pWidth = myOrigonalImage.getIconWidth();
                   pHeight = myOrigonalImage.getIconHeight();
                   image = myOrigonalImage.getImage ().getScaledInstance(pWidth, pHeight, Image.SCALE_DEFAULT);
    //               image = this.viewer.getScreenBuffer();
    //               pane = new Panel();
                   //  Create a JPanel to draw the image
                   pane = new JPanel(){
                        protected void paintComponent(Graphics g)  {
                             System.out.println("Paint : pX " + pX + " pY :" + pY);
                             g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
                   pane.setBounds (0, 0, pWidth, pHeight);
                   //  Load the button image using a URL
                   print = new JButton("print", new ImageIcon(PrintThisPolygon.class.getResource ("images/print.gif")));
    //               print = new JButton("print", new ImageIcon("images/print.gif"));
                   print.setBounds(0,5,55,20);
                   print.setEnabled(true);
                   print.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             print();
                   resize = new JButton("+", new ImageIcon("images/print.gif"));
                   resize.setBounds(55,5,50, 20);
                   resize.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             resizePlus();
                   desize = new JButton("-", new ImageIcon("images/print.gif"));
                   desize.setBounds(105,5,50, 20);
                   desize.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             resizeMinus();
                   //  Setup a transparent glass panel with no layout manager
                   JPanel glassPanel = new JPanel ();
                   glassPanel.setLayout (null);
                   glassPanel.setOpaque (false);
                   //  Add the image panel to the dialog
                   getContentPane().add(pane);
                   //  Add the buttons to the glass panel
                   glassPanel.add(print);
                   glassPanel.add(resize);
                   glassPanel.add(desize);
                   //  Set our created panel as the glass panel and turn it on
                   setGlassPane (glassPanel);
                   glassPanel.setVisible (true);
                   setBounds (100, 100, pWidth, pHeight);
    //               setBounds (100, 100, 500, 300);
              public String getAppletInfo() {
                   return "Identify Polygon\n";
    //          public void paint(Graphics g){
    //          protected void paintComponent(Graphics g)  {
    //               System.out.println("Paint : pX " + pX + " pY :" + pY);
    //               g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
              protected void print() {
                   //  Pretend to print
    //               ImagePrint sp = new ImagePrint(this.viewer);
                   System.out.println ("Print view...");
              public void resizeMinus(){
                   //  Scale the image down 10%
                   int scaledWidth = pWidth - (int)(pWidth * 0.1);
                   int scaledHeight = pHeight - (int)(pHeight * 0.1);
                   scaleImage (scaledWidth, scaledHeight);
              public void resizePlus(){
                   //  Scale the image up 10%
                   int scaledWidth = pWidth + (int)(pWidth * 0.1);
                   int scaledHeight = pHeight + (int)(pHeight * 0.1);
                   scaleImage (scaledWidth, scaledHeight);
              private void scaleImage (int scaledWidth, int scaledHeight)  {
                   //  Create a new icon for drawing and retrieve its actuall size
                   image = myOrigonalImage.getImage ().getScaledInstance (scaledWidth, scaledHeight, Image.SCALE_DEFAULT);
                   pWidth = scaledWidth;
                   pHeight = scaledHeight;
                   //  Resize
                   setSize (pWidth, pHeight);
                   pane.setSize (pWidth, pHeight);
                   validate();
    }

  • Cannot display JLabel text in JTable

    Hi, This is a simple but frustrating little problem
    I am having trouble displaying the label text in a column of a JTable.
    I have hacked up a copy of TableDialogEditDemo.java from the tutorials
    on using JTables. This uses a renderer and editor models to deal with a
    column of colors.
    I have changed it to use JLabels instead. What want is for the label
    text to appear and when the user selects the cell be allowed to launch
    a dialog box (such as the demo program does with colorchooser).
    The dialog launching funcionalty works fine but the label text does not display.
    I end up with the column of JLabels as blank, even though the values
    are properly set. It seems like the TableCellRenderer doesn't display the
    controls text.
    I've spent the better part of two work days trying to get this one to work.
    Compiling and just running the code (without any interaction with the table)
    shows the problem. The second column of items will be blank instead of
    cells with text.
    Help!
    Thanks!
    /Steve McCauley
    Sanera Systems
    [email protected]
    Here is the code:
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.JLabel;
    import javax.swing.JDialog;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JColorChooser;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.JScrollPane;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import java.awt.*;
    import java.awt.event.*;
    * This is like TableEditDemo, except that it substitutes a
    * Favorite Color column for the Last Name column and specifies
    * a custom cell renderer and editor for the color data.
    public class TableDialogEditDemo extends JFrame {
    private boolean DEBUG = false;
    public TableDialogEditDemo() {
    super("TableDialogEditDemo");
    MyTableModel myModel = new MyTableModel();
    JTable table = new JTable(myModel);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Set up renderer and editor for the Favorite Color column.
    setUpColorRenderer(table);
    setUpColorEditor(table);
    //Set up real input validation for integer data.
    setUpIntegerEditor(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class ColorRenderer extends JLabel
    implements TableCellRenderer {
    Border unselectedBorder = null;
    Border selectedBorder = null;
    boolean isBordered = true;
    public ColorRenderer(boolean isBordered) {
    super();
    this.isBordered = isBordered;
    // setOpaque(true); //MUST do this for background to show up.
    public Component getTableCellRendererComponent(
    JTable table, Object color,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    // setBackground((Color)color);
    setForeground(Color.black);
    setBackground(Color.white);
    System.out.println(" Label: " + ((JLabel)color).getText());
    if (isBordered) {
    if (isSelected) {
    if (selectedBorder == null) {
    selectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getSelectionBackground());
    setBorder(selectedBorder);
    } else {
    if (unselectedBorder == null) {
    unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5,
    table.getBackground());
    setBorder(unselectedBorder);
    return this;
    private void setUpColorRenderer(JTable table) {
    table.setDefaultRenderer(JLabel.class,
    new ColorRenderer(true));
    //Set up the editor for the Color cells.
    private void setUpColorEditor(JTable table) {
    //First, set up the button that brings up the dialog.
    final JButton button = new JButton("") {
    public void setText(String s) {
    //Button never shows text -- only color.
    button.setBackground(Color.white);
    button.setBorderPainted(false);
    button.setMargin(new Insets(0,0,0,0));
    //Now create an editor to encapsulate the button, and
    //set it up as the editor for all Color cells.
    final ColorEditor colorEditor = new ColorEditor(button);
    table.setDefaultEditor(JLabel.class, colorEditor);
    //Set up the dialog that the button brings up.
    final JColorChooser colorChooser = new JColorChooser();
    ActionListener okListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    colorEditor.currentLabel = new JLabel("xxx");
    final JDialog dialog = JColorChooser.createDialog(button,
    "Pick a Color",
    true,
    colorChooser,
    okListener,
    null); //XXXDoublecheck this is OK
    //Here's the code that brings up the dialog.
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // button.setBackground(colorEditor.currentColor);
    // colorChooser.setColor(colorEditor.currentColor);
    //Without the following line, the dialog comes up
    //in the middle of the screen.
    //dialog.setLocationRelativeTo(button);
    dialog.show();
    * The editor button that brings up the dialog.
    * We extend DefaultCellEditor for convenience,
    * even though it mean we have to create a dummy
    * check box. Another approach would be to copy
    * the implementation of TableCellEditor methods
    * from the source code for DefaultCellEditor.
    class ColorEditor extends DefaultCellEditor {
    JLabel currentLabel = null;
    public ColorEditor(JButton b) {
    super(new JCheckBox()); //Unfortunately, the constructor
    //expects a check box, combo box,
    //or text field.
    editorComponent = b;
    setClickCountToStart(1); //This is usually 1 or 2.
    //Must do this so that editing stops when appropriate.
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fireEditingStopped();
    protected void fireEditingStopped() {
    super.fireEditingStopped();
    public Object getCellEditorValue() {
    return currentLabel;
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column) {
    ((JButton)editorComponent).setText(value.toString());
    currentLabel = (JLabel)value;
    return editorComponent;
    private void setUpIntegerEditor(JTable table) {
    //Set up the editor for the integer cells.
    final WholeNumberField integerField = new WholeNumberField(0, 5);
    integerField.setHorizontalAlignment(WholeNumberField.RIGHT);
    DefaultCellEditor integerEditor =
    new DefaultCellEditor(integerField) {
    //Override DefaultCellEditor's getCellEditorValue method
    //to return an Integer, not a String:
    public Object getCellEditorValue() {
    return new Integer(integerField.getValue());
    table.setDefaultEditor(Integer.class, integerEditor);
    class MyTableModel extends AbstractTableModel {
    final String[] columnNames = {"First Name",
    "Favorite Color",
    "Sport",
    "# of Years",
    "Vegetarian"};
    // final Object[][] data = {
    // {"Mary", new Color(153, 0, 153),
    // "Snowboarding", new Integer(5), new Boolean(false)},
    // {"Alison", new Color(51, 51, 153),
    // "Rowing", new Integer(3), new Boolean(true)},
    // {"Kathy", new Color(51, 102, 51),
    // "Chasing toddlers", new Integer(2), new Boolean(false)},
    // {"Mark", Color.blue,
    // "Speed reading", new Integer(20), new Boolean(true)},
    // {"Philip", Color.pink,
    // "Pool", new Integer(7), new Boolean(false)}
    final Object[][] data = {
    {"Mary", new JLabel("label-1"),
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", new JLabel("label-2"),
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", new JLabel("label-3"),
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", new JLabel("label-4"),
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Philip", new JLabel("label-5"),
    "Pool", new Integer(7), new Boolean(false)}
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 1) {
    return false;
    } else {
    return true;
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    public static void main(String[] args) {
    TableDialogEditDemo frame = new TableDialogEditDemo();
    frame.pack();
    frame.setVisible(true);

    You pretty much hit the nail on the head. Thank!
    Just didn't realize I needed to set the text of the component but with your
    tip and thinking about it, it makes sense.
    Actually I needed to use:
    setText(t_label.getText());
    Using toString got me: "java.swing......" (the components text representation)
    Thanks a bunch!
    /Steve

Maybe you are looking for

  • Bapi to load Purchase Info records.

    Hi all, can anyone suggest a bapi for loading purchase info records. thanks, deepthi.n

  • Why does Premiere Pro CS5 process audio source before exporting clip in AME CS5?

    Hello everyone, my first post here. I am currently trying out the trial CS5 Master Collection on my MacBook Pro. I've been using Premiere Pro CS5 to put together family videos. I select a certain portion of a sequence and queue it for export in Media

  • PO Upload and Download functionality

    Hello All, We are using SRM_SERVER 5, Version 4, SP 5 and have configured Standalone scenairo. Need to know if Download and Uplaod functionality is applicable for Purchase orders with in SRM version 4. These options are available with Contracts and B

  • Badi or exit in f-53.

    hello gurus i have  requirement that in f-53 in assigmnet we give the cheque number but there may happen duplicate entries so if there any badi which can sort this prob out. plz help.

  • Best way to transfer all data to a new model phone...

    Does anyone have a recommended and systematic way to transfer contacts, messages etc from one phone to another. eg I recently upgraded from a 6310 to an N95. I discovered that some of my contacts inj the 6310 were onn the SIM and some were on the pho