我真的很困惑,我尝试将椭圆设置为恰好在红色 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();
}
});
}
}