2015-01-07 1 views
0

특정 buttonactionPerformed() 메서드가 실행되는 동안 현재 내 JFrame에 표시된 커서를 "작업 완료 중입니다"와 같은 텍스트로 변경하려고합니다. 내가 찾은 유일한 해결책은 Cursor을 내 원하는 텍스트가 포함 된 Image으로 변경하는 것입니다. 코드는 다음과 같습니다 :이 코드커서로 텍스트 변경/표시

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Cursor; 
import java.awt.Dimension; 
import java.awt.Graphics2D; 
import java.awt.Point; 
import java.awt.Toolkit; 
import java.awt.event.ActionEvent; 
import java.awt.geom.Ellipse2D; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 
import java.nio.file.Paths; 
import javax.imageio.ImageIO; 
import javax.swing.AbstractAction; 
import javax.swing.JButton; 
import javax.swing.JFrame; 

public class Hasikome extends JFrame{ 

static Cursor cursor; 

private static final long serialVersionUID = 1L; 

public static void main(String[] args) { 

     final Hasikome hasi = new Hasikome(); 
     hasi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     hasi.setSize(new Dimension(1200, 1200)); 
     hasi.setPreferredSize(new Dimension(500, 500)); 
     Toolkit kit = Toolkit.getDefaultToolkit(); 
     Dimension dim = kit.getBestCursorSize(16, 16); 
     BufferedImage buffered = null; 
     try { 
      buffered = ImageIO.read(new File(Paths.get("").toAbsolutePath().toString() + "\\belge.png")); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     java.awt.Shape circle = new Ellipse2D.Float(0, 0, dim.width - 1, dim.height - 1); 
     Graphics2D g = buffered.createGraphics(); 
     g.setColor(Color.BLUE); 
     g.draw(circle); 
     g.setColor(Color.RED); 
     hasi.add(new JButton(new AbstractAction() { 

      private static final long serialVersionUID = 1L; 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       hasi.setCursor(cursor); 
       try { 
        Thread.sleep(10000); 
       } catch (InterruptedException e1) { 
        e1.printStackTrace(); 
       } finally { 
        hasi.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); 
       } 
      } 
     }), BorderLayout.NORTH); 
     int centerX = (dim.width - 1) /2; 
     int centerY = (dim.height - 1)/2; 
     g.drawLine(centerX, 0, centerX, dim.height - 1); 
     g.drawLine(0, centerY, dim.height - 1, centerY); 
     g.dispose(); 
     cursor = kit.createCustomCursor(buffered, new Point(centerX, centerY), "myCursor"); 
     hasi.pack(); 
     hasi.setVisible(true); 
    } 
} 

문제는이 라인은 항상 Windows에 크기 32 × 32로 Cursor를 생성하고 플랫폼에 의존 Dimension dim = kit.getBestCursorSize(16, 16);이다. 32x32 이상 값을 사용할 수 없으면 cursor = kit.createCustomCursor(buffered, new Point(centerX, centerY), "myCursor"); 행에 대해 예외가 발생합니다. 그리고 합리적으로 긴 텍스트 (250x16)를 사용하기 때문에 text imageCursor으로 올바르게 표시 할 수 없습니다.

이 솔루션은 필연적으로 사용자에게 Cursor으로 텍스트를 표시하고 일부는 ButtonactionPerformed() 메서드가 실행되는 동안 필요하지 않습니다. 내가 이것을 할 수있는 방법이 있습니까? 미리 감사드립니다.

답변

3

한 가지 방법으로 Disabled Glass Pane을 확인하십시오.

If는 "대기"커서를 사용하는 동안 반투명 배경에 칠해진 텍스트로 Glass Pane을 표시 할 수 있습니다.

1

"Please wait"텍스트를 반드시 사용해야하는 경우가 아니라면 컴퓨터에 내장 된로드 아이콘을 사용하는 것이 훨씬 쉽습니다. 사용하는 경우 :

hasi.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); 
doProcessing(); 
hasi.setCursor(Cursor.getDefaultCursor()); 

동일한 효과가 있어야합니다.

+0

이것은 올바른 생각이지만 setCursor 함수 주위에서 SwingUtilities.invokeLater를 사용해야하고 비 -ui 스레드에서 doProcessing()을 수행해야합니다. – ControlAltDel

+0

선택 사항이 내 것이었을 경우에만 이것도 사용했습니다. 그러나 요구 사항은 위의 내 질문에 대한 답변을 찾기 위해 나를 이끌었다. 이 모든 답변과 내가 찾고있는 답변은 운영상의 차이가 있지만 시각적 인 차이는 없습니다. – halil

1

UI 스레드를 차단 하시겠습니까?

어쨌든 가장 좋은 방법은 JLayeredPane을 사용하고 JLayeredPane의 모달 레이어에서 JLabel (사용자가 직접 크기를 설정해야 함)을 팝업 한 다음 작업이 완료되면 제거하는 것입니다 .

