有啥办法可以刷新 JDialog 并重新制作它?

Posted

技术标签:

【中文标题】有啥办法可以刷新 JDialog 并重新制作它?【英文标题】:Is there any way i can refresh a JDialog and remake it?有什么办法可以刷新 JDialog 并重新制作它? 【发布时间】:2022-01-12 03:39:12 【问题描述】:

我有一个带有一个按钮的主 JFrame,当我按下此按钮时,会打开一个 JDialog,其中包含 Json 文件中的一些对象。对于每个对象,我都有一个删除按钮。一切都很好,但是要查看除我删除的这个对象之外的所有对象,我必须关闭 JDialog 并再次打开它。有什么办法可以刷新 JDialog?我发现一个“解决方案”女巫是处置 JDialog 并制作新的,然后将新的设置为可见,但这并不是我真正需要的。我需要在按下按钮后立即看到新的结果。下面的 JFrame myFrame 是主框架不关心它(“我猜”)。 这是我的对话框:

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;

这是我的 JPanel 女巫,它在每个面板中都有一些来自 json 文件的详细信息。:

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;

这是我的删除按钮的动作监听器(是里面带有“X”的按钮):

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;

【问题讨论】:

来自 Json 文件的一些对象。 - 可能使用 JTable 来显示这些对象。然后,当您想要进行更改时,您只需从 TableModel 中添加/删除一行数据。 【参考方案1】:

您的问题的基本答案是,您的对话/面板需要某种方式来获得“下一个”鸡尾酒。那么您需要做的就是更新新鸡尾酒的详细信息。

实现这一目标的最佳方式是拥有某种“经理”,它负责管理您系统中的所有鸡尾酒。在删除当前鸡尾酒之前,您需要确定列表中鸡尾酒的当前索引,删除鸡尾酒,然后呈现现在占据该位置的鸡尾酒。你也可以使用某种Iterator 来做到这一点,但这有什么好玩的呢。

由于我无法访问您的所有代码(而且您的 UI 代码有些混乱),因此我设计了自己的示例。

下面是“详细信息”窗格,其中显示了有关鸡尾酒的详细信息,并允许用户将其删除。

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;
    
    

您会注意到,我已将CocktailManager 的实例以及Cocktail 的实例传递给了详细信息窗格。

如果当前的Cocktail 被删除,则显示下一个Cocktail(变为当前的),依此类推,直到您没有更多鸡尾酒了。

其中一些可以通过在CocktailManager 本身上使用观察者模式来解耦(因此,当添加或删除鸡尾酒时,相关方可以对其做出反应,但我认为这个概念已经断章取义了问题)。

可运行示例...

因为脱离上下文的代码很难理解,所以我提供了一个可运行的示例...

这个例子利用了依赖注入(对于reference、reference、reference、reference)和“编码到接口”(对于reference和reference)

这将允许您为 CocktailManager 定义您自己的“合同”并根据您的需要定义您自己的实现,但核心概念应该继续有效

您可能还想看看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:自带图片

nbb:创建此示例时没有消耗任何鸡尾酒,尽管它可能会提高质量 ?

【讨论】:

以上是关于有啥办法可以刷新 JDialog 并重新制作它?的主要内容,如果未能解决你的问题,请参考以下文章

有啥方法可以捕获页面刷新并暂停它?

制作一个显示“请稍候”JDialog 的摆动线程

刷新列表视图数据库

最近开始学习用spine做骨骼动画,有啥办法把一张完整的切片大图重新变成一张张小图?

有没有办法使用 quick.db 制作 discord.js 日志系统

有啥办法可以做到,所以我不必重新声明 module.exports 的依赖项?