Search code examples
javaswingjframerefreshjdialog

How can i refresh a JDialog Image Correctly?


i am coding a program using SWing in java, but this is my problem, when i press a button, I want that every time I press a button, I update a new image in the same position as the previous one, I try to do it in the action listener of the code, but the image is not updated and the one that was At the beginning, can someone help me in this? Thank you very much.

public MainWindow() {
    initComponents();
    setIconImage(Icono);
    this.setLocationRelativeTo(null);
    this.setResizable(false);
    Imagen fondo=new Imagen();
    this.add(fondo, BorderLayout.CENTER);
    this.pack();
    PracticeMode = new javax.swing.JDialog();
}

private void StartPracticeActionPerformed(java.awt.event.ActionEvent evt) {                                              
    ButtonsSelected(1);
    StartGame Practice=new StartGame(OpcComboBox, numUnity, numTrys, 
    opcNotas, false);
    PracticeBF.dispose();
    PracticeMode.setIconImage(Icono);
    PracticeMode.setBounds(460, 600, 460, 538);
    PracticeMode.setVisible(true);
    CirculodeQuintasBW BW=new CirculodeQuintasBW();
    PracticeMode.add(BW, BorderLayout.CENTER);
    PracticeMode.pack();
    PracticeMode.setLocationRelativeTo(null);
    PracticeMode.setResizable(false);
}           

This is the Image that i want to refresh, it supossed to be another Image before of that, but each time i tried to refresh it doesnt work... PracticeMode it supossed to be a JDialog, anybody can help me?.

private void D2ActionPerformed(java.awt.event.ActionEvent evt) {                                   
    CirculodeQuintasD D=new CirculodeQuintasD();
    PracticeMode.add(D, BorderLayout.CENTER);
    PracticeMode.validate();
    PracticeMode.repaint();
    PracticeMode.pack();
}       

Solution

  • First of all variable names and method names should NOT start with an upper case character. Learn by example from reading your text book or tutorial and then follow the Java conventions and don't make up your own!

    when i press a button, I want that every time I press a button, I update a new image in the same position as the previous one,

    Add an JLabel containing an ImageIcon to your panel.

    When you want to change the image you just use:

    label.setIcon( new ImageIcon(...) );
    

    For example read the section from the Swing tutorial on How to Use Combo Boxes. It does exactly what your want. It uses an ActionListener to change the image of a label. The only different is that the ActionEvent is generated by clicking on an item in the combobox instead of clicking on a button.