+0

주제에 관심이있는 사용자를 위해 [여기] (http://alvinalexander.com/java/java-custom-mouse-cursor-xy-coordinates-position)에서 찾은 답에 대한 예제가 있습니다. – halil

0

이 대답하지 않습니다,하지만 어쩌면 당신이 원하는 것을 할 수 있습니다

단지 아이디어
package com.stackoverflow.questions; 

import java.awt.Color; 
import java.awt.Cursor; 
import java.awt.FlowLayout; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Point; 
import java.awt.RenderingHints; 
import java.awt.Toolkit; 
import java.awt.event.ActionEvent; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import java.awt.image.BufferedImage; 
import javax.swing.AbstractAction; 
import javax.swing.JButton; 
import javax.swing.JComponent; 
import javax.swing.JFrame; 
import javax.swing.SwingUtilities; 
import javax.swing.SwingWorker; 

/** 
* Just an idea for the Stackoverflow question http://stackoverflow.com/questions/27822671 
*/ 
public class SO27822671 extends JFrame { 

    /** 
    * The Glasspane on which we'll draw the "please wait..." thing. 
    */ 
    private MyGlassPane myGlassPane; 

    /** 
    * Blank cursor to hide the cursor. 
    */ 
    private final Cursor blankCursor; 

    /** 
    * Init. 
    */ 
    public SO27822671() { 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    setBounds(300, 300, 400, 400); 

    myGlassPane = new MyGlassPane(); 
    setGlassPane(myGlassPane); 

    getContentPane().setLayout(new FlowLayout()); 
    getContentPane().add(new JButton(new AbstractAction("Click Me!") { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
     doMyStuff(); 
     } 
    })); 

    // http://stackoverflow.com/a/1984117/3366578 
    blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(
     new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB), new Point(0, 0), "blank cursor"); 
    } 

    /** 
    * Do the heavy stuff. 
    */ 
    private void doMyStuff() { 
    // show our glasspane 
    myGlassPane.setVisible(true); 

    // save the current cursor 
    final Cursor currentCursor = getCursor(); 

    // hide the cursor 
    setCursor(blankCursor); 

    new SwingWorker<Void, Void>() { 

     @Override 
     protected Void doInBackground() throws Exception { 
     // hard work here 
     Thread.sleep(2000); 
     return null; 
     } 

     @Override 
     protected void done() { 
     try { 
      get(); 
     } 
     catch (Exception e) { 
      // do your exception handling here 
      e.printStackTrace(); 
     } 
     finally { 
      // hide our glasspane 
      myGlassPane.setVisible(false); 

      // restore the cursor 
      setCursor(currentCursor); 
     } 
     } 
    }.execute(); 
    } 

    /** 
    * This is our glasspane. 
    */ 
    class MyGlassPane extends JComponent { 

    /** 
    * To save the mouse X position. 
    */ 
    private int mouseXPosition; 

    /** 
    * To save the mouse Y position. 
    */ 
    private int mouseYPosition; 

    /** 
    * The text to show. 
    */ 
    private String text = "Please wait..."; 

    /** 
    * Init. 
    */ 
    public MyGlassPane() { 
     // to get the cursor position 
     MouseAdapter mouseAdapter = new MouseAdapter() { 

     @Override 
     public void mouseMoved(MouseEvent e) { 
      computeMousePositionAndRepaint(e); 
     } 

     @Override 
     public void mouseEntered(MouseEvent e) { 
      computeMousePositionAndRepaint(e); 
     } 
     }; 

     addMouseMotionListener(mouseAdapter); 
     addMouseListener(mouseAdapter); 
    } 

    /** 
    * Compute the mouse position and invoke repaint on our glasspane. 
    * @param e 
    */ 
    private void computeMousePositionAndRepaint(MouseEvent e) { 
     mouseXPosition = e.getX(); 
     mouseYPosition = e.getY(); 
     repaint(); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     // draw here what you want instead 
     int textHeight = g.getFontMetrics().getHeight(); 
     int textWidth = g.getFontMetrics().stringWidth(text); 
     int textDescent = g.getFontMetrics().getDescent(); 

     int x = mouseXPosition - textWidth/2; 
     int y = mouseYPosition - textHeight/2; 

     g.setColor(Color.white); 
     g.fillRect(x - 4, y - 4, textWidth + 8, textHeight + 8); 

     ((Graphics2D) g).setRenderingHint(
      RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
     g.setColor(Color.black); 
     g.drawString(text, x, y + textHeight - textDescent); 
    } 
    } 

    public static void main(String[] args) { 
    SwingUtilities.invokeLater(new Runnable() { 

     @Override 
     public void run() { 
     new SO27822671().setVisible(true); 
     } 
    }); 
    } 
} 

.

관련 문제