有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JScrollPane和GridBagLayout

我想创建两个固定大小的不可编辑文本框(每个文本框只包含一行),但我希望它们可以滚动(仅水平),因为我知道它们包含的文本非常长。我希望它们位于我在下面定义的两个按钮下方,并且我希望每个文本框位于它们自己的行中

问题是,所有内容都显示出来,按钮按预期工作,但文本框不会滚动,尽管我可以通过某种方式拖动并选择框中其他不可见的文本。我不知道标签是否可以滚动,它们是更好的选择吗

代码:

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;
}

共 (1) 个答案

  1. # 1 楼答案

    1. 永远不要使用setPreferredSize!这覆盖了JScrollPane需要的信息,以便决定如何滚动组件。有关更多详细信息,请参见Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?。相反,使用JTextArea(int, int)构造函数为JScrollPane提供提示,例如JTextArea master = new JTextArea(1, 20);。超过20字符的任何文本将导致JScrollPane显示水平滚动条
    2. 不要同时将JTextAreaJScrollPane添加到容器中。添加JTextArea会自动将其从JScrollPane中删除,这不是您想要的
    3. 使用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的上下文中创建和修改的。有关详细信息,请参见Initial Threads