2015-01-17 1 views
0

문제가있어서 해결할 수 없습니다. 나는 여러 개의 JFrames를 가진 프로그램을 만들고 있는데, 팝업이 Android의 토스트로 표시되기를 원했습니다. 저를 돕는 수업을 찾았습니다. 이 클래스에는 ToFast를 만들기 위해 JFrame의 위치를 ​​취하는 메서드가 있습니다. 문제는 내가 JFrame을 개별적으로 실행할 때 Toast가 완벽하게 작동하지만 전체 프로그램을 실행할 때 JFrame이 다른 JFrame을 호출하는 버튼이있는 곳에서 JFrame의 위치를 ​​취하여 Toast를 만드는 메서드는 NullPointerException을 보여줍니다. 매개 변수로 지정된 JFrame이 null입니다. 따라서 위치를 얻을 수는 없지만 개별적으로 작동합니다. 뭐가 잘못 되었 니? 누구든지 나를 도울 수 있을까? 감사.getLocation NullPointerException JFrame

토스트 코드 :

public class Toast extends JDialog { 
private static final long serialVersionUID = -1602907470843951525L; 

public enum Style { 
    NORMAL, SUCCESS, ERROR 
}; 

public static final int LENGTH_SHORT = 3000; 
public static final int LENGTH_LONG = 6000; 
public static final Color ERROR_RED = new Color(121, 0, 0); 
public static final Color SUCCESS_GREEN = new Color(22, 127, 57); 
public static final Color NORMAL_BLACK = new Color(0, 0, 0); 

private final float MAX_OPACITY = 0.8f; 
private final float OPACITY_INCREMENT = 0.05f; 
private final int FADE_REFRESH_RATE = 20; 
private final int WINDOW_RADIUS = 15; 
private final int CHARACTER_LENGTH_MULTIPLIER = 7; 
private final int DISTANCE_FROM_PARENT_TOP = 100; 

private JFrame mOwner; 
private String mText; 
private int mDuration; 
private Color mBackgroundColor = Color.BLACK; 
private Color mForegroundColor = Color.WHITE; 

public Toast(JFrame owner) { 
    super(owner); 
    mOwner = owner; 
} 

private void createGUI() { 
    setLayout(new GridBagLayout()); 
    addComponentListener(new ComponentAdapter() { 
     @Override 
     public void componentResized(ComponentEvent e) { 
      setShape(new RoundRectangle2D.Double(0, 0, getWidth(), 
        getHeight(), WINDOW_RADIUS, WINDOW_RADIUS)); 
     } 
    }); 

    setAlwaysOnTop(true); 
    setUndecorated(true); 
    setFocusableWindowState(false); 
    setModalityType(ModalityType.MODELESS); 
    setSize(mText.length() * CHARACTER_LENGTH_MULTIPLIER, 25); 
    getContentPane().setBackground(mBackgroundColor); 

    JLabel label = new JLabel(mText); 
    label.setForeground(mForegroundColor); 
    add(label); 
} 

public void fadeIn() { 
    final Timer timer = new Timer(FADE_REFRESH_RATE, null); 
    timer.setRepeats(true); 
    timer.addActionListener(new ActionListener() { 
     private float opacity = 0; 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      opacity += OPACITY_INCREMENT; 
      setOpacity(Math.min(opacity, MAX_OPACITY)); 
      if (opacity >= MAX_OPACITY) { 
       timer.stop(); 
      } 
     } 
    }); 

    setOpacity(0); 
    timer.start(); 

    setLocation(getToastLocation()); 
    setVisible(true); 
} 

public void fadeOut() { 
    final Timer timer = new Timer(FADE_REFRESH_RATE, null); 
    timer.setRepeats(true); 
    timer.addActionListener(new ActionListener() { 
     private float opacity = MAX_OPACITY; 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      opacity -= OPACITY_INCREMENT; 
      setOpacity(Math.max(opacity, 0)); 
      if (opacity <= 0) { 
       timer.stop(); 
       setVisible(false); 
       dispose(); 
      } 
     } 
    }); 

    setOpacity(MAX_OPACITY); 
    timer.start(); 
} 

