gpt4 book ai didi

java - 在 JPane 上正确显示多行

转载 作者:行者123 更新时间:2023-11-30 08:01:03 25 4
gpt4 key购买 nike

我有一个关于多行支持的 JPane 的问题:如果内容只有一行,JPane 会正确显示。但从 2 行或更多行开始,内容移到顶部,显示不正常。有 1 行: enter image description here

2行或更多: enter image description here

代码在这里:

    String test=" Deutsch, Bahasa Indonesia,Italiano &nbsp; <a href=\"\">  edit</a>";
this.add(panelWithHtmlListener(test), new GridBagConstraints(0, POS_Y, 1, 1,
1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.CENTER,
new Insets(0, GUIConstants.ELM_FIRST_COLUMN_WIDTH+8 , 0,
GUIConstants.ELM_ALIGN_RIGHT), 8, 0));

private static JPanel panelWithHtmlListener(String msg){

JEditorPane jEditorPane = new JEditorPane("text/html", msg);
jEditorPane.setEditable(false);
jEditorPane.setOpaque(false);
int w= getContentWidtht(msg);
int h= getContentHeight(msg);
// jEditorPane.setPreferredSize(new Dimension(370,h));
jEditorPane.setAlignmentY(LEFT_ALIGNMENT);
HyperlinkListener listener = new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent hyperLink) {

if (HyperlinkEvent.EventType.ACTIVATED.
equals(hyperLink.getEventType())) {
try {
//respond to html link clicked
// JOptionPane.showMessageDialog(null, "HTML has been clicked !!" );
JFrame frame;
SearchLanguageDialog window = new SearchLanguageDialog();
window.frame.setVisible(true);
}
catch (Exception ex) { ex.printStackTrace();}


}
}
};

jEditorPane.addHyperlinkListener(listener);

JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout(5, 5));
jPanel.add(jEditorPane, BorderLayout.CENTER);
jPanel.setBackground(Color.white);


return jPanel;
}

请帮我重温一下。谢谢!

最佳答案

这段代码对您有帮助吗?

我在 JLabel 文本中添加了一些 html,并将布局更改为 GroupLayout(我所知道的最灵活的 - 我们一直使用它:P)

import javax.swing.GroupLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TestPanel extends JPanel {

final String LONG_MSG = "This is some sample text with many words to display. It should be definitely wrapped";
final String LINK = "<a href='#'>link</a>";
JLabel lblTitle = new JLabel("Content:");
JLabel lblContent = new JLabel("<html><body style='width: 300px'>" + LONG_MSG + " " + LINK + "</body></html>");

public TestPanel() {
GroupLayout layout = new GroupLayout(this);
setLayout(layout);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(lblTitle)
.addGap(20)
.addComponent(lblContent));
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(lblTitle)
.addComponent(lblContent));
}

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setContentPane(new TestPanel());
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

enter image description here

关于java - 在 JPane 上正确显示多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31916917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com