任务:使用BoxLayout将一些带有一些文本的JLabel添加到JPanel,然后将此面板添加到JScrollPane以向下滚动该文本标签。
问题:
我设置 text.setMaximumSize(..),但JScrollPane不这么认为并添加水平滚动条。 text.setPreferredSize 限制完美,但我无法使用它,因为需要计算每个标签的高度(可能使用字体大小并获得标签自动断路器),这对我来说很难。
这是代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
public class NewPanel {
private JFrame frame;
private JLabel text;
public NewPanel() {
int formWidth = 700;
int formHeight = 700;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++)
sb.append("Test String ");
String resStr = "<html>" + sb.toString() + "</html>";
text = new JLabel();
text.setText(resStr);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(text);
JScrollPane scrollPane = new JScrollPane(
panel,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
);
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setPreferredSize(new Dimension(formWidth, formHeight));
frame.add(scrollPane);
frame.pack();
//Change max width for label with form resize
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
super.componentResized(e);
resizePanels();
}
@Override
public void componentMoved(ComponentEvent e) {
super.componentMoved(e);
resizePanels();
}
});
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void resizePanels() {
int labelSize = frame.getWidth() - 200;
// - 200 For show that text limited by setMaximumSize
text.setMaximumSize(new Dimension(labelSize, Integer.MAX_VALUE));
//Integer.MAX_VALUE - for unlimited height (maybe exist better way?)
//text.setPreferredSize(new Dimension(labelSize, 1000));
//limit perfect and hide horizontal scroll, but don't think that it better way
//because i need get plane border "back to back" text border,
//so i must count label height (front height + maybe label auto line break place)
//that look like hard way
text.revalidate();
text.repaint();
}
}