简体   繁体   中英

Is there any way i can refresh a JDialog and remake it?

I have one main JFrame with one button, when i press this button, one JDialog open with some objects from a Json File. For each object i have a delete button. Everything works great but to see all objects except this one i deleted, i have to close the JDialog and open it again. Is there any way i can refresh JDialog? I found one "solution" witch is to dispose the JDialog and make new one and then set the new one visible, but its not really what i need. I need to see the new results immediately after the button press.The JFrame myFrame bellow is the main Frame dont care about it("i guess"). this is my Dialog:

public class MyFavoriteCoctails extends JDialog {

public MyFavoriteCoctails(JFrame myFrame) {
    this.myFrame = myFrame;
    setLocationRelativeTo(myFrame);
    maker();
}

private void maker() {
    setModal(true);
    setTitle("My Favortie Cocktails");
    setResizable(false);
    setLayout(new BorderLayout());
    JPanel panelOnTop = new JPanel(new BorderLayout());
    JLabel favCocktailLabel = new JLabel("My Favorite Cocktails");
    favCocktailLabel.setFont(new Font("Sans Serif", Font.PLAIN, 150));
    favCocktailLabel.setForeground(Color.red);
    panelOnTop.setBorder(BorderFactory.createMatteBorder(5, 5, 5, 5, Color.red));
    panelOnTop.add(favCocktailLabel, BorderLayout.CENTER);
    panelOnTop.setBackground(Color.white);
    this.add(panelOnTop, BorderLayout.NORTH);
    JPanel panelForCocktails = new JPanel();
    this.add(panelForCocktails, BorderLayout.CENTER);
    List<Coctail> list = SingleObject.getfavCoctailList();
    int row;
    if ((list.size() % 5) != 0) {
        row = list.size() / 5 + 1;
    } else {
        row = list.size() / 5;
    }
    panelForCocktails.setLayout(new GridLayout(row, 5));
    this.add(panelForCocktails, BorderLayout.CENTER);
    for (int i = 0; i < list.size(); i++) {
            panelForCocktails.add(new CocktailJPanelForFavorites(list.get(i).getId(), list.get(i).getImg(),
                    list.get(i).getName(), list.get(i), this, myFrame));
    }
    pack();


}

JFrame myFrame;

} This is my JPanel witch it has some details from json file in every panel.:

public class CocktailJPanelForFavorites extends JPanel {
public CocktailJPanelForFavorites(String id, String img, String name, Coctail coctail, JDialog dialog, JFrame myFrame) {
    this.coctail = coctail;
    this.myFrame=myFrame;
    this.id = id;
    this.name = name;
    this.img = img;
    this.dialog=dialog;
    maker();
}

@SuppressWarnings({ "rawtypes", "unchecked" })
public void maker() {
    setLayout(new BorderLayout(1, 1));
    this.setBackground(Color.white);
    this.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));
    JLabel nameLabel = new JLabel(name, SwingConstants.CENTER);
    nameLabel.setFont(new Font("Sans Serif", Font.BOLD, 18));
    this.add(nameLabel, BorderLayout.NORTH);
    JButton deleteFavorite = new JButton("X");

    JComboBox comboBox = new JComboBox(Favouritetype.values());
    comboBox.setRenderer(new MyComboBoxRenderer("ΚΑΤΗΓΟΡΙΑ"));
    comboBox.setSelectedIndex(-1);
    ;

    try {
        URL url = new URL(img);
        BufferedImage c = ImageIO.read(url);
        ImageIcon imageIcon = new ImageIcon(c); // load the image to a imageIcon
        Image image = imageIcon.getImage(); // transform it
        Image newimg = image.getScaledInstance(200, 200, java.awt.Image.SCALE_SMOOTH); // scale
        imageIcon = new ImageIcon(newimg); // transform it back
        JLabel jp = new JLabel(imageIcon, JLabel.CENTER);
        jp.setBorder(BorderFactory.createMatteBorder(10, 10, 10, 10, Color.white));
        jp.addMouseListener(new MouseAdapter(id));
        jp.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        add(jp, BorderLayout.CENTER);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JPanel deleteAndCombo = new JPanel(new GridLayout(1, 2));
    deleteAndCombo.add(deleteFavorite);
    deleteAndCombo.add(comboBox);
    add(deleteAndCombo, BorderLayout.SOUTH);
    DeleteFavorite act = new DeleteFavorite(coctail, deleteFavorite, dialog, this, myFrame);
    deleteFavorite.addActionListener(act);

}

