JTextPane中消失的组件

时间:2019-12-10 12:07:40

标签: java

我通过删除与问题无关的所有代码简化了我的问题。这给我留下了2个简单的Java类:

  1. BugFrameTest。存储最初为null的DefaultStyledDocument。有一个按钮可以打开一个对话框,第二个类。
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyledDocument;

public class BugFrameTest extends javax.swing.JFrame {

    private DefaultStyledDocument sectionTextDoc = null;

    public BugFrameTest() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Click for Dialog");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jButton1)
                .addContainerGap(20, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // java - get screen size using the Toolkit class
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        double screenWidth = screenSize.getWidth();
        double screenHeight = screenSize.getHeight();

        double percentReduce = 0.90;

        Dimension dimension = new Dimension();
        dimension.setSize(
                (int) (screenWidth * percentReduce),
                (int) (screenHeight * percentReduce));

        SectionJDialog2 sectionJDialog2 = null;

        sectionJDialog2 = new SectionJDialog2(
                this, true, sectionTextDoc);

        sectionJDialog2.setLocationRelativeTo(this);

        sectionJDialog2.setVisible(true);

        // After closing we store the document to display again.
        sectionTextDoc
                = (DefaultStyledDocument) sectionJDialog2.getDocument();
    }                                        

    /**
     * @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(BugFrameTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BugFrameTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BugFrameTest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BugFrameTest.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 BugFrameTest().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}
  1. SectionJDialog2。该对话框包含一个JTextPane和一个按钮,该按钮将一个空的JTextArea插入JTextPane中。关闭对话框后,JTextPane的DefaultStyledDocument存储在BugFrameTest中。
import java.awt.Color;
import javax.swing.JTextArea;
import javax.swing.text.DefaultStyledDocument;

public class SectionJDialog2 extends javax.swing.JDialog {

    private DefaultStyledDocument doc = new DefaultStyledDocument();

    public SectionJDialog2(
            java.awt.Frame parent,
            boolean modal,
            DefaultStyledDocument doc) {

        super(parent, modal);

        initComponents();

        pack();

        if (doc == null) {
            doc = new DefaultStyledDocument();
        }

        this.jTextPane1.setDocument(doc);
    }

    public DefaultStyledDocument getDocument() {
        return (DefaultStyledDocument) this.jTextPane1.getDocument();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        textAreaButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                closeDialogHandler(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jScrollPane2.setViewportView(jTextPane1);

        textAreaButton.setText("Insert Text Area");
        textAreaButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textAreaButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 551, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(textAreaButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(textAreaButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

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

    private void closeDialogHandler(java.awt.event.WindowEvent evt) {                                    

    }                                   

    private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
        this.dispose();
    }                                  

    private void textAreaButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
        JTextArea quoteField = new JTextArea();
        quoteField.setBackground(Color.lightGray);
        quoteField.setLineWrap(true);

        jTextPane1.insertComponent(quoteField);
    }                                              

    // Variables declaration - do not modify                     
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextPane jTextPane1;
    private javax.swing.JButton textAreaButton;
    // End of variables declaration                   
}

在第一次打开SectionJDialog2时,一切都很好。您可以插入JTextArea和没有问题的文本。然后关闭对话框。

在重新打开SectionJDialog2时(通过在BugFrameTest中按下按钮),文本和JTextArea仍然存在。但是,如果现在在JTextArea之后立即按返回键,则JTextArea消失(至少从显示中消失)。您可以关闭然后重新打开对话框,然后重新显示JTextArea。

然后我的问题很简单,如何阻止JTextArea消失?

谢谢。

2 个答案:

答案 0 :(得分:0)

JTextArea不能在没有JScrollPane父级的情况下使用。如果没有该父对象,它希望尽可能宽,这会导致JTextPane的布局问题。

JTextArea是一个文本组件,它允许多行文本。那真的是你想要的吗?如果只需要一个单行文本组件,则应使用JTextField

如果您坚持使用JTextArea,set its preferred column count并将其放置在JScrollPane中:

JTextArea quoteField = new JTextArea();
quoteField.setColumns(10);
quoteField.setBackground(Color.lightGray);
quoteField.setLineWrap(true);

jTextPane1.insertComponent(new JScrollPane(quoteField));

答案 1 :(得分:0)

我认为这个问题是Java中的错误。但是,在将可序列化的StyledDocument写入文件,然后在打开对话框之前读回对象之后,我发现了一种解决方法。

// Serialize data object to a file
ObjectOutputStream out = new ObjectOutputStream(
        new FileOutputStream(filePath) );
out.writeObject(doc);
out.close();


FileInputStream fis = new FileInputStream(
        filePath
);
ObjectInputStream reader = new ObjectInputStream(fis);
doc = (StyledDocument) reader.readObject();
相关问题