Hi I'm coding an alarm application.
I have a snooze class which gets called when the alarm sounds. It used to work fine before using JMF.But after using JMF I see only the outer frame of my snooze UI.
I tried starting a new thread for the class but got the same result. I'm pasting here code of the classes in which I think the problem is in.
Please help me solve the problem.
*IsTime class. Which checks whether it is the time to sound alarm. *
package alarm;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class IsTime {
int hrs;
int min;
int sec;
GregorianCalendar clk=new GregorianCalendar();
Calendar gtl= Calendar.getInstance();
mp3 mix=new mp3();
public void makeReady(int h,int m,int s,String ampm){
Calendar c1=Calendar.getInstance();
c1.set(Calendar.HOUR_OF_DAY,h);
c1.set(Calendar.MINUTE, m);
c1.set(Calendar.SECOND,s);
if("PM".equals(ampm)){
c1.set(Calendar.AM_PM, Calendar.PM);
if(Calendar.getInstance().get(Calendar.AM_PM)==Calendar.PM){
System.out.println("now is pm");
if(c1.after(Calendar.getInstance())){
check(c1);
}
c1.set(Calendar.DAY_OF_YEAR,c1.get(Calendar.DAY_OF_YEAR)+1);
check(c1);
}
}
if(Calendar.getInstance().get(Calendar.AM_PM)==Calendar.AM){
System.out.println("now is am");
if(c1.after(Calendar.getInstance())){
check(c1);
}
c1.set(Calendar.DAY_OF_YEAR,c1.get(Calendar.DAY_OF_YEAR)+1);
check(c1);
}
if(Calendar.getInstance().get(Calendar.AM_PM)==Calendar.PM){
c1.set(Calendar.DAY_OF_YEAR,c1.get(Calendar.DAY_OF_YEAR)+1);
check(c1);
}
}
public void check(Calendar ch){
System.out.println("got to check");
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));
System.out.println(ch.get(Calendar.HOUR_OF_DAY));
while(!(Calendar.getInstance().after(ch))){
}
Snooze snz=new Snooze();
snz.start();
mix.start();
}
public void makeReady(int mis){
Calendar sz=Calendar.getInstance();
sz.set(Calendar.SECOND, 0);
sz.set(Calendar.MINUTE, Calendar.getInstance().get(Calendar.MINUTE)+mis);
check(sz);
}
}
*Media class which plays song when it is time *
package alarm;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.media.*;
import java.io.*;
import java.net.URL;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
class mp3 extends Thread
{
private URL url;
private MediaLocator mediaLocator;
private Player playMP3;
static String mp3;
static String mp4;
public mp3()
{
try{
System.out.println(System.getProperty("os.name"));
System.out.println("before"+mp3);
if(System.getProperty("os.name").equals("Linux")){
mp4="file://".concat(mp3);
}
else{
mp4="file:///".concat(mp3);
}
System.out.println(mp4);
this.url = new URL(mp4);
}catch(java.net.MalformedURLException e)
{System.out.println(e.getMessage());}
}
public void run()
{
try{
System.out.println(url);
mediaLocator = new MediaLocator(url);
playMP3 = Manager.createPlayer(mediaLocator);
}catch(java.io.IOException e)
{System.out.println(e.getMessage());
}catch(javax.media.NoPlayerException e)
{System.out.println(e.getMessage());}
playMP3.addControllerListener(new ControllerListener()
{
public void controllerUpdate(ControllerEvent e)
{
if (e instanceof EndOfMediaEvent)
{
playMP3.stop();
playMP3.close();
}
}
}
);
playMP3.realize();
playMP3.start();
}
}
*Snooze class where the real problem is *
package alarm;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Snooze extends Thread implements ActionListener{
JFrame sozef=new JFrame("Snooze");
JLabel tl=new JLabel("After");
JLabel ml=new JLabel("mins");
JComboBox tiec=new JComboBox();
JButton soo=new JButton("Snooze");
JButton stp=new JButton("Stop");
mp3 mi=new mp3();
Snooze sz;
public void run(){
sozef.setSize(500,700);
sozef.setLayout(null);
tl.setBounds(50,50,50,50);
tiec.setBounds(50,90,50,30);
ml.setBounds(120,90,50,50);
soo.setBounds(50,130,90,30);
stp.setBounds(50, 170, 90, 30);
JcAdd(tiec);
sozef.add(tl);
sozef.add(tiec);
sozef.add(ml);
sozef.add(soo);
sozef.add(stp);
soo.addActionListener(this);
sozef.setVisible(true);
sozef.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void JcAdd(JComboBox jc){
for(int i=0;i<=10;i++)
jc.addItem(Integer.toString(i));
}
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==soo){
int ma=Integer.parseInt(tiec.getSelectedItem().toString());
mi.stop();
IsTime sz=new IsTime();
sz.makeReady(ma);
}
mi.stop();
}
} ![this is the frame I see when the snooze is being called][1]
This is not the correct way to implement a delay:
while(!(Calendar.getInstance().after(ch))){
}
In fact, it's going to cause serious problems.
Try calculating the number of milliseconds between your target date and the current time, and passing that value to Thread.sleep. Your computer's case fans will thank you. And it may very well be the case that your busy loop is starving the AWT event thread, thus preventing your frame from showing.
Related
I'm trying to code a plugin where the border follows a player and doubles everytime they get an advancement. The problem is I don't know how to detect when someone gets an advancement and keep it in the same class. Here is the current code.
survivalBorders.class
package sc458.survivalborders;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldBorder;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerAdvancementDoneEvent;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class survivalBorders extends JavaPlugin {
public void onEnable() {
World world = Bukkit.getWorld("survival");
WorldBorder border = world.getWorldBorder();
double borderSize = border.getSize();
while(true) {
if(PlayerAdvancementDoneEvent) {
border.setSize(borderSize*2);
}
}
}
public void onDisable() {
}
}
MoveEvent.class
package sc458.survivalborders;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldBorder;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
public class MoveEvent implements Listener {
public void onMove(PlayerMoveEvent e) {
Player p = e.getPlayer();
World world = Bukkit.getWorld("survival");
WorldBorder border = world.getWorldBorder();
int locX = p.getLocation().getBlockX();
int locZ = p.getLocation().getBlockZ();
border.setCenter(locX, locZ);
}
}
Try to call the PlayerMoveEvent with a Listener and then you can just everytime he moves (event gets triggered) -> set the border again. So basically when his coordinates change, the border will immediantly follow you.
public class MoveEvent implements Listener {
#EventHandler
public void onMove(PlayerMoveEvent e) {
Player p = e.getPlayer();
WorldBorder border = world.getWorldBorder();
int locX = p.getLocation().getBlockX();
int locZ = p.getLocation().getBlockZ();
border.setCenter(locX, locZ);
}
}
Im newbie to Java, how can i handle current player joined the world?
package page.a0x77.kubecraft;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.player.*;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;
#Mod(
modid = Kubecraft.MOD_ID,
name = Kubecraft.MOD_NAME,
version = Kubecraft.VERSION
)
public class Kubecraft {
#SubscribeEvent
public void playerLoggedInEvent(EntityJoinWorldEvent event) {
// ClientCommandHandler.instance.executeCommand(Minecraft.getMinecraft().player, "your command");
System.out.println("TEST");
}
}
I want to make auto auth on player joined, send message to chat on join.
You should use:
#EventBusSubscriber
public static class Class {
#SubscribeEvent
public static void onEvent(EntityJoinWorldEvent event) {
if ((event.getEntity() instanceof PlayerEntity)) {
LogManager.getLogger().info("Joined!");
}
}
}
I thought maybe you'd need the instance of the player to be able to get it to work.
...
#Mod(
modid = Kubecraft.MOD_ID,
name = Kubecraft.MOD_NAME,
version = Kubecraft.VERSION
)
public class Kubecraft {
...
#SubscribeEvent
public static void onEvent(EntityJoinWorldEvent event) {
Timer timer = new Timer(3000, new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
if(!sent) Minecraft.getMinecraft().player.sendChatMessage("/setblock ~ ~ ~ grass");
sent = true;
}
});
timer.setRepeats(false); // Only execute once
if(!sent) {
timer.start();
}
}
}
...
I am building a simple program with one button. I want to play the "zvuk.wav" file after I click on the button. It's not working though and I cant solve why. When I click the button, nothing happens. The zvuk.wav file is in the src file with the classes.
Here is my first class which imports java.applet:
package Music;
import java.net.MalformedURLException;
import java.net.URL;
import java.applet.*;
public class Music {
private URL soubor;
public Music(String cesta){
try {
soubor = new URL("file:"+cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button:
package Music;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame{
public static final int WIDTH = 480;
public static final int HEIGHT = 600;
private String file;
public MainFrame(){
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
JButton bPlay = new JButton("PLAY");
jPanel.setLayout(null);
add(jPanel);
jPanel.add(bPlay);
bPlay.setBounds(200, 250, 100, 50);
bPlay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Music music = new Music("zvuk.wav");
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
Please note that Applet.newAudioClip(url).play() does not throw an error if it fails for whatever reason (for example nothing will happen if the project cannot find the wav file).
Try this stand alone test app. Does it work?
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class MainClass {
public static void main(String[] args) {
try {
URL url = new URL("file:zvuk.wav" );
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
System.in.read();
ac.stop();
} catch (Exception e) {
System.out.println(e);
}
}
}
If this small sample works, then it should be a small matter to modify it for your purposes.
However if it doesn't work then we almost certainly know that you project is unable to find the wav file.
Try add this to the code above:
//existing line
URL url = new URL("file:zvuk.wav" );
//new lines to debug wav file location
File myMusicFile = new File(url.getPath());
if(myMusicFile.exists() && !myMusicFile.isDirectory()) {
System.out.println("File exists and is not a directory");
}
If the file does not exist then that's your problem, and you need to point your URL to the correct location.
However if the file does exist and it still doesn't work then we have another possible issue outside of code.
It is possible that .play() is completing too quickly, see below for an example of how to keep it alive.
It is possible that your wav file is not a type that can be played, or it requires an unsupported codec. This is a far bigger topic and needs a new question, and a little bit of research on your part.
Here is the example to keep it alive from the sample code:
//load and start audio
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
//keep thread alive until a key is pressed
System.in.read();
ac.stop();
Sources:
http://www.java2s.com/Code/JavaAPI/java.applet/AppletnewAudioClipURLaudioFileURL.htm
http://docs.oracle.com/javase/7/docs/api/java/applet/AudioClip.html#play%28%29
I do this using NetBeans. This is the code.
Music.java file
package sound.play;
import java.applet.Applet;
import java.net.MalformedURLException;
import java.net.URL;
public class Music {
private URL soubor;
public Music(String cesta) {
try {
soubor = new URL("file:" + cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MainFrame extends javax.swing.JFrame {
public static final int WIDTH = 200;
public static final int HEIGHT = 200;
private String file;
public MainFrame() {
initComponents();
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
jPanel.setLayout(null);
add(jPanel);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Music music = new Music("zvuk.wav");
String filename = "zvuk.wav";
URL url = this.getClass().getResource(filename);
File myMusicFile = new File(url.getPath());
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}
I have 3 clasess : Loader, MyDialog and TEST(with main method). (for code see below)
Everything I want to achieve is create simple dialog with JLabel and JProgressBar, which will notify user about how much time remains to show MyDialog. MyDialog is Jdialog with time consuming operation in constructor (loading data from database etc.).
In code below is model situation. When "MyDialog" is created by main (constant BY_USER is false), everything working exactly i want to. But when i make dialog with button , and instance of MyDialog is created after button press (constant BY_USER is true), Loader is blank white form. It looks like is not completed.
Loader is extending Thread, so i suppose that problem will be in threading (event dispatch thread)? I dont know, what is wrong and how fix it. Please help.
Thanks and sorry for my English.
CLASS TEST :
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class TEST {
public static final boolean BY_USER = false;
public static void main(String[] args) {
if (BY_USER) {
JFrame mainDialog = new JFrame("Main");
JButton show = new JButton("Show MyDialog");
show.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
MyDialog dialog = new MyDialog();
}
});
mainDialog.add(show);
mainDialog.setLocationRelativeTo(null);
mainDialog.setMinimumSize(new Dimension(160, 80));
mainDialog.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainDialog.setVisible(true);
} else {
MyDialog dialog = new MyDialog();
}
}
}
CLASS MyDialog :
package test;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class MyDialog extends JFrame{
public MyDialog() {
super();
// making loader with title, first message and count of steps of operation
Loader loader = new Loader("Loader", "First showed message", 100);
loader.ShowLoader();
// time-consuming operation (loading data from database etc.).
// for clarity replaced with for statement
int j=0;
for(int i=0; i<Integer.MAX_VALUE; i++)
{
j++;
if(j==Integer.MAX_VALUE/100){
// updating loader message and progress bar value
loader.NewAction(Integer.MAX_VALUE - i+"");
j=0;
}
}
// closing loader
loader.DestroyLoader();
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setSize(300, 300);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
CLASS Loader:
package test;
import java.awt.BorderLayout;
import java.awt.Dialog;
import java.awt.Dimension;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
public class Loader extends Thread{
private JDialog dialog;
private JLabel message = new JLabel("", SwingConstants.CENTER);
private JProgressBar progressBar = new JProgressBar(0, 100);
private String newMessage;
private double percentForStep;
private int remainingSteps;
public Loader(String taskName, String firstMessage, int steps) {
this.remainingSteps = steps-1;
dialog = new JDialog((Dialog) null, taskName);
dialog.setLayout(new BorderLayout(15, 15));
dialog.add(message, BorderLayout.CENTER);
dialog.add(progressBar, BorderLayout.SOUTH);
message.setText(firstMessage);
percentForStep = 100 / steps;
}
public void ShowLoader()
{
dialog.setMinimumSize(new Dimension(400,120));
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
this.start();
}
public void DestroyLoader(){
dialog.dispose();
this.interrupt();
}
public void NewAction(String newMessage){
this.newMessage = newMessage;
this.remainingSteps--;
Lock.changed = true;
}
public int RemainingStepsCount()
{
return remainingSteps;
}
#Override
#SuppressWarnings({"CallToThreadYield", "SleepWhileInLoop"})
public void run() {
do{
synchronized (Lock.class) {
if (Lock.changed) {
Lock.changed = false;
this.message.setText(newMessage);
this.progressBar.setValue((int)(100-(remainingSteps*percentForStep)));
dialog.repaint();
}
dialog.repaint();
}
}while(true);
}
}
class Lock{
static boolean changed = false;
}
Look to SwingWorker and his use; I think it can help you to solve the problem.
Is it possible to change the color of a text in a text field?I am trying to build an interpreter, so I was wondering on how would you change the color of the text in real time.
For example the word I enter in the text field is:
printf("hi");
The word printf becomes green after a few seconds.
Is it possible?
package test;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class BlinkColorTextField {
BlinkColorTextField() {
final JTextField blinkingText = new JTextField("Red & Blue");
ActionListener blinker = new ActionListener() {
boolean isRed = true;
public void actionPerformed(ActionEvent ae) {
if (isRed) {
blinkingText.setForeground(Color.BLUE);
} else {
blinkingText.setForeground(Color.RED);
}
isRed = !isRed;
}
};
Timer timer = new Timer(1000, blinker);
timer.start();
JOptionPane.showMessageDialog(null, blinkingText);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new BlinkColorTextField();
}
});
}
}
Try this:
HighlightPainter greenPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.GREEN);
//in a thread...
Highlighter h = tf.getHighlighter();
h.addHighlight(offset, offset+length, greenPainter);
You have to use JEditorPane / JTextPane instead of JTextField and also you can draw the text/string by overriding the paintComponent method.