java - 带 Swing 的测试套件

标签 java swing jlabel jtextfield

我开始用java制作一个“测试套件”。我目前正在从事句子完成类型测试。基本上我有一个带有占位符的文本,用户应该在其中输入一些文本,稍后将对其进行评估。我发现通过使用 FlowLayout,我可以将 JLabel 和 JTextField 放在一起。问题在于文本 block 太长。它应该跨越多行,但我不确定如何实际做到这一点。虽然没关系,如果我将一个小文本从行尾推到新行,但如果整个文本 block 比行宽长,我仍然会卡住。

而且我不想重新发明轮子,那么有没有用于测试套件的开源库?我的 googlefu 失败了。

the desired output

最佳答案

我发现这个问题的最佳解决方案是使用 Rob Camick 的 WrapLayout

WrapLayout 本质上是 FlowLayout 的扩展,当内容不再水平放置时,它会包裹内容。

查看上面链接的博客,它解释了您遇到问题的原因。

已更新

另一种选择是使用 JTextPane 并将字段插入到,例如...

enter image description here

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;

public class TestText {

    public static void main(String[] args) {
        new TestText();
    }

    public TestText() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JTextPane tp = new JTextPane();
                tp.replaceSelection("Asd, asd, asd, fgh ");
                addField(tp);
                tp.replaceSelection(" more funky text here ");
                addField(tp);
                tp.replaceSelection(" and this must wrap on the edge. The color code of red is: #");
                addField(tp);
                tp.replaceSelection(". ");
                tp.setEditable(false);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(tp));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

            protected void addField(JTextPane tp) {
                JTextField field = new JTextField(10);
                field.setAlignmentY(0.75f);
                tp.insertComponent(field);
            }
        });
    }

}

请注意,编辑器本身不可编辑,但文本字段...

关于java - 带 Swing 的测试套件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22185757/

相关文章:

java - 我怎样才能在java中压缩一个字符串?

Java,悬停组件时显示帮助标签

java - 尝试在模态对话框中更新 JLabel

java - 在屏幕上拖动一个 jlabel

java - 为什么数据没有显示在我的 ListView 上?

java - 我怎样才能在 EasyMock 中进行 cast 操作?

Java OutOfMemoryError 与 ArrayList<List<Integer>>

java - 如何移动到 JTextField 中的下一个标记

java - 在 Java 中进行 KeyEvent 更新 JLabel

java - java中不兼容的类型