我有 Jlabels
在 JSsrollPane
右对齐。我希望标签是多行的,所以我添加 <html>hello<br>world<html>
. 现在的问题是,标签不再向右对齐,而是填充整个布局。
没有html标记时的外观。
html标记的外观
mre公司:
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.WindowEvent;
public class Test extends JPanel {
static JScrollPane scroll_area = new JScrollPane();
static JPanel panel = new JPanel();
static JButton btn = new JButton("Add");
private static final Color lbl_color = new Color(171, 171, 171);
private static final EmptyBorder lbl_padding = new EmptyBorder(10, 10,10, 10);
Test(){
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
scroll_area.getViewport().add(panel);
scroll_area.createVerticalScrollBar();
scroll_area.createHorizontalScrollBar();
add(scroll_area);
add(btn);
btn.addActionListener(e -> addText());
setSize(300, 30);
}
public static void addText(){
String text = "<html><font color='#F9F6F6'>Hello world <br> Welcome to Earth</font></html>";
// String text = "Hello world Welcome to Earth";
JLabel mess_lbl = new JLabel(text, JLabel.RIGHT);
mess_lbl.setOpaque(true);
mess_lbl.setBackground(lbl_color);
mess_lbl.setAlignmentX(Component.RIGHT_ALIGNMENT);
panel.add(mess_lbl);
panel.add(Box.createRigidArea(new Dimension(0, 5)));
panel.updateUI();
}
public static void main(String[] args){
JFrame frame = new JFrame();
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
frame.add(new Test());
frame.setSize(500, 300);
frame.setVisible(true);
}
}
我想我的多行标签的右侧布局如图1所示。
1条答案
按热度按时间omhiaaxx1#
我没有太多的工作经验
BoxLayout
,所以您可能希望等待,看看其他人是否有任何想法或建议。但只要一点点努力,我就可以用一个GridBagLayout
相反