Java Swing processing status - java

I am trying to implement a swing frame. In this, I want to display a processing status in a textPanel using a different thread while performing the needed task. I tried the following code. Of course there is something wrong with the logic. Please provide me with the proper approach
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class SampleSwing {
private JFrame frame;
public static JTextField textField;
public static boolean processing=false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleSwing window = new SampleSwing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SampleSwing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(0, 31, 434, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
processing=true;
Processingstatus ps=new Processingstatus();
ps.start();
/*perform the actual task*/
processing=false;
}
});
btnNewButton.setBounds(174, 74, 89, 23);
frame.getContentPane().add(btnNewButton);
}
}
class Processingstatus extends Thread{
public void run() {
try {
while(SampleSwing.processing) {
SampleSwing.textField.setText("Processing");
Thread.sleep(1000);
SampleSwing.textField.setText("Processing..");
Thread.sleep(1000);
SampleSwing.textField.setText("Processing...");
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

First I thought, "you should be using a SwingWorker, as it has methods to handle progress and EDT updates..."
But when I looked closer, you don't actually really care about the process itself, you just want some where to show that a process is running...They are two separate entities, that are only related because one (the UI updates) will run so long as the other is running.
So, instead, I used a javax.swing.Timer. This allows me to schedule an event to occur every n milliseconds and have that triggered in the EDT, nice and clean...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.Timer;
public class SampleSwing {
private JFrame frame;
public static JTextField textField;
public static boolean processing = false;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SampleSwing window = new SampleSwing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SampleSwing() {
initialize();
}
private Timer processTimer;
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
textField = new JTextField(25);
frame.add(textField, gbc);
processTimer = new Timer(500, new ActionListener() {
private StringBuilder dots = new StringBuilder(3);
#Override
public void actionPerformed(ActionEvent e) {
dots.append(".");
if (dots.length() > 3) {
dots.delete(0, dots.length());
}
textField.setText("Processing" + dots.toString());
}
});
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!processing) {
processing = true;
processTimer.start();
} else {
processTimer.stop();
processing = false;
textField.setText(null);
}
}
});
frame.add(btnNewButton, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
}
}
ps For the reason why your original code didn't work, see my comment in the above comments section ;)

Related

JTextField - Call event after not editing in n seconds [duplicate]

how to start a function after stop typing in a JTextField. Not for every key release. If two key release time difference is greater than 1 second then it will run this function. Otherwise wait for 1 second.
Use a Swing Timer and a DocumentListener, each time the Document is updated, reset the Timer
Have a look at How to use Swing Timers and Listening for Changes on a Document for more details
As a, simple, example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JTextField field = new JTextField(20);
JLabel label = new JLabel("Waiting");
DeferredDocumentListener listener = new DeferredDocumentListener(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute your required functionality here...
label.setText(label.getText() + ".");
}
}, true);
field.getDocument().addDocumentListener(listener);
field.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
listener.start();
}
#Override
public void focusLost(FocusEvent e) {
listener.stop();
}
});
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(field, gbc);
add(label, gbc);
}
}
public class DeferredDocumentListener implements DocumentListener {
private final Timer timer;
public DeferredDocumentListener(int timeOut, ActionListener listener, boolean repeats) {
timer = new Timer(timeOut, listener);
timer.setRepeats(repeats);
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
#Override
public void insertUpdate(DocumentEvent e) {
timer.restart();
}
#Override
public void removeUpdate(DocumentEvent e) {
timer.restart();
}
#Override
public void changedUpdate(DocumentEvent e) {
timer.restart();
}
}
}
If you don't mind using two libraries, this is very easy to solve with RxSwing and RxJava:
EventQueue.invokeLater(() -> {
try {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
JTextField textField = new JTextField(30);
frame.getContentPane().add(textField, BorderLayout.NORTH);
// HERE
SwingObservable.fromDocumentEvents(textField.getDocument())
.debounce(1, TimeUnit.SECONDS)
.map(documentEvent -> textField.getText())
.subscribe(System.out::println);
frame.setVisible(true);
frame.pack();
} catch (final Exception e) {
e.printStackTrace();
}
});

