Mam problem z metodą repaint()
w moim kodzie Java. Chcę to nazwać w innym class
, ale nie mogę, coś w ogóle nie działa. Szukałem na forach, ale nic nie było w stanie mi pomóc.Metoda Repaint() wywoływania w innej klasie
My głównaclass
:
public class Main {
public static Main main;
public static JFrame f;
public Main(){
}
public static void main(String[] args) {
main = new Main();
f = new JFrame();
Ball b = new Ball();
f.getContentPane().setBackground(Color.GRAY);
f.add(b);
f.setSize(500, 500);
f.setLocationRelativeTo(null);
f.setTitle("Test");
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.addMouseMotionListener(b);
f.addKeyListener(new Key());
}
}
Ballclass
gdzie stworzyłem 2DGraphics dla ruchomych kształtach:
public class Ball extends JLabel implements MouseMotionListener{
public Ball(){
}
public static double x = 10;
public static double y = 10;
public static double width = 40;
public static double height = 40;
String nick;
boolean isEllipse = true;
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if(isEllipse){
Ellipse2D e2d = new Ellipse2D.Double(x, y, width, height);
g2d.setColor(Color.RED);
g2d.fill(e2d);
}
else{
Rectangle2D r2d = new Rectangle2D.Double(x, y, width, height);
g2d.setColor(Color.GREEN);
g2d.fill(r2d);
}
}
@Override
public void mouseDragged(MouseEvent e) {
isEllipse = false;
x = e.getX() - 30;
y = e.getY() - 40;
this.repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
x = e.getX() - 30;
y = e.getY() - 40;
isEllipse = true;
this.repaint();
}
}
I Kluczoweclass
gdzie kładę KeyListener
dla przesunąć kształty naciskanie klawisza:
public class Key extends Ball implements KeyListener {
public Key() {
}
@SuppressWarnings("static-access")
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W){
super.x += 10;
super.repaint();
System.out.println("x: " + super.x);
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
Ale coś jest nie tak z tym kodem: Super metoda nie działa dla Keyclass
. Wszystko w Piłkaclass
działa dobrze. Gdzie jest problem?
Och, dziękuję, teraz to działa. :) Używam KeyListener, ponieważ nie zamierzam zrobić czegoś dużego, w rzeczywistości nie używam "czystej" Javy (bez rozszerzonych bibliotek dla wtyczek do gier) od 2014 roku i teraz muszę o tym przypominać od początku . :RE – McDaniel