有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java包装JTextArea没有获得足够的空间/窃取空间

包装(setLineWrap(true)JTextArea似乎没有足够的空间,因此被切断:
JTextArea cut off

将父布局及其子布局进行两次似乎可以解决这个问题:
JTextArea proper size

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.Collectors;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class JTextAreaTest {
    public static void main(String[] args) throws InvocationTargetException, InterruptedException {
        SwingUtilities.invokeAndWait(() -> {
            Arrays.asList(true, false).forEach(packTwice -> {
                testWrappingCutOff(packTwice);
            });
        });
    }
      
    private static void testWrappingCutOff(boolean packTwice) {
        JFrame frame = new JFrame("packTwice: " + packTwice);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        
        JTextArea wrapping = new JTextArea();
        wrapping.setLineWrap(true);
        wrapping.setText(Collections.nCopies(10, "wrapping").stream().collect(Collectors.joining(" ")));
        frame.add(wrapping);

        frame.pack();
        // Second call to pack() solves the problem
        if (packTwice) {
            frame.pack();
        }
        
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
}

此外,当它与其他组件一起使用时,它会“窃取”它们的空间。也就是说,当其他组件位于JScrollPane内时,它们会得到滚动条,即使它们的公共父组件可以被放大以适应这两个组件:
JTextArea stealing space

两次调用pack()再次解决了这个问题:
Both components properly layed out

将父母两次分开是相当不方便的,而且可能并不总是可能的

  • 我是否用错了课堂
  • 这是已知的限制,因为只有知道有多少可用空间,才能进行包装
  • 这是Swing的一个(尚未报道)错误吗
  • 还是有其他问题

共 (0) 个答案