the five top rows of the oval are erased. why?

这一生的挚爱 提交于 2019-12-11 02:35:11

问题


I'm really confused, I tried setting the oval to be exactly inside the red JPanel and the oval went 5 pixels too low. I tried to change y1 to -5 so it would be exactly in the JPanel, the oval moved to the right place but the five top rows of the oval were erased why did these things happen? and how do I place the oval in the middle of the JPanel?

package il.co.atlantis;

import javax.swing.*;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;


public class PanelExample_Extended{

public static final int WID = 20, HEI = 20;
public static int x1 = 0, y1 = -5;

public class MyGraphics extends JComponent {

    private static final long serialVersionUID = 7526472295622776147L;

    MyGraphics() {
        setPreferredSize(new Dimension(20,20));
    }

    public void paintComponent(Graphics g){
        super.paintComponents(g);
        g.setColor(Color.blue);
        g.fillOval(x1, y1, WID, HEI);
    }

}

 public JPanel createContentPane (){

    JPanel totalGUI = new JPanel();
    totalGUI.setLayout(null);

    JPanel redPanel = new JPanel();
    redPanel.setBackground(Color.red);
    redPanel.setLocation(10, 10);
    redPanel.setSize(20,20);
    MyGraphics tr = new MyGraphics();
    tr.setLocation(0, 0);
    redPanel.add(tr);
    totalGUI.add(redPanel);

    JPanel bluePanel = new JPanel();
    bluePanel.setBackground(Color.blue);
    bluePanel.setLocation(220, 10);
    bluePanel.setSize(50, 50);
    totalGUI.add(bluePanel);

    totalGUI.setOpaque(true);
    return totalGUI;
}

private static void createAndShowGUI() {

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("[=] ??? [=]");


    PanelExample_Extended demo = new PanelExample_Extended();
    frame.setContentPane(demo.createContentPane());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(290, 100);
    frame.setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}
}

回答1:


If you start drawing at -5, you're drawing off of the JComponent, so it makes sense that that portion of the image won't show. I think that your problem stems from trying to use absolute positioning (a thing to avoid) on a JPanel that by default uses FlowLayout.

If you describe better what you're trying to do and perhaps give us images of what you want, we may be able to help better.

Try giving your red JPanel a BorderLayout and seeing what happens.

  JPanel redPanel = new JPanel(new BorderLayout());

But most important, please read up on and understand the layout managers.



来源:https://stackoverflow.com/questions/19575849/the-five-top-rows-of-the-oval-are-erased-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!