java - 将组件添加到 jscrollpane 中的面板后如何从下到上滚动

标签 java swing jscrollpane

我有一个 jscrollpane,我向其中添加了面板,然后在面板内动态添加 jlabel 和 textarea。 动态地将组件添加到面板后,垂直滚动到底部。 我想要的是将垂直滚动带到顶部。这就是我的问题,我该如何解决这个问题,我们将不胜感激。

这是我的代码

import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MyGui1 extends JPanel implements ActionListener {
    /**
     * 
     */

    protected JPanel panel;
    protected JTextArea textarea;
    static JFrame frame;
    JLabel Jlabel = null;

    public MyGui1() {
        // to lay out the container's components in a rectangular grid
        super(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.fill = GridBagConstraints.HORIZONTAL;

        JButton jbutton = new JButton("button");
        jbutton.setActionCommand("button");
        jbutton.addActionListener(this);
        add(jbutton, c);

        c.gridy = 1;
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.BOTH;

        c.weightx = 1.0;
        c.weighty = 1.0;
        setBackground(Color.cyan);
        panel = new JPanel(new GridLayout(0, 1));
        JScrollPane jsp = new JScrollPane(panel);

        jsp.setPreferredSize(new Dimension(300, 300));

        add(jsp, c);
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

    }

    public void actionPerformed(ActionEvent evt) {

        if ("button".equals(evt.getActionCommand())) {
            execute();
        }
    }

    synchronized public void execute() {

        // to remove all the content of panel
        panel.removeAll();
        // to refresh the window
        repaint();

        for (int i = 0; i < 20; i++) {

            Jlabel = new JLabel("Labe1l" + i);
            Jlabel.setVerticalAlignment(SwingConstants.TOP);
            panel.add(Jlabel);

            textarea = new JTextArea(3, 3);
            textarea.setText("sample text ");
            textarea.append("\n");
            textarea.setEditable(false);
            // in order to wrap up the data in text area
            textarea.setLineWrap(true);
            panel.add(textarea, BorderLayout.CENTER);
        }

        frame.revalidate();
    }

    @SuppressWarnings("static-access")
    private static void createAndShowGUI() {
        // Create and set up the window.
        frame = new JFrame("DesktopSearchEngine");
        frame.setLayout(new BorderLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // adding window listener for exit operation
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                JFrame frame = (JFrame) e.getSource();

                int result = JOptionPane.showConfirmDialog(frame,
                        "Are you sure you want to exit the application?",
                        "Exit Application", JOptionPane.YES_NO_OPTION);

                if (result == JOptionPane.YES_OPTION) {

                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                } else if (result == JOptionPane.NO_OPTION) {
                    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                }
            }
        });
        // Add contents to the window GUI part and to perform all operations
        frame.add(new MyGui1());

        // Display the window.
        frame.pack();
        // to keep the frame visible
        frame.setVisible(true);

    }

    public static void main(String[] args) {
        // Schedule a job for the event dispatch thread:
        // creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

}

最佳答案

myScrollPane.getVerticalScrollBar().setValue(0);

如果你想保持在动态添加组件之前的某个位置,你可以保存滚动条值然后重新使用它,如下所示:

int myScrollPanesOldPosition = myScrollPane.getVerticalScrollBar().getValue();
// dynamically add components
myScrollPane.getVerticalScrollBar().setValue(myScrollPanesOldPosition );

关于java - 将组件添加到 jscrollpane 中的面板后如何从下到上滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22939027/

相关文章:

java - 使用 JFileChooser 保存字符串

java - JOptionPane 解析数组

Java Swing JTextArea 行号

java - 无法解析方法 equals(java.lang.Long)

java - Jsoup - 只保留标签并删除所有文本

Java,FileWriter(file, true) 不追加到文件上

java - 我如何调整 jscrollpane 的大小

java - 如何使用 JsonAutoDetect 实现旧 Firebase 中可用的技巧?

java - 在 Java 桌面应用程序中实现 'Send Feedback' 功能

java - JScrollBar 中的 Page Up/Down 事件