private Point getToastLocation() { 
    System.out.println(mOwner); 
    Point ownerLoc = mOwner.getLocation(); 
    int x = (int) (ownerLoc.getX() + ((mOwner.getWidth() - this.getWidth())/2)); 
    int y = (int) (ownerLoc.getY() + DISTANCE_FROM_PARENT_TOP); 
    return new Point(x, y); 
} 

public void setText(String text) { 
    mText = text; 
} 

public void setDuration(int duration) { 
    mDuration = duration; 
} 

@Override 
public void setBackground(Color backgroundColor) { 
    mBackgroundColor = backgroundColor; 
} 

@Override 
public void setForeground(Color foregroundColor) { 
    mForegroundColor = foregroundColor; 
} 

public static Toast makeText(JFrame owner, String text) { 
    return makeText(owner, text, LENGTH_SHORT); 
} 

public static Toast makeText(JFrame owner, String text, Style style) { 
    return makeText(owner, text, LENGTH_SHORT, style); 
} 

public static Toast makeText(JFrame owner, String text, int duration) { 
    return makeText(owner, text, duration, Style.NORMAL); 
} 

public static Toast makeText(JFrame owner, String text, int duration, 
     Style style) { 
    Toast toast = new Toast(owner); 
    toast.mText = text; 
    toast.mDuration = duration; 

    if (style == Style.SUCCESS) 
     toast.mBackgroundColor = SUCCESS_GREEN; 
    if (style == Style.ERROR) 
     toast.mBackgroundColor = ERROR_RED; 
    if (style == Style.NORMAL) 
     toast.mBackgroundColor = NORMAL_BLACK; 

    return toast; 
} 

public void display() { 
    new Thread(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       createGUI(); 
       fadeIn(); 
       Thread.sleep(mDuration); 
       fadeOut(); 
      } catch (Exception ex) { 
       ex.printStackTrace(); 
      } 
     } 
    }).start(); 
} 

JFrame의 코드 :

public class MenuAtendente extends JFrame { 

private JPanel contentPane; 
private static JLabel lblInfo; 
static MenuAtendente frame; 

/** 
* Launch the application. 
*/ 

public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       frame = new MenuAtendente(); 
       frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

/** 
* Create the frame. 
*/ 
public MenuAtendente() { 
    setTitle("SGTA - <Nome da Academia>"); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    JFrame teste = frame; 
    setBounds(100, 100, 663, 449); 
    setLocationRelativeTo(null); 
    setResizable(false); 
    contentPane = new JPanel(); 
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
    setContentPane(contentPane); 
    contentPane.setLayout(null); 

    JLabel lblMenuAtendente = new JLabel("Menu Atendente"); 
    lblMenuAtendente.setFont(new Font("Tahoma", Font.PLAIN, 17)); 
    lblMenuAtendente.setBounds(22, 11, 165, 28); 
    contentPane.add(lblMenuAtendente); 

    JButton btnCadastrarAluno = new JButton("Cadastrar Novo Aluno"); 
    btnCadastrarAluno.setBounds(10, 75, 213, 84); 
    contentPane.add(btnCadastrarAluno); 
    btnCadastrarAluno.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      CadastroAlunosForm tela; 
      try { 
       tela = new CadastroAlunosForm(); 
       tela.setVisible(true); 
       setVisible(false); 
      } catch (ParseException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 
     } 
    }); 

    JButton btnPerfilDeAlunos = new JButton("Perfil de Alunos"); 
    btnPerfilDeAlunos.setBounds(10, 172, 170, 84); 
    contentPane.add(btnPerfilDeAlunos); 
    btnPerfilDeAlunos.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      try { 
       PerfilUsuario tela = new PerfilUsuario(); 
       tela.setVisible(true); 
       setVisible(false); 
      } catch (ParseException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 

     } 
    }); 

    JButton btnRelatoriosDeAluno = new JButton("Relat\u00F3rios de Alunos"); 
    btnRelatoriosDeAluno.setBounds(10, 277, 225, 84); 
    contentPane.add(btnRelatoriosDeAluno); 
    btnRelatoriosDeAluno.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      System.out.println(frame); 
      Toast.makeText(frame, "Olá", Style.SUCCESS).display(); 

     } 
    }); 

    JButton btnLogout = new JButton("Logout"); 
    btnLogout.setBounds(419, 17, 89, 23); 
    contentPane.add(btnLogout); 
    btnLogout.addActionListener(new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      SessaoUsuario.getInstancia().setUsuarioLogado(null); 
      Login tela = new Login(); 
      tela.setVisible(true); 
      dispose(); 
     } 
    }); 

    lblInfo = new JLabel(""); 
    lblInfo.setBounds(10, 386, 581, 14); 
    contentPane.add(lblInfo); 

    JButton button = new JButton("Alterar Cadastro Aluno"); 
    button.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      AlterarCadastroAlunosForm tela; 
      try { 
       tela = new AlterarCadastroAlunosForm(); 
       tela.setVisible(true); 
       dispose(); 
      } catch (ParseException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 

     } 
    }); 
    button.setBounds(267, 75, 177, 84); 
    contentPane.add(button); 
} 

