OffsetSample.java Source code

Java tutorial

Introduction

Here is the source code for OffsetSample.java

Source

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.BoundedRangeModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class OffsetSample {
    public static void main(String args[]) {
        JFrame frame = new JFrame("Offset Example");
        Container content = frame.getContentPane();
        JPanel panel = new JPanel(new BorderLayout());
        JLabel label = new JLabel("Name: ");
        label.setDisplayedMnemonic(KeyEvent.VK_N);
        final JTextField textField = new JTextField();
        label.setLabelFor(textField);
        panel.add(label, BorderLayout.WEST);
        panel.add(textField, BorderLayout.CENTER);
        content.add(panel, BorderLayout.NORTH);
        JButton button = new JButton("Get Offset");
        ActionListener actionListener = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                System.out.println("Offset: " + textField.getScrollOffset());
                System.out.println("Visibility: " + textField.getHorizontalVisibility());
                BoundedRangeModel model = textField.getHorizontalVisibility();
                int extent = model.getExtent();
                textField.setScrollOffset(extent);
            }
        };
        button.addActionListener(actionListener);
        content.add(button, BorderLayout.SOUTH);
        frame.setSize(250, 150);
        frame.setVisible(true);
    }
}