I'm trying to create a small program, that I want to change the background slowly while scrolling the scrollbar (JScrollPane). It's like onscroll function in Javascript.
I created the scroll pane and added to it a frame then put some components in it, what I want now, is when the user scrolls, the BG of the scroll pane changes slowly from black to white, when it reaches the bounds of the frame:
This how I created the frame and scroll pane:
public AdminFrame() {
setBounds(20, 20, 1300, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new BorderLayout(0, 0));
JPanel contentPane = new JPanel();
contentPane.setForeground(Color.WHITE);
contentPane.setFont(new Font("Tahoma", Font.BOLD, 11));
contentPane.setBounds(120, 50, 692, 7);
contentPane.setPreferredSize(new Dimension(1300, 1500));
getContentPane().add(contentPane, BorderLayout.CENTER);
contentPane.setLayout(null);
JScrollPane scrollPane=new JScrollPane(contentPane,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBackground(BgColor);
scrollPane.getVerticalScrollBar().setUnitIncrement(25);
}
I tested many ideas, also many block of solutions that I found in the web but nothing works.
Like:
scrollPane.getViewport().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
// TODO Auto-generated method stub
contentPane.setBackground(Color.white);
System.out.println("scorled");
}
} )
Or:
scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
// TODO Auto-generated method stub
scrollPane.setBackground(new Color(BgColor.getRed()-10,BgColor.getBlue()-10,BgColor.getGreen()-10)); //change the background color;
}
});
Introduction
Your "simple" project is not simple in Java. Java is not the same language as JavaScript. Simple things in JavaScript can be incredibly hard to duplicate in Java.
Here's a GUI I put together. This is the initial state.
This is the state with the vertical scroll bar about halfway down.
This is the state with the vertical scroll bar all the way down.
Explanation
Oracle has a nifty tutorial, Creating a GUI With JFC/Swing that will take you through the many many steps to create a Swing GUI. Skip the Netbeans section.
I created a background
JPanel. I placed the backgroundJPanelinside aJScrollPane. I placed theJScrollPaneinside the mainJPanel. I placed the mainJPanelinside aJFrame.I started the Swing application with a call to the
SwingUtilitiesinvokeLatermethod. This method ensures that the Swing components will be created and executed on the Event Dispatch Thread.I used Swing layout managers to layout the Swing components.
Code
Here's the complete runnable code. I made all the classes inner classes so I could post the code as one block.