问题描述
我在 var matchingValue = [];
var unMatchingValue = [];
for(var i = 0; i < this.productDoc.length; i++)
{
for(var j = 0; j < this.fileList.length; j++)
{
if(this.productDoc[i].name == this.fileList[j])
{
this.matchingValue[i].push(this.productDoc[i].name);
//this will push the matching element from the productDoc
//in the new array matchingValue
}
else if(this.product[i].name != this.fileList[j])
{
this.unMatchingValue[i].push(this.product[i].name);
}
}
}
中有 Jlabels
,它们向右对齐。我希望标签是多行的,所以我添加了 JSsrollPane
。现在的问题是标签不再向右对齐,而是填充了整个布局。
没有 html 标签的样子。
html 标签的外观
MRE:
<html>hello<br>world<html>
我希望我的多行标签位于布局的右侧,如图 1 所示。
解决方法
我对 BoxLayout
没有太多经验,因此您可能需要等待,看看其他人是否有任何想法或建议。但是只需要一点点努力,我就可以使用 GridBagLayout
来代替
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.WindowEvent;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
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);
private JPanel filler = new JPanel();
Test() {
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(4,4,0);
gbc.weighty = 1;
panel.add(filler,gbc);
scroll_area.getViewport().add(panel);
scroll_area.createVerticalScrollBar();
scroll_area.createHorizontalScrollBar();
add(scroll_area);
add(btn);
btn.addActionListener(e -> addText());
setSize(300,30);
}
private int counter;
public void addText() {
counter += 1;
String text = "<html><font color='#F9F6F6'>Hello world <br> Welcome to Earth " + counter + "</font></html>";
// String text = "Hello world Welcome to Earth";
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.EAST;
gbc.weightx = 1.0;
gbc.insets = new Insets(4,0);
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,gbc,panel.getComponentCount() - 1);
//panel.add(Box.createRigidArea(new Dimension(0,5)));
panel.revalidate();
panel.repaint();
}
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);
}
}