Редактирование текста во второстепенном окне Java

Занимаюсь приложение по созданию визиток. Сейчас в замешательстве как реализовать редактирование текста. Есть 3 файла. В VizitkaCreator реализуется функционал добавление элементом на визитку, при нажатии на кнопку для добавления текста, срабатывает функция addText(), которая создает текстовое поле в VizitkaCreator и Preview. Это текстовое поле редактируется при помощи TextEditor. Проблема в том, что когда я хочу удалить или например стереть текст из preview то это не работает, в остальных окнах работает.

VizitkaCreator

public class VizitkaCreator extends JFrame implements TextEditor.TextChangeListener{

private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel settings;
private JPanel panel_addImage;
private JButton btn_addImage;
private Button btn_preview;
private Button btn_clear;
private Button btn_removeImg;
private Button btn_export;
private Button btn_close;
private VizitkaCreator lastVizitkaCreator;
private JButton btn_addText;
private Image backgroundImage;
private TextEditor editor;
private JTextField textFieldInSettings;
private List<JTextField> textFieldsList = new ArrayList<>();
private List<JLabel> textLabels = new ArrayList<>();
private Preview previewWindow;
private JButton btn_addQr;
private JPanel texts;
private JButton btnUp;
private JButton btnDown;
private JButton btnLeft;
private JButton btnRight;


private void Common() {
    previewWindow = new Preview();
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(new GridLayout(0, 1, 0, 10));
    
    texts = new JPanel();
    contentPane.add(texts);
    texts.setLayout(new GridLayout(5, 1, 3, 0));

    settings = new JPanel();
    contentPane.add(settings);
    settings.setLayout(new GridLayout(2, 1, 5, 5));

    btn_addImage = new JButton("AddImage");
    settings.add(btn_addImage);
    
    btn_addText = new JButton("Add Text");
    settings.add(btn_addText);
                            
                            btn_addQr = new JButton("Add Qr");
                            btn_addQr.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                }
                            });
                            settings.add(btn_addQr);                        
                            btn_preview = new Button("Preview");
                            btn_preview.setForeground(UIManager.getColor("Button.background"));
                            btn_preview.setBackground(new Color(0, 128, 255));
                            
                            btn_preview.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    previewWindow.setVisible(true);
                                }
                            });
                            
                            settings.add(btn_preview);
            
                    btn_clear = new Button("Clear");
                    btn_clear.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            System.out.println(textFieldInSettings.getText());
                            removeImage();
                            previewWindow.removeAllTextFromPreview(textFieldInSettings.getText()); 
                        }
                    });
                    
                            btn_removeImg = new Button("Remove Image");
                            settings.add(btn_removeImg);
                    settings.add(btn_clear);
                    btn_removeImg.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            removeImage();
                        }
                    });

                    
                            btn_export = new Button("Export");
                            settings.add(btn_export);
                            
                                    btn_close = new Button("Back");
                                    settings.add(btn_close);
                                    
                                    btn_close.addActionListener(new ActionListener() {
                                        public void actionPerformed(ActionEvent e) {
            lastVizitkaCreator.setVisible(true);
                                            dispose(); 
                                        }
                                    });

    btn_addImage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "jpeg", "png", "gif");
            fileChooser.setFileFilter(filter);
            int result = fileChooser.showOpenDialog(VizitkaCreator.this);
            if (result == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                try {
                    Image image = ImageIO.read(selectedFile);
                    int width = image.getWidth(null);
                    int height = image.getHeight(null);
                    if ((width <= 1063 || width >= 1000) && (height <= 591 || height >= 560)) {
                        previewWindow.setBackgroundImage(image);
                        previewWindow.setVisible(true);
                    } else {
                        JOptionPane.showMessageDialog(VizitkaCreator.this, "Veľkosť obrázka musí byť 1063 x 591 pixelov.", "Chyba", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    });

    
    btn_addText.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            addText();
        }
    });
    
    
    setVisible(true);
}

public void removeImage() {
    previewWindow.setBackgroundImage(null);
    repaint();
}

