简体   繁体   中英

Why setBackground method can't set the background of my JPanel?

I am trying to build a simple oval slider program. I gave the window's background color orange, but it's not setting the background as orange, rather a gray background. Moreover the slider can't pass the appropriate value. Becaause when I slide to increase the size of the oval, it turns into a strange shape, distracting from it's original oval shape.

This is my complete code:

package drawoval;

import java.awt.Color;
import javax.swing.JFrame;

public class Drawoval {

    public static void main(String[] args) {

        TheWindows tw=new TheWindows();
        tw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        tw.setSize(230,280);
        tw.setVisible(true);

    }


}



package drawoval;

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

import javax.swing.event.*;

public class TheWindows extends JFrame{
   private JSlider slider;
   private Oval myPanel;


    public TheWindows(){
       super("The title");
       myPanel=new Oval();
       myPanel.setBackground(Color.ORANGE);
       slider=new JSlider(SwingConstants.HORIZONTAL,0, 200,10);
       slider.setMajorTickSpacing(10);
       slider.setPaintTicks(true);
       slider.addChangeListener(
       new ChangeListener(){
           public void stateChanged(ChangeEvent e){
               myPanel.setNewD(slider.getValue());

           }

       }

       );
       add(slider,BorderLayout.SOUTH);
       add(myPanel,BorderLayout.CENTER);

    }



}



package drawoval;

import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Oval extends JPanel {

    private int d = 10;

    public void paintComponent(Graphics g) {
        super.paintComponents(g);
        g.fillOval(10, 10, d, d);

    }

    public void setNewD(int newD) {
        d = (newD >= 0 ? newD : 10);
        repaint();

    }

    public Dimension getPreferredDim() {

        return new Dimension(200, 280);

    }

    public Dimension getMinSize() {
        return getPreferredDim();

    }

}

Because your calling super.paintComponents(g); and not super.paintComponent(g) ...not the s at the end of the method name...

Also, I'm not sure what you think getPreferredDim and getMinSize will do, but they won't be called by any API within Swing, I think you mean getPreferredSize and getMinimumSize which will be used by the layout manager to make better decisions about how to layout your component

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM