ari*_*rik 5 java scroll jpanel jscrollpane
我有一个内部非常高的JPanel的JScrollPane,它是动态更改的,项目在其末尾附加.我想要的是滚动到前面提到的JScrollPane的底部,以便新添加的项目立即可见(它们不会直接附加到滚动窗格,而是附加到其JPanel,并且是私有对象,所以不能引用.
我怎样才能让滚动窗格滚动到最底部?提前致谢!
And*_*son 16
JComponent.scrollRectToVisible(Rectangle)
.在JPanel
实例上调用它.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ScrollToNewLabel {
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JPanel gui = new JPanel(new BorderLayout(3,3));
final JPanel panel = new JPanel(new GridLayout(0,1));
JScrollPane scroll = new JScrollPane(panel);
scroll.setPreferredSize(new Dimension(80,100));
gui.add(scroll, BorderLayout.CENTER);
JButton addLabel = new JButton("Add Label");
gui.add(addLabel, BorderLayout.NORTH);
ActionListener listener = new ActionListener() {
int counter = 0;
public void actionPerformed(ActionEvent ae) {
panel.add(new JLabel("Label " + ++counter));
panel.revalidate();
int height = (int)panel.getPreferredSize().getHeight();
Rectangle rect = new Rectangle(0,height,10,10);
panel.scrollRectToVisible(rect);
}
};
addLabel.addActionListener(listener);
JOptionPane.showMessageDialog(null, gui);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
这例如基于Vincent的回答,即可使用JScrollPane.getVerticalScrollBar()
.setValue(height)
.其中height
是在像素中的面板的优选高度.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ScrollToNewLabel {
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JPanel gui = new JPanel(new BorderLayout(3,3));
final JPanel panel = new JPanel(new GridLayout(0,1));
final JScrollPane scroll = new JScrollPane(panel);
scroll.setPreferredSize(new Dimension(80,100));
gui.add(scroll, BorderLayout.CENTER);
JButton addLabel = new JButton("Add Label");
gui.add(addLabel, BorderLayout.NORTH);
ActionListener listener = new ActionListener() {
int counter = 0;
public void actionPerformed(ActionEvent ae) {
panel.add(new JLabel("Label " + ++counter));
panel.revalidate();
int height = (int)panel.getPreferredSize().getHeight();
scroll.getVerticalScrollBar().setValue(height);
}
};
addLabel.addActionListener(listener);
JOptionPane.showMessageDialog(null, gui);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15222 次 |
最近记录: |