如何解决Java:文本未在JFrame对话框中自动换行
|| 我正在使用JFrame来显示一个带有一些文本和2个按钮的消息框。如何根据框的大小自动包装文本? 这是我当前的代码: dialogFrame = new JFrame();
JButton newButton = new JButton(\"New\");
newButton.addActionListener(new newUploadAction());
JButton resumeButton = new JButton(\"Resume\");
resumeButton.addActionListener(new resumeUploadAction());
//dialogFrame.setUndecorated(true);
JPanel addPanel = new JPanel();
JPanel addPanel2 = new JPanel();
addPanel.add(newButton);
addPanel.add(resumeButton);
String text = \"<html><p>A previous control file exists for this file. \";
text += \"Would you like to initiate a new transfer or resume the previous one?</p></html>\";
JLabel testLabel = new JLabel(text);
//testLabel.setPreferredSize(new Dimension(1,1));
addPanel2.add(testLabel);
Container content = dialogFrame.getContentPane();
//content.setBackground(Color.white);
content.setLayout(new BoxLayout(content,BoxLayout.PAGE_AXIS));
content.add(addPanel2);
content.add(addPanel);
dialogFrame.setSize(200,200);
dialogFrame.setVisible(true);
dialogFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
我在某处读到那个电话
testLabel.setPreferredSize(new Dimension(1,1));
会导致我想要的换行行为,但这只会导致文本根本不显示。
解决方法
您可以将文本放在
JTextArea
中,然后在JTextArea
上分别调用setLineWrap(true)
和setWrapStyleWord(true)
。如果您希望它看起来更像JLabel风格,则只需根据自己的喜好更改JTextArea
的颜色设置即可。
编辑1
还有另一件事可能起作用:考虑让持有人JPanel
使用BorderLayout
:
JPanel addPanel2 = new JPanel(new BorderLayout()); //!! added BorderLayout
这样添加的ѭ10将会填充ѭ11。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。