swing.timer working but has some bug

I have a working app, but very fast timer gets confused.
The idea is to to load data from database to two JTables every 100s and constantly switch between them every 10 seconds. Have everything working but after a few. I am posting the simple example of the problem, please help me find the bug, this is my first time with swing.timers and i guess it is something trivial:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.JTable;
import javax.swing.JScrollPane;
public class Test extends JFrame {
private JPanel contentPane;
private JTable pTable ;
private JTable cTable;
private Timer timer;
private Timer worker;
public int flag=0;
public int flip=0;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try{
initialize();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
}
public static void initialize(){
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, e1);
}
}
public Test() {
try{
setTitle("Warehouse stats");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
ActionListener work = new ActionListener(){
#Override
public void actionPerformed(ActionEvent event)
{
flip=0;
// this is where i would load the tables from DB
pTable = new JTable(10,10);
cTable = new JTable(5,5);
ActionListener action = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
if(flip==0){
scrollPane.setViewportView(pTable);
flip=1;
}else if (flip==1){
scrollPane.setViewportView(cTable);
flip=0;
}
}
};
timer = new Timer(10*1000,action);
timer.setInitialDelay(0);
if(!timer.isRunning()){
timer.start();
}
}
};
worker = new Timer(100*1000,work);
worker.setInitialDelay(0);
worker.start();
}catch (Exception e2){
JOptionPane.showMessageDialog(null, e2);
}
}
}

Opening a different frame with a button in Java

I am trying to open the menu frame using a button on the main frame. I added an event to the button and I tried calling the other class but it keeps giving me an error of ":: expected after this token"
This is my main frame
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main extends JFrame {
public static JPanel mainPane;
public final JButton menuButton = new JButton("New button");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
mainPane = new JPanel();
mainPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(mainPane);
mainPane.setLayout(null);
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu.main(String[] args);
}
});
menuButton.setBounds(76, 89, 104, 32);
mainPane.add(menuButton);
}
}
And this is my menu frame
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
public class Menu extends JFrame {
public static JPanel menuPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu frame = new Menu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Menu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
menuPane = new JPanel();
menuPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(menuPane);
menuPane.setLayout(null);
JLabel menuTitle = new JLabel("Menu");
menuTitle.setBounds(194, 11, 46, 14);
menuPane.add(menuTitle);
}
}
change your action event to this.no need to call main method .create a new instance of Menu class instead.
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu menu = new Menu();
menu.setVisible(true);
}
});
if you relly want to call main method then use
menuButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Menu.main(new String[0]);
}
});
the error is here
Menu.main(String[] args);//error
this is not a correct way of passing arguments to a methods.this is declaration of parameter list.
you can correct error by changing it to ,
String args[] = null;
Menu.main(args); //correct

How can i send an event while the program is in a loop?

I work at a project and i need to understand very well how event-driven programming works. I've read a lot in the last few days and i understood how this is working but i cant figure some things out.
In a class called Application i got this:
public void Simulate() throws InterruptedException {
int i = 0;
while (1 == 1) {
System.out.println(i);
Thread.sleep(1000);
i++;
}
}
And i have this class:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Visual {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Visual window = new Visual();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Visual() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 472, 381);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton btnStart = new JButton("Start");
btnStart.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
Application app = new Application();
try {
app.Simulate();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
**JButton print = new JButton("Print");
print.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("random text");
}
});**
panel.add(print);
panel.add(btnStart);
}
}
What i want to do is when i run this program, i want to pres the putton Start to start the loop in the simulate method and then i want to press the button print, to print some random text while the counter is still running. The problem is that after i pres the start button, the print button becomes unavailable, and cant be pressed anymore. How can i solve this?
For buttons don't use addMouseListener, use addActionListener and override actionPerformed method, to be able to print your number while the loop is running, try to call your simulate method using new thread. Change your Visual class to the followng example:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Visual {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Visual window = new Visual();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Visual() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 472, 381);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Application app = new Application();
(new Thread(new Runnable() {
public void run() {
try {
app.Simulate();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
})).start();
}
});
JButton print = new JButton("Print");
print.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("random text");
}
});
panel.add(print);
panel.add(btnStart);
}
}

