JDialog doesn't size correctly with wrapped JTextArea

别说谁变了你拦得住时间么 提交于 2021-02-11 16:51:29

问题


While making a program, I noticed a bug with the JOptionPane.showMessageDialog() call. I use a button to create a JTextArea that wraps and then display a dialog containing this text area.

If the text area is too large, however, the dialog does not size itself correctly to the height of the JTextArea. The Dialog cuts off the OK button in this example.

I replicated the bug in the following code:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;


public class DialogBug {

    public static void main(String[] args) {
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final String text = "looooooooooooooooooooooong text looooooooooooooooooooooooooooooooooooooong text";

        JButton button = new JButton();
        button.setPreferredSize(new Dimension(30, 30));

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JTextArea area = new JTextArea(text, 0, 50);
                area.setEditable(false);
                area.setLineWrap(true);
                area.setWrapStyleWord(true);
                area.append(text);
                area.append(text);
                area.append(text);

                JOptionPane.showMessageDialog(frame, area, "why does it do this", JOptionPane.WARNING_MESSAGE);
            }
        });

        frame.add(button);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

I would post a picture, but I don't have enough reputation...

Is there a way to fix this without having to use a JScrollPane?

Here's a screenshot:


回答1:


If you run the pack command on the dialog (a function in the Window class) it will resize based on subcomponents. For your case you will have to rewrite without using the showMessageDialog() to get the resize to work (so make the dialog first, add the text, pack, then show it)

Dialog b = new Dialog();
// add stuff
b.pack();

For my test code it worked perfectly to get the dialogs to be the right sizes

  1. Without pack() With Pack Command
  2. With pack() With Pack Command


来源:https://stackoverflow.com/questions/23260894/jdialog-doesnt-size-correctly-with-wrapped-jtextarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!