Java - 通过复选框同步两个滚动条

时间:2018-01-26 23:48:06

标签: java swing actionlistener jscrollpane jscrollbar

下面的代码创建了一个复选框,我想打开/关闭我的两个面板上的同步滚动。最初,当程序运行时,滚动条是独立的。选中复选框后," if"到达语句后,将scrolller2的滚动条设置为scroller1滚动条的模型并将它们连接起来,即它们一起移动。

然而问题是当取消选中该复选框时,意味着我希望滚动条再次独立。我在else语句中的任何内容似乎都没有用。

JCheckBox check = new JCheckBox("Global");

ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
        boolean selected = abstractButton.getModel().isSelected();
        System.out.println(selected);
        if (selected){
            scroller2.getHorizontalScrollBar().setModel(scroller.getHorizontalScrollBar().getModel());
        } else {
            scroller = new JScrollPane(plotPanel);
            scroller2 = new JScrollPane(plotPanel2);
        }
    }
};
check.addActionListener(actionListener);    

1 个答案:

答案 0 :(得分:-2)

此:

// At the top of your file, you'll need this to access the Timer:
using System.Windows.Forms;


public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private static Stopwatch stopwatch = new Stopwatch();
    private static readonly Timer Timer = new Timer { Interval = 100 };

    private void Form1_Load(object sender, EventArgs e)
    {
        btnStartStop.Text = "Start";
        txtVrijeme.Text = stopwatch.Elapsed.ToString("hh\\:mm\\:ss\\.ff");
        Timer.Tick += Timer_Tick;  // This hooks up an event handler for the Tick event
    }

    // This code executes every {Timer.Interval} millisecond when the timer is running
    private void Timer_Tick(object sender, EventArgs e)
    {
        txtVrijeme.Text = stopwatch.Elapsed.ToString("hh\\:mm\\:ss\\.ff");
    }

    // This method handles the button click. It changes the button text and starts
    // or stops the stopwatch, depending on whether the stopwatch is running
    private void btnStartStop_Click(object sender, EventArgs e)
    {
        if (stopwatch.IsRunning)
        {
            stopwatch.Stop();
            Timer.Stop();
            btnStartStop.Text = "Start";
        }
        else
        {
            Timer.Start();
            stopwatch.Start();
            btnStartStop.Text = "Stop";
        }
    }
}

创建两个新的JScrollPanes,但你不做任何事情。理解变量引用的对象更改,这里的scrolller和scroller2 vairables对显示的对象有无效,这个问题得到了引用变量和引用或对象。如果要更改显示的JScrollPane,则必须删除旧的JScrollPane,并将新的JScrollPane添加到GUI。

但你想要这样做。只需给其中一个水平JScrollBars一个新模型,特别是一个新的DefaultBoundedRangeModel。我会使用占用4个整数的构造函数,并从当前模型中获取值,范围,最小值,最大值参数。

例如,像:

scroller = new JScrollPane(plotPanel);
scroller2 = new JScrollPane(plotPanel2);

注意未经测试的代码