public VizitkaCreator() {
    Common();
    textFieldsList = new ArrayList<>();
    textLabels = new ArrayList<>();
    texts.setPreferredSize(new Dimension(50, 50));
    setMinimumSize(new Dimension(550, 300));
    setSize(550, 300);

}

public void createVizitka(String[] texts, Font[] fonts, int[] xPositions, int[] yPositions, String imagePath) {
    textFieldsList = new ArrayList<>();
    List<JLabel> textLabels = new ArrayList<>();
    Preview previewWindow = new Preview();
    Common();
    for (int i = 0; i < texts.length; i++) {
        JLabel label = new JLabel(texts[i]);
        label.setFont(fonts[i]);
        label.setBounds(xPositions[i], yPositions[i], 200, 50);
        previewWindow.add(label);
    }

    if (imagePath != null && !imagePath.isEmpty()) {
        try {
            Image image = ImageIO.read(new File(imagePath));
            Preview previewWindow = new Preview(textLabels, image);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    previewWindow.revalidate();
    previewWindow.repaint();
}

private TextEditor.TextChangeListener textChangeListener = new TextEditor.TextChangeListener() {
    @Override
    public void onTextChange(String newText) {
        updatePreviewWithText(newText);
    }
};





@Override
public void onTextChange(String newText, Font font, Color textColor) {
    setTextInSettings(newText);
    updatePreviewWithText(newText, font, textColor);
}

private void setTextInSettings(String newText) {
    if (textFieldsList.size() > 0) {
        textFieldsList.get(textFieldsList.size() - 1).setText(newText);
    }
}

private void updatePreviewWithText(String text, Font font, Color textColor) {
    JLabel label = new JLabel(text);
    label.setFont(font);
    label.setForeground(textColor);
    label.setBounds(0, 0, 200, 50);
    previewWindow.addTextLabel(label);

    for (JTextField textField : textFieldsList) {
        if (textField.getText().equals(text)) {
            break; 
        }
    }
    textLabels.add(label);

    previewWindow.revalidate();
    previewWindow.repaint();
    if (textLabels != null) {
        textLabels.add(label);
    }

    previewWindow.revalidate();
    previewWindow.repaint();
}

public void addText() {
    TextEditor textEditorInstance = new TextEditor();
    textEditorInstance.setTextChangeListener(this); 
    textEditorInstance.setVisible(true);
    
    JTextField textFieldInSettings = new JTextField(); 
    textFieldInSettings.setEditable(false);
   
    JPanel panel_textSettings = new JPanel();        
    panel_textSettings.setLayout(new GridLayout(1, 0, 0, 0));
    panel_textSettings.add(textFieldInSettings);
    
    textEditorInstance.setTextMoveListener(previewWindow);
    JButton btnDelete = new JButton("Delete");
    btnDelete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            removeText(textFieldInSettings.getText());
            texts.remove(textFieldInSettings);
            texts.revalidate();
            texts.repaint();
            System.out.println(textFieldInSettings.getText());
            previewWindow.removeTextFromPreview(textFieldInSettings.getText());
        }
    });
    panel_textSettings.add(btnDelete);

    JButton btnEdit = new JButton("Edit");
    btnEdit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (editor == null) {
                editor = new TextEditor(); 
                editor.setText(textFieldInSettings.getText());
                editor.setTextChangeListener(new TextEditor.TextChangeListener() {
                    @Override
                    public void onTextChange(String newText, Font font, Color textColor) {
                        if (textFieldInSettings != null) {
                            textFieldInSettings.setText(newText);
                            updatePreviewWithText(newText, font, textColor);
                        }
                    }
                });
            } else {
                editor.setText(textFieldInSettings.getText());
                updatePreviewWithText(textFieldInSettings.getText(), editor.getCurrentFont(), editor.getCurrentColor());
            }
            editor.setVisible(true); 
        }
    });


    panel_textSettings.add(btnEdit);

    texts.add(panel_textSettings);
    texts.revalidate();
    texts.repaint();
    textFieldsList.add(textFieldInSettings);
    previewWindow.updateTextFieldsList(textFieldsList);
    
}

public void addText(List<String> texts) {
    for (String text : texts) {
        JLabel label = new JLabel(text);
        contentPane.add(label);
    }
    contentPane.revalidate();
    contentPane.repaint();
}

public void addTextLabel(JLabel label) {
    
    textLabels.add(label); 
    add(label); 
    revalidate();
    repaint();
}

public void clearTextLabels() {
    for (JLabel label : textLabels) {
        remove(label); 
    }
    textLabels.clear();
    repaint(); 
}

public void removeTextLabel(JLabel label) {
    if (textLabels.contains(label)) { 
        remove(label); 
        textLabels.remove(label); 
        revalidate();
        repaint();
    }
}


public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                VizitkaCreator frame = new VizitkaCreator();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

private void removeText(String textToRemove) {
    for (Component component : texts.getComponents()) {
        if (component instanceof JPanel) {
            JPanel panel = (JPanel) component;
            for (Component innerComponent : panel.getComponents()) {
                if (innerComponent instanceof JTextField) {
                    JTextField textField = (JTextField) innerComponent;
                    if (textField.getText().equals(textToRemove)) {
                        texts.remove(panel);
                        texts.revalidate();
                        texts.repaint();
                        previewWindow.removeTextLabel(findLabelByText(textToRemove));
                        return;
                    }
                }
            }
        }
    }
}

private JLabel findLabelByText(String text) {
    for (JLabel label : previewWindow.getTextLabels()) {
        if (label.getText().equals(text)) {
            return label;
        }
    }
    return null;
}


}

Preview

public class Preview extends JFrame implements TextEditor.TextMoveListener {

private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JLabel backgroundLabel;
private Image backgroundImage;
private java.util.List<JLabel> textLabels;
private int startX, startY;
private JTextField draggedTextField;
private List<Point> labelPositions;
private List<JTextField> textFieldsList;
/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Preview frame = new Preview();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Preview() {
    
     addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                System.out.println(1);
                for (JTextField textField : textFieldsList) {
                    if (textField.getBounds().contains(e.getPoint())) {
                        draggedTextField = textField;
                        startX = e.getX();
                        startY = e.getY();
                        break;
                    }
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                System.out.println(2);
                if (draggedTextField != null) {
                    draggedTextField.setLocation(draggedTextField.getX() + e.getX() - startX,
                            draggedTextField.getY() + e.getY() - startY);
                    draggedTextField = null;
                }
            }
        });

        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                System.out.println(3);
                if (draggedTextField != null) {
                    draggedTextField.setLocation(draggedTextField.getX() + e.getX() - startX,
                            draggedTextField.getY() + e.getY() - startY);
                }
            }
        });
    
    setResizable(false); 
    labelPositions = new ArrayList<>();
    textLabels = new ArrayList<>();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

    int windowWidth = 532;
    int windowHeight = 295;
    setSize(windowWidth, windowHeight);

    getRootPane().setBorder(new EmptyBorder(10, 10, 10, 10));

    int rightMargin = 50;
    int xPos = screenSize.width - windowWidth - rightMargin;
    int yPos = (screenSize.height - windowHeight) / 2; 
    setLocation(xPos, yPos);

    contentPane = new JPanel();
    contentPane.setBorder(new LineBorder(Color.BLACK));

    setContentPane(contentPane);
    contentPane.setLayout(null);

}

public Preview(List<String> texts, Image backgroundImage) {
    textLabels = new ArrayList<>();
    setTitle("Preview");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);

    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));
    setContentPane(contentPane);
    contentPane.setLayout(new BorderLayout());

    for (String text : texts) {
        JLabel textLabel = new JLabel(text);
        textLabel.setHorizontalAlignment(SwingConstants.CENTER);
        contentPane.add(textLabel);
    }

    backgroundLabel = new JLabel(new ImageIcon(backgroundImage));
    contentPane.add(backgroundLabel, BorderLayout.CENTER); 

    pack(); 
    setLocationRelativeTo(null); 
}

public void setBackgroundImage(Image backgroundImage) {
    this.backgroundImage = backgroundImage;
    repaint();
}   

