Swing AdjustmentListener介面

2019-10-16 22:11:22

AdjustmentListener介面用於接收調整事件。處理調整事件的類需要實現此介面。

類宣告

以下是java.awt.event.AdjustmentListener介面的宣告 -

public interface AdjustmentListener
   extends EventListener

介面方法

編號 方法 描述說明
1 void adjustmentValueChanged(AdjustmentEvent e) 調整值的值發生變化時呼叫。

方法繼承

該類從以下介面繼承方法 -

  • java.awt.event.EventListener

AdjustmentListener範例

使用編輯器建立以下Java程式:AdjustmentListenerDemo.java

package com.yiibai.swing.listener;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AdjustmentListenerDemo {
    private JFrame mainFrame;
    private JLabel headerLabel;
    private JLabel statusLabel;
    private JPanel controlPanel;

    public AdjustmentListenerDemo() {
        prepareGUI();
    }

    public static void main(String[] args) {
        AdjustmentListenerDemo swingListenerDemo = new AdjustmentListenerDemo();
        swingListenerDemo.showAdjustmentListenerDemo();
    }

    private void prepareGUI() {
        mainFrame = new JFrame("Java SWING AdjustmentListener範例");
        mainFrame.setSize(400, 400);
        mainFrame.setLayout(new GridLayout(3, 1));

        headerLabel = new JLabel("", JLabel.CENTER);
        statusLabel = new JLabel("", JLabel.CENTER);
        statusLabel.setSize(350, 100);

        mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent) {
                System.exit(0);
            }
        });
        controlPanel = new JPanel();
        controlPanel.setLayout(new FlowLayout());

        mainFrame.add(headerLabel);
        mainFrame.add(controlPanel);
        mainFrame.add(statusLabel);
        mainFrame.setVisible(true);
    }

    private void showAdjustmentListenerDemo() {
        headerLabel.setText("Listener in action: AdjustmentListener");

        JPanel panel = new JPanel();
        JScrollBar scrollbar = new JScrollBar();
        scrollbar.addAdjustmentListener(new CustomAdjustmentListener());

        panel.add(scrollbar);
        controlPanel.add(panel);
        mainFrame.setVisible(true);
    }

    class CustomAdjustmentListener implements AdjustmentListener {
        public void adjustmentValueChanged(AdjustmentEvent e) {
            statusLabel.setText("Adjustment value: " + Integer.toString(e.getValue()));
        }
    }
}

執行上面範例程式碼,得到以下結果:

AdjustmentListener