在我的应用程序中,我需要自动换行标签,它包含在JPanel(带GridBagLayout)中,而JPanel又包含在JScrollPane中,JScrollPane包含在可调整大小的JFrame中。文本应始终与Scrollpane允许的一样宽(即一次完全可见)。我已经尝试了很多东西:
作为参考,这里是我的Panel类的源代码,没有任何包装:
public class ProgPanel extends JPanel {
/**
* Create the panel.
*/
public ProgPanel() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0};
gridBagLayout.rowHeights = new int[]{59, 0, 0};
gridBagLayout.columnWeights = new double[]{1.0};
gridBagLayout.rowWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
JLabel lblName = new JLabel("Long, long text taht needs to be wrapped, because it is displayed in a very big font on a kindof small screen, bla bla bla bhlergh lol rofl 1337");
GridBagConstraints gbc_lblName = new GridBagConstraints();
gbc_lblName.gridwidth = 2;
gbc_lblName.anchor = GridBagConstraints.WEST;
gbc_lblName.insets = new Insets(0, 0, 5, 0);
gbc_lblName.gridwidth = 1;
gbc_lblName.gridx = 0;
gbc_lblName.gridy = 0;
add(lblName, gbc_lblName);
lblName.setBorder(new EmptyBorder(10, 5, 0, 10));
lblName.setIconTextGap(10);
lblName.setIcon(new ImageIcon("someicon.png"));
lblName.setFont(getFont().deriveFont(Font.BOLD+Font.ITALIC, 48));
}
}
编辑:这是使用JTextArea的实现,它只会增加宽度,但不会缩小:https://pastebin.com/egMXfwK1(由于长度较长且烦人的SO格式化而导致的Pastebin)
EDIT2:以下是一些显示问题的图片:http://imgur.com/a/mhtV9