String id, name, img;
Coctail coctail;
JDialog dialog;
JFrame myFrame;

}

And this is my Action Listener of my Delete Button(is the button with the "X" inside):

public class DeleteFavorite implements ActionListener {
public DeleteFavorite(Coctail coctail, JButton deleteFavorite, JDialog dialog, JPanel cockPane, JFrame myFrame) {
    this.deleteFavorite = deleteFavorite;
    this.coctail = coctail;
    this.myFrame=myFrame;
    this.dialog=dialog;
    this.cockPane=cockPane;
}

@Override
public void actionPerformed(ActionEvent e) {
    SingleObject obj = SingleObject.getInstance();
    List<Coctail> list = SingleObject.getfavCoctailList();

    List<Coctail> favcoctailList = list;
    int len = favcoctailList.size();
    if (favcoctailList != null) {
        for (int i = 0; i < len; i++) {
            if ((favcoctailList.get(i).getId().toString().trim().equals(coctail.getId().toString().trim()))) {
                favcoctailList.remove(i);
                break;
            }
        }
    }
    System.out.println(favcoctailList);
    obj.make(favcoctailList);
    dialog.dispose();
     MyFavoriteCoctails dialog1 = new MyFavoriteCoctails(myFrame);
     dialog1.setVisible(true);
}
JButton deleteFavorite;
Coctail coctail;
JDialog dialog;
JPanel cockPane;
JFrame myFrame;

}

The basic answer to your question is, your dialog/panel needs some way to get the "next" cocktail. Then all you need to do is update the details of the new cocktail.

The best way to achieve this is to have some kind of "manager", which managers all the cocktails within your system. Before deleting the current cocktail, you'd ascertain the current index of the cocktail within the list, remove the cocktail and then present the cocktail which now occupies this position. You could also do this with some kind of Iterator , but where's the fun in that.

Since I don't have access to all you code (and your UI code is a bit of mess), I devised my own example.

Below is the "detail" pane, which presents details about a give cocktail and allows the user to remove it.

public class CocktailDetailPane extends JPanel {
    
    private JLabel imageLabel;
    private JLabel nameLabel;
    
    private CocktailManager cocktailManager;
    private Cocktail cocktail;
    
    public CocktailDetailPane(Cocktail cocktail, CocktailManager manager) {
        this.cocktailManager = manager;
        setLayout(new BorderLayout());
        
        imageLabel = new JLabel();
        nameLabel = new JLabel();
        
        JPanel contentPane = new JPanel(new GridBagLayout());
        contentPane.setBorder(new EmptyBorder(16, 16, 16, 16));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridheight = GridBagConstraints.REMAINDER;
        gbc.anchor = GridBagConstraints.PAGE_START;
        gbc.insets = new Insets(4, 4, 4, 4);
        
        contentPane.add(imageLabel, gbc);

        gbc = new GridBagConstraints();
        gbc.insets = new Insets(4, 4, 4, 4);
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.LINE_START;

        contentPane.add(nameLabel, gbc);
        gbc.gridy++;
        contentPane.add(new JLabel("Drink it fast, drink it often"), gbc);
        
        add(contentPane);
        
        setCocktail(cocktail);
        
        JPanel actionPane = new JPanel(new GridBagLayout());
        JButton deleteButton = new JButton("Delete");
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CocktailManager manager = getCocktailManager();
                List<Cocktail> cocktails = manager.getCocktails();
                Cocktail cocktail = getCocktail();
                int index = cocktails.indexOf(cocktail);
                manager.remove(cocktail);
                if (cocktails.isEmpty()) {
                    JOptionPane.showMessageDialog(CocktailDetailPane.this, "No more cocktails for you", "Empty", JOptionPane.ERROR_MESSAGE);
                    SwingUtilities.windowForComponent(CocktailDetailPane.this).dispose();
                } else {
                    if (index >= cocktails.size()) {
                        index = 0;
                    }
                    setCocktail(cocktails.get(index));
                }
            }
        });
        actionPane.add(deleteButton);
        
        add(actionPane, BorderLayout.SOUTH);
    }
    
    protected void setCocktail(Cocktail cocktail) {
        imageLabel.setIcon(new ImageIcon(cocktail.getImage()));
        nameLabel.setText(cocktail.getName());
        this.cocktail = cocktail;
    }

    public CocktailManager getCocktailManager() {
        return cocktailManager;
    }

    public Cocktail getCocktail() {
        return cocktail;
    }
    
}

