0

I've tried to test the technique presented in ->this answer <-.

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {

        BufferedImage img = new BufferedImage(plotPanel.getWidth(),plotPanel.getHeight(),BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2d = img.createGraphics();

        g2d.setColor(Color.red);        
        g2d.drawLine(0, 0, plotPanel.getWidth(), plotPanel.getHeight());

        JLabel picLabel = new JLabel(new ImageIcon( img ));

        plotPanel.add(picLabel);
        plotPanel.revalidate();
        plotPanel.repaint();
    }

Why do the plotPanel still remains intact?

UPDATE

Here is the well-anticipated SSCCE:

package javaapplication10;

import javax.swing.SwingUtilities;


public class JavaApplication10 {

    public static void main(String[] args) {
       SwingUtilities.invokeLater(new Runnable()
       {
               public void run()
               {
                   new NewJFrame().setVisible(true);
               }   
       });

    }
}

package javaapplication10;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JLabel;


public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        plotPanel = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        plotPanel.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout plotPanelLayout = new javax.swing.GroupLayout(plotPanel);
        plotPanel.setLayout(plotPanelLayout);
        plotPanelLayout.setHorizontalGroup(
            plotPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        plotPanelLayout.setVerticalGroup(
            plotPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 379, Short.MAX_VALUE)
        );

        jButton1.setText("jButton1");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        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(plotPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 758, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(plotPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(124, Short.MAX_VALUE))
        );

        plotPanel.getAccessibleContext().setAccessibleName("plotPanel");
        plotPanel.getAccessibleContext().setAccessibleDescription("");

        pack();
    }// </editor-fold>

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
           BufferedImage img = new BufferedImage(plotPanel.getWidth(),plotPanel.getHeight(),BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2d = img.createGraphics();

        g2d.setColor(Color.red);        
        g2d.drawLine(0, 0, plotPanel.getWidth(), plotPanel.getHeight());

        JLabel picLabel = new JLabel(new ImageIcon( img ));

        plotPanel.add(picLabel);
        plotPanel.revalidate();
        plotPanel.repaint();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }


        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    private javax.swing.JButton jButton1;
    private javax.swing.JPanel plotPanel;

}
Community
  • 1
  • 1
0x6B6F77616C74
  • 2,559
  • 7
  • 38
  • 65
  • 3
    Can you post an [SSCCE](http://sscce.org/)? – Reimeus May 08 '13 at 22:51
  • What layout manager does `plotPanel` use? – wchargin May 08 '13 at 22:58
  • @WChargin- GUI was auto-created with NetBeans WYSIWYG tool. – 0x6B6F77616C74 May 08 '13 at 23:28
  • @0x6B6F77616C74 It still uses a layout manager. Using a WYSIWYG tool **does not mean** that you don't need to know how to write layout code. Check out [How Layout Management Works](http://docs.oracle.com/javase/tutorial/uiswing/layout/howLayoutWorks.html) for information on layout managers. – wchargin May 08 '13 at 23:42
  • What's the size of `plotPane` when you create the image? Try either debugging the code or putting in `System.out.println` statements that dump the details to the console... – MadProgrammer May 08 '13 at 23:47

4 Answers4

2

Make sure to call revalidate after adding the JLabel picLabel:

plotPanel.revalidate();

Also, you're using GroupLayout which requires both horizontal and vertical sequential groups to be added to the layout for any new component to be visible. This layout is not the most easy to code by hand and produces a lot of boiler-plate code. Use the more conventional layout managers to become familiar with the code. See A Visual Guide to Layout Managers

Reimeus
  • 158,255
  • 15
  • 216
  • 276
2

Instead of adding the component without the proper constraints, you should create and use a custom glass pane:

class NewJFrame extends JFrame {

    // ...

    class RedLineGlassPane extends JComponent {
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g2d.setColor(Color.red);        
            java.awt.Component contentPane = NewJFrame.this.getContentPane();
            g2d.drawLine(0, 0,
                         contentPane.getWidth(), contentPane.getHeight());
        }
    }

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
        setGlassPane(new RedLineGlassPane());
        getGlassPane().setVisible(true);
        repaint();
    }

}

General coding suggestions and tips

  • Don't use a GUI builder until you can write layout code yourself. I know it's challenging, but you'll keep running into problems if you don't understand the code that's being generated.
  • If you must use a GUI builder, don't use the Netbeans GUI builder. This is subjective, but I have a few issues with Netbeans's builder:
    • It doesn't let you edit the code it generates.
    • It produces really messy code with GroupLayout.
    • It doesn't actually import anything; it uses fully qualified names everywhere.
    • It often produces code that's just plain bad: in your example, the mouse listener should be an action listener, so the user can press "Space" or whatever to activate it.
    • Instead, I would recommend using Eclipse and the WindowBuilder GUI builder, which used to be commercial but is now open source. It's a much more flexible builder that can both read code and write code – if you want to edit the code it generates, you can, and then continue to use the builder.
  • Read the Swing Trail. It really is worth the time.
  • When in doubt, use MigLayout for a comprehensive, easy-to-use layout manager.
  • Give your variables descriptive names. plotPanel is good. jButton1 is not.
  • When writing an SSCCE, include the minimum amount of code possible.
    • This will force you to find where the problem is, and often (for me it's about 80% of the time) allows you to find a solution on your own.
    • This will also force you to actually understand the code the GUI builder generates for you (although you should do this already).
    • Copy your code to a new file (a single file!) and keep deleting code until the problem goes away.
    • In your example, you can strip out:
      • the JavaApplication10 class, because NewJFrame has a main method
      • everything to do with the plot panel
      • everything to do with Nimbus
      • all the GroupLayout code
wchargin
  • 15,589
  • 12
  • 71
  • 110
  • @0x6B6F77616C74 Please consider posting an [SSCCE](http://www.sscce.org) for quicker, better assistance. – wchargin May 08 '13 at 23:45
2

Your plotPanel is using a GroupLayout:

plotPanel = new javax.swing.JPanel();
javax.swing.GroupLayout plotPanelLayout = new javax.swing.GroupLayout(plotPanel);
plotPanel.setLayout(plotPanelLayout);

You can't just add components to a GroupLayout without specifying constraints:

plotPanel.add(picLabel);

I have no idea how GroupLayout works so I would suggest that you create the JLabel in your GUI builder and add it to your plotPanel. That is, let the GUI builder create all the constraints for you.

Then when you want to actually add in Icon to the label you just do:

picLabel.setIcon(new ImageIcon( img ));

Now the layout manager will automatically layout the panel to include the new image.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

The main issue was that the element cannot be simply added when it uses layout manager, especially the GroupLayout. Here is the full solution, basing on camickr and Reimeus tips and my further investigations:

   private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
        BufferedImage img = new BufferedImage(plotPanel.getWidth(),plotPanel.getHeight(),BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2d = img.createGraphics();

        g2d.setColor(Color.red);        
        g2d.drawLine(0, 0, plotPanel.getWidth(), plotPanel.getHeight());

        jLabel1.setIcon(new ImageIcon(img)); //placed on plotPanel

        plotPanel.add(jLabel1);
        plotPanel.revalidate();
        plotPanel.repaint();

    }

All in all we only need to turn off the layout manager:

Windows->Navigating->Navigator->[JFrame]->plotPanel(right click)->Set layout->null

0x6B6F77616C74
  • 2,559
  • 7
  • 38
  • 65