@Override public void actionPerformed(ActionEvent ae) { this.add(lab1); validate(); repaint(); }
this.addActionListener(this);
this.addActionListener(this);
Vous n’avez pas trouvé la réponse que vous recherchez ?
Posez votre questiont.addActionListener(this);
import java.awt.BorderLayout; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.*; public class MainFrame extends JFrame { /** * */ private static final long serialVersionUID = -2784991357311304465L; // Simple Object class used to add our MainPanel to a JFrame so that it can // be displayed without the use of an applet. MainPanel mPanel,mPanel2; MainFrame() { setTitle("Ball animation"); Container content = getContentPane(); JPanel test = new JPanel(new FlowLayout()); setSize(100, 100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.add(new MainPanel()); // add MainPanel JPanel to JFrame content.add(test, BorderLayout.WEST); pack(); setVisible(true); // show class } public static void main(String[] args) { new MainFrame(); } }
//required libraries: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import javax.swing.*; public class MainPanel extends JPanel { // inherit JPanel Image ballImage; // Reserve memory for Image ballImage; int i = 0; // Constructor:----------------------------------------------------- public MainPanel() { ImageIcon ball_IMG_ICON = new ImageIcon("ball.png"); ballImage = ball_IMG_ICON.getImage(); // get ImageIcon ball_IMG_ICON and // store it in Image ballImage prepareImage(ballImage, this); setDoubleBuffered(true); setBorder(BorderFactory.createTitledBorder("EnOcean")); setSize(100,100); new Timer(1000, paintTimer).start(); } // ---------------------------------------------------------------- public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D) g; g2d.drawImage(ballImage, 10, 10, this); //Draws the ball Image at the correct X and Y co-ordinates. Toolkit.getDefaultToolkit().sync(); // necessary for linux users to draw and animate image correctly g.dispose(); } Action paintTimer = new AbstractAction() { // functionality of our timer: public void actionPerformed(ActionEvent e) { if ( i== 0){ ImageIcon ball_IMG_ICON = new ImageIcon("ball.png"); ballImage = ball_IMG_ICON.getImage(); // get ImageIcon ball_IMG_ICON and // store it in Image ballImage i++; } else if (i ==1){ ImageIcon ball_IMG_ICON = new ImageIcon("ball2.png"); ballImage = ball_IMG_ICON.getImage(); // get ImageIcon ball_IMG_ICON and // store it in Image ballImage i = 0; } repaint(); } }; }
@Override public void paintComponent(Graphics g){ if(image!=null){ Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.drawImage(image, 0, 0, getWidth(), getHeight(), null); } }