Can't change background of a JFrame with JScrollBar?
Hello everyone. I have a 'Grapher' class that extends JComponent that draws some rectangles. I wanted it to have a scrollbar, so I added an instance of the Grapher class into a JScrollBar, added the JScrollBar into a JFrame, and set the frame visible to see my rectangles. I didn't like the gray background so I figured I would be easily able to change it to another color, say red, but however I do this nothing works. Here is a part of my code:
Code:
Grapher component = new Grapher();
component.setPreferredSize(new Dimension(1250, 500));
component.setBackground(Color.red);
JScrollPane scrollBar=new JScrollPane(component,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollBar.setPreferredSize(component.getPreferredSize());
scrollBar.setBackground(Color.red);
JFrame viewFrame = new JFrame("Viewing Window");
viewFrame.setSize(1250, 500);
viewFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
viewFrame.add(scrollBar);
viewFrame.setLocationRelativeTo(null); //makes frame appear in center of screen
viewFrame.getContentPane().setBackground(Color.red);
viewFrame.setVisible(true);
Re: Can't change background of a JFrame with JScrollBar?
Moved from New to Java.
Please use meaningful variable names. That means, don't have a variable named scrollBar that refers to a JScrollPane.
Anything you see in a JScrollPane is the scroll pane's viewport view: in your code snippet, component. If the viewport view is transparent -- doesn't paint its background -- the background of the JScrollPane's JViewport will show. Not the background of the scroll pane nor that of the frame's content pane.
db
Re: Can't change background of a JFrame with JScrollBar?
Thank you very much db, I was able to remove all of the other attempts at coloring the background and replaced it with a single line! I just called the scrollBar.getViewport() method and set the Viewport's color to Red. Thanks again