public static void getLblInfo(String mensagem) { 
    lblInfo.setText(mensagem); 
} 

} 
+0

[MCVE] (http://stackoverflow.com/help/mcve)를 만들면 더 빨리 답변을 얻을 수 있습니다. 링크에서 정확히 무엇이 의미하는지 확인하십시오. 예, 시간을내어 쓰려면 1 시간 정도 걸리지 만, (a) 프로그램을 조정하면 무엇이 잘못되었는지 알 수 있고 (b) 더 쉽게 실행하고 도움을 줄 수 있습니다. – RealSkeptic

+0

[여러 JFrames 사용, 좋고 나쁜 연습?] (http://stackoverflow.com/q/9554636/418556) –

답변

0

당신은 항상 SwingUtilities.getWindowAncestor(component)를 사용하여 표시 구성 요소의 최상위 창 부모를 얻을 수 있습니다. 예를 제쳐두고

Window win = SwingUtilities.getWindowAncestor(someComponent); 
Point ownerLoc = win.getLocation(); 

, 들어

  • 당신은 아마이 프로그램에 하나 이상의 JFrame의를 갖고, 아마도 2 윈도우가 JDialog를해야한다 또는를 통해 JPanel의 전망을 교환 고려하지 않을 CardLayout. 장식되지 않은 창을 표시해야하는 경우 JWindow가 더 좋을지 궁금합니다. 확실하지 않습니다.
  • null 레이아웃을 사용하면 setBounds(...)은 위험한 코드이며 결국 당신을 물릴 수 있습니다. 레이아웃 관리자를 사용하면 구성 요소의 위치와 크기를 쉽게 구성 할 수 있습니다.
  • 백그라운드 스레드의 createGUI, fadeIn 및 fadeOut 메소드에서 표시 방법이 스윙 호출을 할 때 스윙 스레드 안전이 아닙니다. 이를 위해 스윙 타이머를 사용하는 것이 좋습니다. 더 나은, 더 스레드

    import java.awt.Color; 
    import java.awt.EventQueue; 
    import java.awt.GridBagLayout; 
    import java.awt.Point; 
    import java.awt.event.*; 
    import java.awt.geom.RoundRectangle2D; 
    
    import javax.swing.*; 
    import javax.swing.border.*; 
    
    public class FooGui { 
        public static void main(String[] args) { 
         MenuAtendente.main(args); 
        } 
    } 
    
    @SuppressWarnings("serial") 
    class MenuAtendente extends JFrame { 
    
        private JPanel contentPane; 
        private static JLabel lblInfo; 
        static MenuAtendente frame; 
    
        /** 
        * Launch the application. 
        */ 
    
        public static void main(String[] args) { 
         EventQueue.invokeLater(new Runnable() { 
         public void run() { 
          try { 
           frame = new MenuAtendente(); 
           frame.setVisible(true); 
          } catch (Exception e) { 
           e.printStackTrace(); 
          } 
         } 
         }); 
        } 
    
        /** 
        * Create the frame. 
        */ 
        public MenuAtendente() { 
         setTitle("SGTA - <Nome da Academia>"); 
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
         setBounds(100, 100, 663, 449); 
         setLocationRelativeTo(null); 
         setResizable(false); 
         contentPane = new JPanel(); 
         contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
         setContentPane(contentPane); 
         contentPane.setLayout(null); // *** ugh, don't do this. 
    
         JButton btnRelatoriosDeAluno = new JButton("Relat\u00F3rios de Alunos"); 
         btnRelatoriosDeAluno.setBounds(10, 277, 225, 84); 
         contentPane.add(btnRelatoriosDeAluno); 
         btnRelatoriosDeAluno.addActionListener(new ActionListener() { 
    
         @Override 
         public void actionPerformed(ActionEvent e) { 
          //!! 
          System.out.println(frame); 
          Toast.makeText(frame, "Olá", Toast.Style.SUCCESS).display(); 
         } 
         }); 
    
        } 
    
        public static void getLblInfo(String mensagem) { 
         lblInfo.setText(mensagem); 
        } 
    
    } 
    
    class Toast extends JDialog { 
        private static final long serialVersionUID = -1602907470843951525L; 
    
        public enum Style { 
         NORMAL, SUCCESS, ERROR 
        }; 
    
        public static final int LENGTH_SHORT = 3000; 
        public static final int LENGTH_LONG = 6000; 
        public static final Color ERROR_RED = new Color(121, 0, 0); 
        public static final Color SUCCESS_GREEN = new Color(22, 127, 57); 
        public static final Color NORMAL_BLACK = new Color(0, 0, 0); 
    
        private final float MAX_OPACITY = 0.8f; 
        private final float OPACITY_INCREMENT = 0.05f; 
        private final int FADE_REFRESH_RATE = 20; 
        private final int WINDOW_RADIUS = 15; 
        private final int CHARACTER_LENGTH_MULTIPLIER = 7; 
        private final int DISTANCE_FROM_PARENT_TOP = 100; 
    
        private JFrame mOwner; 
        private String mText; 
        private int mDuration; 
        private Color mBackgroundColor = Color.BLACK; 
        private Color mForegroundColor = Color.WHITE; 
    
        public Toast(JFrame owner) { 
         super(owner); 
         mOwner = owner; 
        } 
    
        private void createGUI() { 
         setLayout(new GridBagLayout()); 
         addComponentListener(new ComponentAdapter() { 
         @Override 
         public void componentResized(ComponentEvent e) { 
          setShape(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), 
            WINDOW_RADIUS, WINDOW_RADIUS)); 
         } 
         }); 
    
         setAlwaysOnTop(true); 
         setUndecorated(true); 
         setFocusableWindowState(false); 
         setModalityType(ModalityType.MODELESS); 
         setSize(mText.length() * CHARACTER_LENGTH_MULTIPLIER, 25); 
         getContentPane().setBackground(mBackgroundColor); 
    
         JLabel label = new JLabel(mText); 
         label.setForeground(mForegroundColor); 
         add(label); 
        } 
    
        public void fadeIn() { 
         final Timer timer = new Timer(FADE_REFRESH_RATE, null); 
         timer.setRepeats(true); 
         timer.addActionListener(new ActionListener() { 
         private float opacity = 0; 
    
         @Override 
         public void actionPerformed(ActionEvent e) { 
          opacity += OPACITY_INCREMENT; 
          setOpacity(Math.min(opacity, MAX_OPACITY)); 
          if (opacity >= MAX_OPACITY) { 
           timer.stop(); 
          } 
         } 
         }); 
    
         setOpacity(0); 
         timer.start(); 
    
         setLocation(getToastLocation()); 
         setVisible(true); 
        } 
    
        public void fadeOut() { 
         final Timer timer = new Timer(FADE_REFRESH_RATE, null); 
         timer.setRepeats(true); 
         timer.addActionListener(new ActionListener() { 
         private float opacity = MAX_OPACITY; 
    
         @Override 
         public void actionPerformed(ActionEvent e) { 
          opacity -= OPACITY_INCREMENT; 
          setOpacity(Math.max(opacity, 0)); 
          if (opacity <= 0) { 
           timer.stop(); 
           setVisible(false); 
           dispose(); 
          } 
         } 
         }); 
    
         setOpacity(MAX_OPACITY); 
         timer.start(); 
        } 
    
        private Point getToastLocation() { 
         System.out.println("Here!"); 
         System.out.println(mOwner); 
         Point ownerLoc = mOwner.getLocation(); 
         // !! Window win = SwingUtilities.getWindowAncestor(someComponent); 
         // Point ownerLoc = win.getLocation(); 
         int x = (int) (ownerLoc.getX() + ((mOwner.getWidth() - this.getWidth())/2)); 
         int y = (int) (ownerLoc.getY() + DISTANCE_FROM_PARENT_TOP); 
         return new Point(x, y); 
        } 
    
        public void setText(String text) { 
         mText = text; 
        } 
    
        public void setDuration(int duration) { 
         mDuration = duration; 
        } 
    
        @Override 
        public void setBackground(Color backgroundColor) { 
         mBackgroundColor = backgroundColor; 
        } 
    
        @Override 
        public void setForeground(Color foregroundColor) { 
         mForegroundColor = foregroundColor; 
        } 
    
        public static Toast makeText(JFrame owner, String text) { 
         return makeText(owner, text, LENGTH_SHORT); 
        } 
    
        public static Toast makeText(JFrame owner, String text, Style style) { 
         return makeText(owner, text, LENGTH_SHORT, style); 
        } 
    
        public static Toast makeText(JFrame owner, String text, int duration) { 
         return makeText(owner, text, duration, Style.NORMAL); 
        } 
    
        public static Toast makeText(JFrame owner, String text, int duration, 
         Style style) { 
         Toast toast = new Toast(owner); 
         toast.mText = text; 
         toast.mDuration = duration; 
    
         if (style == Style.SUCCESS) 
         toast.mBackgroundColor = SUCCESS_GREEN; 
         if (style == Style.ERROR) 
         toast.mBackgroundColor = ERROR_RED; 
         if (style == Style.NORMAL) 
         toast.mBackgroundColor = NORMAL_BLACK; 
    
         return toast; 
        } 
    
        public void display() { 
         new Thread(new Runnable() { 
         @Override 
         public void run() { 
          try { 
           createGUI(); 
           fadeIn(); 
           Thread.sleep(mDuration); 
           fadeOut(); 
          } catch (Exception ex) { 
           ex.printStackTrace(); 
          } 
         } 
         }).start(); 
        } 
    } 
    

    편집 :