Battleship Application crashes if I run it through the main menu after slicking on start

I am creating a battleship game with 4 classes using sockets. A computer, player message and a menu class. To start the game I run the computer class which is the server then I run the menu class which bring up the menu. Through the menu I click start to create a new player object which looks like this
public static void runPlayer()
{
Player client = new Player(); //creates player
client.createBoard();
client.run();
}
this runs perfectly runs without the menu class if i run the computer class then the player class, the game runs successfully. But when i call the run player method in the menu a window pops up with nothing in it.Here is my Menu class
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
import sun.audio.*;
public class Menu {
private javax.swing.JLabel image;
private static final int EXIT_ON_CLOSE = 0;
JFrame frame = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
JLabel statusbar = new JLabel(" Battleship");
JLabel Battleship = new JLabel(" Battleship ");
static AudioPlayer MGP = AudioPlayer.player;
static AudioStream BGM;
AudioData MD;
static ContinuousAudioDataStream loop = null;
public static void waiting (int n)
{
long t0, t1;
t0 = System.currentTimeMillis();
do{
t1 = System.currentTimeMillis();
}
while (t1 - t0 < n);
}
public Menu()
{
frame.setTitle("Battleship");
statusbar.setBorder(BorderFactory.createEtchedBorder(
EtchedBorder.RAISED));
Battleship.setBorder(BorderFactory.createEtchedBorder(
EtchedBorder.RAISED));
panel.setLayout(null);
JButton start = new JButton("Start");
start.setBounds(100, 660, 80, 25);
JButton exit = new JButton("Exit");
exit.setBounds(190, 660, 80, 25);
JButton StopMusic = new JButton("Stop Music");
StopMusic.setBounds(300, 660, 160, 25);
JButton StartMusic = new JButton("Start Music");
StartMusic.setBounds(470, 660, 160, 25);
Battleship.setFont(new Font("Courier New", Font.ITALIC, 36));
Battleship.setForeground(Color.BLACK);
image = new javax.swing.JLabel();
image.setIcon(new javax.swing.ImageIcon("./battleship2.jpg"));
frame.add(image, BorderLayout.EAST);
frame.pack();
frame.add(start);
frame.add(exit);
frame.add(StopMusic);
frame.add(StartMusic);
frame.add(panel);
frame.add(statusbar, BorderLayout.SOUTH);
frame.add(Battleship, BorderLayout.NORTH );
frame.setSize(700, 800);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
music();
start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
{
frame.dispose(); //closes frame
stopMusic(); //stops music
//waiting(500);
runPlayer();
}}
});
StopMusic.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
{
stopMusic();
}
}
});
StartMusic.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
{
startMusic();
}
}
});
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println( "Ending Game" );
System.exit(0);
}
});}
public static void music()
{
try
{
InputStream test = new FileInputStream("./battle.wav");
BGM = new AudioStream(test);
AudioPlayer.player.start(BGM);
}
catch(FileNotFoundException e){
System.out.print(e.toString());
}
catch(IOException error)
{
System.out.print(error.toString());
}
MGP.start(loop);
}
public void stopMusic()
{
if (BGM != null)
AudioPlayer.player.stop(BGM);
if (loop != null)
AudioPlayer.player.stop(loop);
}
public void startMusic() {
try
{
InputStream test = new FileInputStream("./battle.wav");
BGM = new AudioStream(test);
AudioPlayer.player.start(BGM);
}
catch(FileNotFoundException e){
System.out.print(e.toString());
}
catch(IOException error)
{
System.out.print(error.toString());
}
MGP.start(loop);
}
public static void runPlayer()
{
Player client = new Player(); //creates player
client.createBoard();
client.run();
}
public static void main(String[] args)
{
new Menu();
}
}
I think my problem is somewhere in this listener method
start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
{
frame.dispose(); //closes frame
stopMusic(); //stops music
//waiting(500);
runPlayer();
}}
});
It's a bit hard to answer this question with the information provided. But I'll have to guess what the runPlayer() method is doing. I'm assuming there's some type of while loop in there that prevents the Event Dispatch Thread from refreshing the new JFrame you created.
Try to place the stopMusic() and runPlayer() in a new thread.
Basically something like this
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose(); // closes frame
new Thread(){
public void run(){
stopMusic(); // stops music
runPlayer();
}
}.start();
}
});
I think the problem lies outside the code you've shown; it could be anything from a missing setVisible() to a synchronization problem. FWIW, I have a few observation about the code:
Build your GUI on the EDT, #David Young just suggested.
Use static constants to avoid repeating yourself.
Don't use spaces to format labels; use the JLabel alignment constants.
Instead of a null layout, use nested layouts to get the result you want.
To avoid calling a public method in the constructor, you've duplicated the code of startMusic(). Instead, invoke it after the constructor completes.
Here's an example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
import sun.audio.*;
public class Menu {
private static final String TITLE = "Battleship";
private static final String SOUND_FILE = "./battle.wav";
private javax.swing.JLabel image;
JFrame frame = new JFrame(TITLE);
JPanel center = new JPanel(new BorderLayout());
JLabel statusbar = new JLabel(TITLE);
JLabel battleship = new JLabel(TITLE, JLabel.CENTER);
static AudioPlayer MGP = AudioPlayer.player;
static AudioStream BGM;
static ContinuousAudioDataStream loop = null;
AudioData MD;
public Menu() {
frame.setTitle("Battleship");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
statusbar.setBorder(BorderFactory.createEtchedBorder(
EtchedBorder.RAISED));
battleship.setBorder(BorderFactory.createEtchedBorder(
EtchedBorder.RAISED));
JButton start = new JButton("Start");
JButton exit = new JButton("Exit");
JButton StopMusic = new JButton("Stop Music");
JButton StartMusic = new JButton("Start Music");
battleship.setFont(new Font("Courier New", Font.ITALIC, 36));
battleship.setForeground(Color.BLACK);
image = new JLabel();
image.setHorizontalAlignment(JLabel.CENTER);
image.setIcon(new ImageIcon("./battleship2.jpg"));
center.add(image, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.add(start);
panel.add(exit);
panel.add(StopMusic);
panel.add(StartMusic);
center.add(panel, BorderLayout.SOUTH);
frame.add(battleship, BorderLayout.NORTH);
frame.add(center, BorderLayout.CENTER);
frame.add(statusbar, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//frame.dispose();
stopMusic();
runPlayer();
}
});
StopMusic.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
stopMusic();
}
});
StartMusic.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
startMusic();
}
});
exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Ending Game");
System.exit(0);
}
});
}
public void stopMusic() {
if (BGM != null) {
AudioPlayer.player.stop(BGM);
}
if (loop != null) {
AudioPlayer.player.stop(loop);
}
}
public void startMusic() {
try {
InputStream test = new FileInputStream(SOUND_FILE);
BGM = new AudioStream(test);
AudioPlayer.player.start(BGM);
MGP.start(loop);
} catch (FileNotFoundException e) {
System.out.print(e.toString());
} catch (IOException error) {
System.out.print(error.toString());
}
}
public static void runPlayer() {
Player client = new Player();
client.createBoard();
client.run();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Menu menu = new Menu();
menu.startMusic();
}
});
}
// stub for missing class
private static class Player {
void createBoard() {}
void run() {}
}
}

Categories

Resources