1

I am trying to write a Java program which, when you click a button, hides the button and displays an image. I have made it so that the button disappears but the label does not appear. Here is my code:

final JLabel label = new JLabel(image, JLabel.CENTER);
label.setAlignmentX(0);
label.setAlignmentY(0);
label.setVisible(false);
label.setIcon(image);

final JButton button = new JButton("CLICK");
button.addActionListener(new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent e) {
        button.setVisible(false);
        label.setVisible(true);
    }

});
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Cj1m
  • 805
  • 3
  • 11
  • 26

3 Answers3

1

The solution is to place both the button and the label on the same panel. Initially hide the label. Then, when button is clicked, hide button and unhide the label.

Here is an example:

public class MagicButton {

    public static void main(String[] args) {
        // Components
        final JFrame frame = new JFrame("Magic Button");
        final JButton btn = new JButton("Now, you see me!");
        final JLabel label = new JLabel("Now, you don't!");

        // Arrangement
        frame.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
        frame.add(label);
        frame.add(btn);

        // Make Label invisible
        label.setVisible(false);

        // When button clicked: hide button, show label, repack frame
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                btn.setVisible(false);
                label.setVisible(true);
                frame.pack();
            }
        });

        // pack and display
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}
davidXYZ
  • 719
  • 1
  • 8
  • 16
0

Place all items on a JFrame and do a revalidate() on the JFrame to get the changes displayed.

marc3l
  • 2,525
  • 7
  • 34
  • 62
  • You don't add components to a frame. You add components to a JPanel. Then you add the panel to the frame. JFrame does not implement the revalidate() method. You should do revalidate() on the panel. – camickr Jul 18 '13 at 15:53
0

Try this one...

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() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/1371634490.png"))); // NOI18N
        jLabel1.setText("jLabel1");
        jLabel1.setVisible(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(159, 159, 159))
            .addGroup(layout.createSequentialGroup()
                .addGap(148, 148, 148)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(120, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(48, 48, 48)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(91, 91, 91))
        );

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

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
        // TODO add your handling code here:

        jLabel1.setVisible(true);
        jButton1.setVisible(false);
    }

    /**
     * @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);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration
}
Ganesh Rengarajan
  • 2,006
  • 13
  • 26