편집 이것은 코드로 최소한의 예제 프로그램을 만들려고 노력에 지금까지 필자입니다 -safe display() 방법 :

public void display() { 
    final Timer timer = new Timer(mDuration, new ActionListener() { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
     fadeOut(); 
     } 
    }); 
    timer.setRepeats(false); 
    createGUI(); 
    fadeIn(); 
    timer.start(); 
} 
+0

응답 해 주셔서 감사합니다. 하지만 JFrame을 개별적으로 열 때 왜 작동하는지 이해하고 싶었지만 다른 JFrame에서 JFrame을 호출하면 JFrame 프레임 속성이 null입니다. –

+0

@EdvanJunior : 코드를 기반으로 컴파일/실행 가능 버전을 만들려고했을 때 예외를 재생산하지 못했기 때문에 코드를 기반으로 말할 수 없습니다. 더 나은 도움을 얻으려면 문제를 나타내는 최소한의 코드 예제 인 [SSCCE] (http://sscce.org)를 작성하여 게시하여 코드를 압축하십시오. 이렇게하면 코드를 실행하고 수정하고 심지어 수정할 수 있습니다.SSCCE 요구 사항에 대한 많은 중요한 세부 정보를 제공하므로 회신하기 전에 링크를 읽으십시오. –

+0

다음은 코드 저장소 링크입니다. https://github.com/SGTA-BSI/sgta –