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


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
}



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消失?

提前致谢。

最佳答案

如果没有JScrollPane父级,则不应使用JTextArea。如果没有该父项,它希望尽可能宽,这会导致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));

10-07 12:24
查看更多