Java/Swing JFC/Cursor

Материал из Java эксперт
Перейти к: навигация, поиск

Change Cursor in a thread for animation

  
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Main implements Runnable, ActionListener {
  private boolean animate;
  private Cursor[] cursors = new Cursor[] { Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR),
      Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR) };
  private JFrame frame;
  public Main(JFrame frame) {
    animate = false;
    this.frame = frame;
  }
  public void run() {
    int count = 0;
    while (animate) {
      try {
        Thread.currentThread().sleep(200);
      } catch (Exception ex) {
      }
      frame.setCursor(cursors[count % cursors.length]);
      count++;
    }
    frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
  }
  public void actionPerformed(ActionEvent evt) {
    JButton button = (JButton) evt.getSource();
    if (animate) {
      button.setText("Start Animation");
      animate = false;
    } else {
      animate = true;
      button.setText("Stop Animation");
      new Thread(this).start();
    }
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    JButton button = new JButton("Start Animation");
    button.addActionListener(new Main(frame));
    frame.getContentPane().add(button);
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
  public static void p(String str) {
    System.out.println(str);
  }
}





Change the cursor shape

  
import java.awt.Cursor;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main extends JFrame {
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        Main mainForm = new Main();
        mainForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainForm.setSize(250, 250);
        Cursor cursor = new Cursor(Cursor.HAND_CURSOR);
        mainForm.setCursor(cursor);
        mainForm.pack();
        mainForm.setVisible(true);
      }
    });
  }
}





Changing the Cursor

 
import java.awt.Button;
import java.awt.ruponent;
import java.awt.Cursor;
import javax.swing.JFrame;
public class Main {
  public static void main() {
    Component comp = new Button("OK");
    Cursor cursor = comp.getCursor();
    comp.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    JFrame frame = new JFrame();
    frame.add(comp);
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}