我想要创建两个固定大小的不可编辑文本框(每个文本框只包含一行),但我希望它们可以滚动(水平滚动),因为我知道它们包含的文本将非常长。我希望它们位于我在下面定义的两个按钮下面,并且希望每个文本框都位于各自的行中。
问题是,所有的东西都会显示出来,按钮会像预期的那样工作,但是文本框不会滚动,尽管我可以以某种方式拖动并选择框中其他不可见的文本。我不知道标签是否可以滚动,它们会是更好的选择吗?
代码:
public static void main(String[] args)
{
JFrame win = new JFrame("Window");
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setSize(400, 300);
GridBagConstraints c = new GridBagConstraints();
win.setLayout( new GridBagLayout() );
JTextArea master = new JTextArea(1,1);
JTextArea vendor = new JTextArea(1,1);
master.setEditable(false);
vendor.setEditable(false);
master.setPreferredSize( new Dimension(100,20) );
vendor.setPreferredSize( new Dimension(100,20) );
master.setText(/*some really long string*/);
vendor.setText(/*some really long string*/);
JScrollPane mPane = new JScrollPane(master, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
JScrollPane vPane = new JScrollPane(vendor, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
mPane.getHorizontalScrollBar().isVisible();
vPane.getHorizontalScrollBar().isVisible();
JButton one = new JButton("Select");
ActionListener select = new SelectButton(master, vendor);
one.addActionListener(select);
JButton two = new JButton("Run");
c.gridx = 0;
c.gridy = 0;
win.add(one, c);
c.gridx = 1;
c.gridy = 0;
win.add(two, c);
c.gridx = 0;
c.gridy = 1;
win.add(master, c);
win.add(mPane, c);
c.gridx = 0;
c.gridy = 2;
win.add(vendor, c);
win.add(vPane, c);
win.setLocationRelativeTo(null);
win.setVisible(true);
return;
}发布于 2015-03-10 03:16:58
setPreferredSize!这是覆盖JScrollPane需要的信息,以便决定如何滚动组件。有关更多详细信息,请参阅我是否应该避免在Java中使用set(首选的、最大的、最大的、最小的)大小方法?。相反,可以使用JTextArea(int, int)构造函数向JScrollPane提供提示,例如JTextArea master = new JTextArea(1, 20);。任何文本超过20字符将导致JScrollPane显示水平滚动条.JTextArea和JScrollPane添加到容器中。添加JTextArea会自动从JScrollPane中删除它,这不是您想要的。GridBagConstaints#gridwidth控制组件可能展开的列数以帮助修复布局.例如..。
c.gridx = 0;
c.gridy = 1;
c.gridwidth = GridBagConstraints.REMAINDER;
win.add(mPane, c);
c.gridx = 0;
c.gridy = 2;
win.add(vPane, c);我希望这是一个非常简单的例子,如果不是,您应该始终确保您的UI是在EDT上下文中创建和修改的。有关更多细节,请参见初始线程
https://stackoverflow.com/questions/28955518
复制相似问题