我真的很困惑,我尝试将椭圆设置为恰好在红色JPanel内部,并且椭圆太低了5个像素。我试图将y1更改为-5,以便恰好在JPanel中,椭圆移动到正确的位置,但是椭圆的前五行被删除了,为什么会发生这些事情?以及如何将椭圆形放置在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();
        }
    });
}
}

最佳答案

如果从-5开始绘制,则是从JComponent进行绘制,因此有意义的是图像的该部分不会显示。我认为您的问题源于试图在默认使用FlowLayout的JPanel上使用绝对定位(避免发生的事情)。

如果您能更好地描述您要做什么,并向我们提供您想要的图像,我们可能会提供更好的帮助。

尝试给您的红色JPanel一个BorderLayout,看看会发生什么。

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


但最重要的是,请继续阅读并了解布局管理器。

09-30 14:17
查看更多