문제가있어서 해결할 수 없습니다. 나는 여러 개의 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);
}
}
[MCVE] (http://stackoverflow.com/help/mcve)를 만들면 더 빨리 답변을 얻을 수 있습니다. 링크에서 정확히 무엇이 의미하는지 확인하십시오. 예, 시간을내어 쓰려면 1 시간 정도 걸리지 만, (a) 프로그램을 조정하면 무엇이 잘못되었는지 알 수 있고 (b) 더 쉽게 실행하고 도움을 줄 수 있습니다. – RealSkeptic
[여러 JFrames 사용, 좋고 나쁜 연습?] (http://stackoverflow.com/q/9554636/418556) –