public void updateTextFieldsList(List<JTextField> textFieldsList) {
    this.textFieldsList = textFieldsList;
    
}

public void removeTextLabel(JLabel label) {
    if (textLabels.contains(label)) {
        contentPane.remove(label);
        textLabels.remove(label);
        revalidate();
        repaint();
    }
}

public void updateText(String newText, Font font, Color textColor) {
    for (JLabel label : textLabels) {
        if (label.getText().equals(newText)) {
            label.setFont(font);
            label.setForeground(textColor);
            break;
        }
    }
}

public void addTextLabel(JLabel label) {
    contentPane.add(label);
    textLabels.add(label);
    labelPositions.add(label.getLocation());
    revalidate();
    repaint();
}

public List<JLabel> getTextLabels() {
    return textLabels;
}

public void removeTextFromPreview(String text) {
    List<JLabel> labelsToRemove = new ArrayList<>(); 
    for (JLabel label : textLabels) {
        if (label.getText().equals(text)) {
            labelsToRemove.add(label); 
        }
    }

    for (JLabel label : labelsToRemove) {
        removeTextLabel(label);
        contentPane.remove(label);
        textLabels.remove(label); 
    }
    revalidate();
    repaint();
}

public void removeAllTextFromPreview(String textToRemove) {
    Component[] components = contentPane.getComponents();
    for (Component component : components) {
        if (component instanceof JLabel) {
            JLabel label = (JLabel) component;
            if (label.getText().equals(textToRemove)) {
                contentPane.remove(label);
                textLabels.remove(label); 
            }
        }
    }
    revalidate();
    repaint();
}

public void onTextMove(int deltaX, int deltaY) {
    System.out.println(1);
    for (JLabel label : textLabels) {
        Point position = label.getLocation();
        label.setLocation(position.x + deltaX, position.y + deltaY);
    }
    repaint();
}


}

TextEditor

