当我将组件的大小设置为超出组件位置的x和y时,它们都会显示出来,否则它们就不会出现.
这是我的代码:
public class AdamakPogram{
public static void main(String[] args) {
PlayGround playGround = new PlayGround();
Adamak ad1 = new Adamak();
Adamak ad2 = new Adamak();
ad1.setLocation(100,100);
ad2.setLocation(150, 100);
ad1.addMouseListener(new FocusListener(ad1));
ad1.addKeyListener(new ArrowListener(ad1));
playGround.addPerson(ad1);
ad2.addMouseListener(new FocusListener(ad2));
ad2.addKeyListener(new ArrowListener(ad2));
playGround.addPerson(ad2);
}
}
我的PlayGround课程:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class PlayGround extends JFrame{
private static final long serialVersionUID = 1L;
private JPanel zone;
public PlayGround() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
setResizable(false);
zone = new JPanel();
zone.setBorder(new EmptyBorder(5, 5, 5, 5));
zone.setBounds(100, 100, 800, 600);
setContentPane(zone);
zone.setLayout(null);
setVisible(true);
}
public void addPerson(Adamak adamak){
zone.add(adamak);
revalidate();
repaint();
}
public JPanel getZone() {
return zone;
}
public void setZone(JPanel zone) {
this.zone = zone;
}
}
我的adamak(自定义组件)类:
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JComponent;
public class Adamak extends JComponent {
private static final long serialVersionUID = 1L;
@Override
protected void paintComponent(Graphics arg0) {
super.paintComponent(arg0);
Point point = getLocation();
arg0.drawRect(point.x-10, point.y-10, 20, 50);//drawing stomach
arg0.drawLine(point.x+10,point.y, point.x+20, point.y+50);//drawing right hand
arg0.drawLine(point.x-10, point.y, point.x-20, point.y+50);//drawing left hand
arg0.drawLine(point.x, point.y-10, point.x, point.y-20);//drawing neck
arg0.drawLine(point.x-5, point.y+40, point.x-5, point.y+100);//drawing left leg
arg0.drawLine(point.x+5, point.y+40, point.x+5, point.y+100);//drawing right leg
arg0.drawOval(point.x-10, point.y-40, 23, 20);//drawing head
arg0.drawRect(point.x-20, point.y-40, 40, 140);
}
public void moveRight(){
Point point = getLocation();
if((point.x+1-20) < 710){
setLocation(new Point(point.x+1, point.y));
setBounds(point.x-20,point.y-40,710-40,461-140);
repaint();
}
}
public void moveLeft(){
Point point = getLocation();
if((point.x-1-20) > 0){
setLocation(new Point(point.x-1,point.y));
setBounds(point.x-20,point.y-40,710-40,461-140);
repaint();
}
}
public void moveUp(){
Point point = getLocation();
if((point.y-1-40) > 0){
setLocation(new Point(point.x,point.y-1));
setBounds(point.x-20,point.y-40,710-40,461-140);
repaint();
}
}
public void moveDown(){
Point point = getLocation();
if((point.y+1-100) < 461){
setLocation(new Point(point.x,point.y+1));
setBounds(point.x-20,point.y-40,710-40,461-140);
repaint();
}
}
}
任何帮助,将不胜感激.