我真的很困惑,我试着将椭圆形设置在红色的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();
}
});
}
}
使用适当的变量名称“WID”和“HEI”没有多大意义。如果你想让人们阅读你的代码,然后使用可理解的名字。也不要为X,Y使用静态变量。您将永远无法更改您可能使用的其他组件的位置。所有这些属性都属于该类组件的颜色。 – camickr