假设我有一个字符串和JLabel,JLabel显示在JFrame上:
public String content="Hello fellow stack-overflowers, I want to format this output";
public JLabel jL = new JLabel();
执行以下操作后:
jL.setText(content);
我得到了这个输出:
Hello fellow stack-overflowers, I want to for..
但我真正想要的是文字不要超越标签或文本字段的长度,而是要创建一个换行符,如下所示:
Hello fellow stack-overflowers, I want
to format this output
询问是否需要更多信息。
答案 0 :(得分:3)
一种可能的解决方案是将标签文本包装在HTML
标签中,并允许底层布局管理器调整其大小,例如......
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test100 {
public static void main(String[] args) {
new Test100();
}
public Test100() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel label;
private JTextField textField;
public TestPane() {
label = new JLabel("<html>Hello fellow stack-overflowers, I want to format this output</html>");
textField = new JTextField(10);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
add(label);
gbc.gridx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
add(textField, gbc);
}
}
}
这个例子说明了压缩标签分裂的方法,你可能需要稍微调整一下这些值......