public class TextEditor extends JFrame {

private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panel_text;
private JPanel panel_settings;
private JTextArea textArea;
private VizitkaCreator createInstance;
private TextChangeListener textChangeListener;
private Font currentFont;
private Color currentColor;
private JPanel panel_controlBtns;
private JButton btnUp;
private JButton btnDown;
private JButton btnLeft;
private JButton btnRight;
private TextMoveListener textMoveListener;
private Preview previewWindow;
private TextEditor textEditorInstance;

public void setTextEditorInstance(TextEditor textEditorInstance) {
    this.textEditorInstance = textEditorInstance;
    System.out.println(textEditorInstance);
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                TextEditor frame = new TextEditor();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public void onTextMove(int deltaX, int deltaY) {
    System.out.println("Moving text by deltaX: " + deltaX + ", deltaY: " + deltaY);
    if (previewWindow != null) {
        List<JLabel> textLabels = previewWindow.getTextLabels();
        for (JLabel label : textLabels) {
            Point position = label.getLocation();
            label.setLocation(position.x + deltaX, position.y + deltaY);
        }
        previewWindow.repaint();
        System.out.println("Preview window updated.");
    } else {
        System.out.println("Preview window is null. Make sure it is initialized and passed correctly.");
    }
}


public void setPreviewWindow(Preview previewWindow) {
    this.previewWindow = previewWindow;
}


interface TextChangeListener {
    void onTextChange(String newText, Font font, Color textColor);
}

interface TextMoveListener {
    void onTextMove(int deltaX, int deltaY);
}

public void setTextMoveListener(TextMoveListener listener) {
    this.textMoveListener = listener;
}

public void setTextMoveListenerPv(Preview previewWindow) {

    System.out.println("Установка слушателя перемещения текста...");
    this.previewWindow = previewWindow;
    System.out.println("Слушатель перемещения текста установлен: " + previewWindow);

}


private void updateText(String newText, Font font, Color textColor) {
    if (textChangeListener != null) {
        textChangeListener.onTextChange(newText, font, textColor);
    }
}

public void setTextChangeListener(TextChangeListener listener) {
    this.textChangeListener = listener;
}

 public void setTextMoveListener(Preview previewWindow) {
      this.textMoveListener = previewWindow;
}

 
 public Font getSelectedFont() {
        return textArea.getFont();
    }

    public Color getSelectedTextColor() {
        return textArea.getForeground();
    }

public TextEditor() {   
    
    setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(new GridLayout(0, 1, 0, 0));
    
    panel_text = new JPanel();
    contentPane.add(panel_text);
    panel_text.setLayout(new GridLayout(0, 1, 0, 0));
    
    textArea = new JTextArea();
    textArea.setRows(2);
    textArea.setBorder(new EmptyBorder(10, 10, 10, 10));
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.setForeground(Color.GRAY);
    panel_text.add(textArea);
    
    panel_settings = new JPanel();
    panel_settings.setBorder(BorderFactory.createTitledBorder("Text Settings"));
    contentPane.add(panel_settings);
    panel_settings.setLayout(new GridLayout(3, 0, 0, 0));
    
    JLabel fontLabel = new JLabel("Font:");
    panel_settings.add(fontLabel);

    panel_settings.add(fontLabel);
    
    JLabel fontSizeLabel = new JLabel("Font Size:");
    JSpinner fontSizeSpinner = new JSpinner(new SpinnerNumberModel(12, 6, 72, 1));
    fontSizeSpinner.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            int fontSize = (int) fontSizeSpinner.getValue();
            Font currentFont = textArea.getFont();
            textArea.setFont(currentFont.deriveFont((float)fontSize));
        }
    });
    JComboBox<String> fontComboBox = new JComboBox<>(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
    panel_settings.add(fontComboBox); 
    
    fontComboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String fontFamily = (String) fontComboBox.getSelectedItem();
            int fontSize = (int) fontSizeSpinner.getValue(); 
            textArea.setFont(new Font(fontFamily, Font.PLAIN, fontSize));
        }
    });


    panel_settings.add(fontSizeLabel);
    panel_settings.add(fontSizeSpinner);
    
    JLabel colorLabel = new JLabel("Text Color:");
    JButton textColorButton = new JButton("Choose Color");
    textColorButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Color selectedColor = JColorChooser.showDialog(TextEditor.this, "Choose Text Color", Color.BLACK);
            if (selectedColor != null) {
                textArea.setForeground(selectedColor);
            }
        }
    });
    panel_settings.add(colorLabel);
    panel_settings.add(textColorButton);
    
    textArea.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent e) {
            updateText(textArea.getText(), textArea.getFont(), textArea.getForeground());
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            updateText(textArea.getText(), textArea.getFont(), textArea.getForeground());
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            updateText(textArea.getText(), textArea.getFont(), textArea.getForeground());
        }
    }); 
    
    panel_controlBtns = new JPanel();
    panel_controlBtns.setBorder(BorderFactory.createTitledBorder("Control Settings"));
    contentPane.add(panel_controlBtns);
    panel_controlBtns.setLayout(new GridLayout(1, 4, 5, 5));
    
    
    btnUp = new JButton("↑");
    btnUp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println(textEditorInstance);
            textEditorInstance.onTextMove(0, -10);
        }
    });
    panel_controlBtns.add(btnUp);

    btnDown = new JButton("↓");
    btnDown.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (textEditorInstance != null) {
                textEditorInstance.onTextMove(0, 10);
            }
        }
    });
    panel_controlBtns.add(btnDown);

    btnLeft = new JButton("←");
    btnLeft.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (textEditorInstance != null) {
                textEditorInstance.onTextMove(-10, 0);
            }
        }
    });
    panel_controlBtns.add(btnLeft);

    btnRight = new JButton("→");
    btnRight.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (textEditorInstance != null) {
                textEditorInstance.onTextMove(10, 0);
            }
        }
    });
    panel_controlBtns.add(btnRight);

  
}


public void setText(String text) {
    textArea.setText(text);
}

public Font getCurrentFont() {
    return currentFont;
}

public void setCurrentFont(Font font) {
    this.currentFont = font;
}

public Color getCurrentColor() {
    return currentColor;
}

public void setCurrentColor(Color color) {
    this.currentColor = color;
}
}

Ответы (0 шт):