You will note that I've passed an instance of CocktailManager to the details pane as well as the instance of the Cocktail to be initially presented.

If the current Cocktail is deleted, the next Cocktail is presented (made current) and so on until you have no more cocktails left.

Some of this could have been decoupled through the use of an observer pattern on the CocktailManager itself (so when a cocktail was added or removed, interested parties could react to it, but I took that concept as been out of context for the question).

Runnable example...

Because out of context code can be hard to follow, I've provided a runnable example...

This example makes use of dependency injection (for reference , reference , reference , reference ) and "coding to interface" (for reference and reference )

This will allow you to define you own "contract" for the CocktailManager and define your own implementations based on your needs, but the core concept should continue to work

You may also want to take a look at How to Use Lists

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.AbstractListModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                CocktailManager manager = new DefaultCocktailManager();
                JFrame frame = new JFrame();
                frame.add(new CocktailListPane(manager));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public interface Cocktail {
        public String getId();
        public Image getImage();
        public String getName();
    }

    public interface CocktailManager {
        public List<Cocktail> getCocktails();
        public void add(Cocktail coctail);
        public void remove(Cocktail coctail);
    }

    public class CocktailListPane extends JPanel {

        private JList<Cocktail> list;
        private CocktailManager manager;

        public CocktailListPane(CocktailManager manager) {
            this.manager = manager;
            list = new JList<>(new CocktailListModel(manager));
            list.setCellRenderer(new CocktailListCellRenderer());

            list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
            list.setVisibleRowCount(2);

            setLayout(new BorderLayout());
            add(new JLabel("My Favorite Cocktails"), BorderLayout.NORTH);
            add(new JScrollPane(list));

            list.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() != 2) {
                        return;
                    }
                    int index = list.locationToIndex(e.getPoint());
                    if (index < 0) {
                        return;
                    }
                    Cocktail cocktail = list.getModel().getElementAt(index);
                    JDialog dialog = new JDialog(SwingUtilities.windowForComponent(CocktailListPane.this));
                    dialog.setTitle("All your cocktail belong to us");
                    dialog.setModal(true);
                    dialog.add(new CocktailDetailPane(cocktail, getCocktailManager()));
                    dialog.pack();
                    dialog.setLocationRelativeTo(CocktailListPane.this);
                    dialog.setVisible(true);

                    list.setModel(new CocktailListModel(getCocktailManager()));
                }
            });
        }

        public CocktailManager getCocktailManager() {
            return manager;
        }

        protected class CocktailListModel extends AbstractListModel<Cocktail> {

            private CocktailManager manager;

            public CocktailListModel(CocktailManager manager) {
                this.manager = manager;
            }

            @Override
            public int getSize() {
                return manager.getCocktails().size();
            }

            @Override
            public Cocktail getElementAt(int index) {
                return manager.getCocktails().get(index);
            }

        }

        protected class CocktailListCellRenderer extends DefaultListCellRenderer {

            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                if (value instanceof Cocktail) {
                    Cocktail cocktail = (Cocktail) value;
                    value = cocktail.getName();
                    super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                    setIcon(new ImageIcon(cocktail.getImage()));
                    return this;
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }

        }

    }

    public class CocktailDetailPane extends JPanel {

        private JLabel imageLabel;
        private JLabel nameLabel;

        private CocktailManager cocktailManager;
        private Cocktail cocktail;

        public CocktailDetailPane(Cocktail cocktail, CocktailManager manager) {
            this.cocktailManager = manager;
            setLayout(new BorderLayout());

            imageLabel = new JLabel();
            nameLabel = new JLabel();

            JPanel contentPane = new JPanel(new GridBagLayout());
            contentPane.setBorder(new EmptyBorder(16, 16, 16, 16));
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridheight = GridBagConstraints.REMAINDER;
            gbc.anchor = GridBagConstraints.PAGE_START;
            gbc.insets = new Insets(4, 4, 4, 4);

            contentPane.add(imageLabel, gbc);

            gbc = new GridBagConstraints();
            gbc.insets = new Insets(4, 4, 4, 4);
            gbc.gridx = 1;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.LINE_START;

            contentPane.add(nameLabel, gbc);
            gbc.gridy++;
            contentPane.add(new JLabel("Drink it fast, drink it often"), gbc);

            add(contentPane);

            setCocktail(cocktail);

            JPanel actionPane = new JPanel(new GridBagLayout());
            JButton deleteButton = new JButton("Delete");
            deleteButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    CocktailManager manager = getCocktailManager();
                    List<Cocktail> cocktails = manager.getCocktails();
                    Cocktail cocktail = getCocktail();
                    int index = cocktails.indexOf(cocktail);
                    manager.remove(cocktail);
                    if (cocktails.isEmpty()) {
                        JOptionPane.showMessageDialog(CocktailDetailPane.this, "No more cocktails for you", "Empty", JOptionPane.ERROR_MESSAGE);
                        SwingUtilities.windowForComponent(CocktailDetailPane.this).dispose();
                    } else {
                        if (index >= cocktails.size()) {
                            index = 0;
                        }
                        setCocktail(cocktails.get(index));
                    }
                }
            });
            actionPane.add(deleteButton);

            add(actionPane, BorderLayout.SOUTH);
        }

        protected void setCocktail(Cocktail cocktail) {
            imageLabel.setIcon(new ImageIcon(cocktail.getImage()));
            nameLabel.setText(cocktail.getName());
            this.cocktail = cocktail;
        }

        public CocktailManager getCocktailManager() {
            return cocktailManager;
        }

        public Cocktail getCocktail() {
            return cocktail;
        }

    }

    public class DefaultCocktailManager implements CocktailManager {

        private List<Cocktail> cocktails;
        private List<Cocktail> nonmutableCocktails;

        public DefaultCocktailManager() {
            cocktails = new ArrayList<>(4);
            nonmutableCocktails = Collections.unmodifiableList(cocktails);
            for (int index = 1; index < 5; index++) {
                Image image = null;
                try {
                    image = ImageIO.read(getClass().getResource("/images/ct0" + index + ".png")).getScaledInstance(-1, 50, Image.SCALE_SMOOTH);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                Cocktail cocktail = new DefaultCocktail(Integer.toString(index), image, "Cocktail " + index);
                cocktails.add(cocktail);
            }
        }

        @Override
        public List<Cocktail> getCocktails() {
            return nonmutableCocktails;
        }

        @Override
        public void add(Cocktail cocktail) {
            cocktails.add(cocktail);
        }

        @Override
        public void remove(Cocktail cocktail) {
            cocktails.remove(cocktail);
        }

    }

    public class DefaultCocktail implements Cocktail {

        private String id;
        private Image image;
        private String name;

        public DefaultCocktail(String id, Image image, String name) {
            this.id = id;
            this.image = image;
            this.name = name;
        }

        @Override
        public String getId() {
            return id;
        }

        @Override
        public Image getImage() {
            return image;
        }

        @Override
        public String getName() {
            return name;
        }

    }

}

nb: BYO your own images

nbb: No cocktails were consumed in the creation of this example, although it probably would have improved the quality

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM