I am trying to implement splash screen followed my main activity. Code below is what I have manged to do so far. And I am not able to get my splash screen working. Please help.
On running the the file its showing SplashScreen.getSplashScreen() returned null.What to do ?
SplashDemo.java
public class SplashDemo extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame) {
final String[] comps = {"foo", "bar", "baz"};
g.setComposite(AlphaComposite.Clear);
g.fillRect(120,140,200,40);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString("Loading "+comps[(frame/5)%3]+"...", 120, 150);
}
public SplashDemo() {
super("SplashScreen demo");
setSize(300, 200);
setLayout(new BorderLayout());
Menu m1 = new Menu("File");
MenuItem mi1 = new MenuItem("Exit");
m1.add(mi1);
mi1.addActionListener(this);
this.addWindowListener(closeWindow);
MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(m1);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
Graphics2D g = splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
for(int i=0; i<100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(90);
}
catch(InterruptedException e) {
}
}
splash.close();
setVisible(true);
toFront();
}
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
private static WindowListener closeWindow = new WindowAdapter(){
public void windowClosing(WindowEvent e){
e.getWindow().dispose();
}
};
public static void main (String args[]) {
SplashDemo test = new SplashDemo();
}
}
Create your splash screen image, say MySplashyScreen.gif, and put it in a directory called images (or wherever you like).
Then on startup use this command line:
java -splash:images/MySplashyScreen.gif SplashDemo
Related
The game I am building involves switching panels after the start button is clicked when startGame() is called. The program freezes once the button is clicked and does nothing.
Here is code snippet:
public class ArtilleryGame extends JFrame {
private static final long serialVersionUID = 1L;
//TODO: fix clouds from updating with background
static StartPanel startPanel = new StartPanel();
public ArtilleryGame() throws InterruptedException
{
setSize(898,685);
setLocationRelativeTo(null);
setTitle("Tank Game");
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
URL sound = this.getClass().getResource("Sounds/Intro_Screen.wav");
AudioClip drop = Applet.newAudioClip(sound);
drop.loop();
drop.play();
add(startPanel);
//add(new GamePanel());
buttons();
setVisible(true);
}
private void buttons()
{
URL startURL = this.getClass().getResource("imgg/StartBtn.png");
BufferedImage startI = new BufferedImage(170, 62, BufferedImage.TYPE_INT_RGB);
try
{
startI = ImageIO.read(startURL);
} catch (IOException e)
{
e.printStackTrace();
}
ImageIcon startImg = new ImageIcon(startI);
JButton startBtn = new JButton(startImg);
startBtn.setSize(170, 62);
startBtn.setBorder(BorderFactory.createEmptyBorder());
startBtn.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
startGame();
}
});
startBtn.setLocation(365, 310);
StartPanel.background.add(startBtn);
}
public void startGame()
{
remove(startPanel);
add(new GamePanel());
}
public static void displayCredits()
{
JOptionPane.showMessageDialog(null, new CreditsPanel(), "Tank Game", JOptionPane.PLAIN_MESSAGE);
}
public static void main(String[] args) throws InterruptedException
{
new ArtilleryGame();
//displayCredits();
}
}
Use a CardLayout. The CardLayout allows you to easily swap panels.
Read the section from the Swing tutorial on How to Use CardLayout for more information and working examples.
I would like to make my JToolBar impossible to detach from its container but still let the user drag it to one of the container's sides.
I know about
public void setFloatable( boolean b )
but this won't allow the user to move the JToolBar at all.
Is there any way of doing this without overwriting ToolBarUI?
Also, is there an option to highlight its new position before dropping it?
It's not the most elegant solution, but it works.
public class Example extends JFrame {
BasicToolBarUI ui;
Example() {
JToolBar tb = new JToolBar();
tb.add(new JButton("AAAAA"));
tb.setBackground(Color.GREEN);
ui = (BasicToolBarUI) tb.getUI();
getContentPane().addContainerListener(new Listener());
getContentPane().add(tb, BorderLayout.PAGE_START);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
class Listener implements ContainerListener {
#Override
public void componentAdded(ContainerEvent e) {}
#Override
public void componentRemoved(ContainerEvent e) {
if (ui.isFloating()) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ui.setFloating(false, null);
}
});
}
}
}
public static void main(String[] args) {
new Example();
}
}
Explanation:
Whenever the toolbar is moving to a floating state, it is instructed not do so. The only problem is that you have to wait for the EDT to finish the process for creating the floating window, and only then can you tell it not to float. The result is that you actually see the window created and then hidden.
Note:
I think that overriding the UI for the toolbar is a better solution, though it's possible that with a more intricate approach doing something similar to what I did will also work well.
works for me quite correctly on WinOS, old code from SunForum
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CaptiveToolBar {
private Robot robot;
private JDialog dialog;
private JFrame frame;
public static void main(String[] args) {
//JFrame.setDefaultLookAndFeelDecorated(true);
//JDialog.setDefaultLookAndFeelDecorated(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CaptiveToolBar().makeUI();
}
});
}
public void makeUI() {
try {
robot = new Robot();
} catch (AWTException ex) {
ex.printStackTrace();
}
final JToolBar toolBar = new JToolBar();
for (int i = 0; i < 3; i++) {
toolBar.add(new JButton("" + i));
}
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.add(toolBar, BorderLayout.NORTH);
final ComponentListener dialogListener = new ComponentAdapter() {
#Override
public void componentMoved(ComponentEvent e) {
dialog = (JDialog) e.getSource();
setLocations(false);
}
};
toolBar.addHierarchyListener(new HierarchyListener() {
#Override
public void hierarchyChanged(HierarchyEvent e) {
Window window = SwingUtilities.getWindowAncestor(toolBar);
if (window instanceof JDialog) {
boolean listenerAdded = false;
for (ComponentListener listener : window.getComponentListeners()) {
if (listener == dialogListener) {
listenerAdded = true;
break;
}
}
if (!listenerAdded) {
window.addComponentListener(dialogListener);
}
}
}
});
frame.addComponentListener(new ComponentAdapter() {
#Override
public void componentMoved(ComponentEvent e) {
if (dialog != null && dialog.isShowing()) {
setLocations(true);
}
}
});
frame.setVisible(true);
}
private void setLocations(boolean moveDialog) {
int dialogX = dialog.getX();
int dialogY = dialog.getY();
int dialogW = dialog.getWidth();
int dialogH = dialog.getHeight();
int frameX = frame.getX();
int frameY = frame.getY();
int frameW = frame.getWidth();
int frameH = frame.getHeight();
boolean needToMove = false;
if (dialogX < frameX) {
dialogX = frameX;
needToMove = true;
}
if (dialogY < frameY) {
dialogY = frameY;
needToMove = true;
}
if (dialogX + dialogW > frameX + frameW) {
dialogX = frameX + frameW - dialogW;
needToMove = true;
}
if (dialogY + dialogH > frameY + frameH) {
dialogY = frameY + frameH - dialogH;
needToMove = true;
}
if (needToMove) {
if (!moveDialog && robot != null) {
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
dialog.setLocation(dialogX, dialogY);
}
}
}
I have this set up to update pretty constantly on the timer, but I want to be able to pause the timer with the spacebar. I have attempted to implement an actionListener, but I am not sure what to apply it to. Most of the examples I can find relate to buttons or text boxes, not keyboard presses inside a jpanel. I have printed src to the console and it doesn't appear to be registering my spacebar as an event... I have tried adding the actionListener, but I am not getting something about the syntax. Any help would be appreciated.
public class Arena extends JFrame {
private PaintPanel paintPanel;
public Arena() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setMinimumSize(new Dimension(1000, 720));
paintPanel = new PaintPanel();
getContentPane().add(paintPanel, BorderLayout.CENTER);
paintPanel.setBackground(Color.black);
paintPanel.setFocusable(true);
//paintPanel.addActionListener(this);
pack();
paintPanel.initGame();
}
class PaintPanel extends JPanel implements ActionListener {
private List<Gladiator> gladiators;
private Timer timer;
private Ai AI;
private Load loadObject;
public void initGame() {
timer = new Timer(500, this);
timer.start();
AI = new Ai(gladiators);
loadObject = new Load();
}
#Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
System.out.println("************* "+src);
// if (src == spacebar) {
// } else if (src = timer) {
AI.runAI();
try {
Thread.sleep(100);
System.out.println("sleeping");
} catch (InterruptedException d) {
System.err.println("Caught : InterruptedException" + d.getMessage());
}
repaint();
// }
}
public PaintPanel(){
super();
gladiators = new ArrayList<Gladiator>();
String[][] gladiatorInfo = new String[100][25];
String[] gladiatorRaw = new String[100];
String[][] parsedInfo = new String[250][100];
Gladiator[] gladiator = new Gladiator[20];
int[] matchInfo = new int[3];
int numberofcontestants = 0;
gladiatorRaw = loadObject.getGladiators(gladiatorRaw);
parsedInfo = loadObject.parseStats(gladiatorRaw);
Venue venue = new Venue();
matchInfo = loadObject.getMatchSettings(matchInfo);
venue.populateVenue(matchInfo);
gladiator = createGladiators(venue);
for (int a = 0; a < venue.contestants; a++) {
System.out.println("Populating Gladiator "+a);
gladiator[a].populategladiators(parsedInfo,a);
gladiator[a].getEquipment();
gladiator[a].contestantNumber = a;
gladiators.add(gladiator[a]);
}
}
public Gladiator[] createGladiators(Venue venue) {
int[][] initialPlacement = new int[20][2];
Gladiator[] gladiator = new Gladiator[(venue.contestants)];
initialPlacement = loadObject.loadInitialPlacement(venue.contestants);
for (int a = 0; a < venue.contestants; a++) {
System.out.println("Add gladiator "+a);
gladiator[a] = new Gladiator(initialPlacement[a][0],initialPlacement[a][1]);
System.out.println(initialPlacement[a][0]+","+initialPlacement[a][1]);
}
return gladiator;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
try {
BufferedImage background = ImageIO.read(new File("background.png"));
g.drawImage(background,0,0,this);
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
}
for (Gladiator s : gladiators){
s.draw(g2);
}
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Arena gamePanel = new Arena();
gamePanel.setVisible(true);
}
});
}
}
Also, is there a getEvent() key code for the spacebar? Can't seem to find one. Thanks
You should use the key bindings API
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "space");
am.put("space", new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
if (timer.isRunning()) {
timer.stop();
} else {
timer.start();
}
}
});
The InputMap/ActionMap can be applied to any component that extends from JComponent, but in your case, I'd suggest attaching it to your PaintPane
im using
getContentPane().setBackground(Color.PINK);
to set the background of a JFrame to the color pink. this JFrame is being fullscreened using a GraphicsDevice. the color of the background is not changing. any help?
fullscreen code:
public static void main(String... args) {
DisplayMode dMode = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
GameMain game = new GameMain();
game.run(dMode);
}
public void run(DisplayMode dMode) {
getContentPane().setBackground(Color.PINK);
setForeground(Color.WHITE);
setFont(new Font("Arial", Font.PLAIN, 24));
Screen s = new Screen();
try {
s.setFullScreen(dMode, this);
try {
Thread.sleep(5000);
} catch(Exception e) { }
} finally {
s.restoreScreen();
}
}
public void setFullScreen(DisplayMode dMode, JFrame window) {
window.setUndecorated(true);
window.setResizable(false);
gDevice.setFullScreenWindow(window);
if(dMode != null && gDevice.isDisplayChangeSupported()) {
try {
gDevice.setDisplayMode(dMode);
} catch(Exception e) { }
}
}
This works fine for me...
public class TestFullScreen {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
FullFrame frame = new FullFrame();
frame.setUndecorated(true);
frame.getContentPane().setBackground(Color.PINK);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
gs[0].setFullScreenWindow(frame);
}
});
}
public static class FullFrame extends JFrame {
public FullFrame() {
super();
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
});
}
}
}
I even set moved the setBackground call after the setFullScreenWindow call.
Make sure you don't have anything on the content pane that might be taking up the full space and that the content pane hasn't been changed.
I'm using NetBeans 6.1 as my primary IDE, in there I can't run this splash screen example which have given by the Sun (It throws an nullpointerExeption). But I can run this on command line using this arguments.
java -splash:filename.gif SplashDemo
I dont know how to inject command line arguments in NetBeans. Please someone help.
import java.awt.*;
import java.awt.event.*;
public class SplashDemo extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame) {
final String[] comps = {"foo", "bar", "baz"};
g.setComposite(AlphaComposite.Clear);
g.fillRect(120, 140, 200, 40);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString("Loading " + comps[(frame / 5) % 3] + "...", 120, 150);
}
public SplashDemo() {
super("SplashScreen demo");
setSize(300, 200);
setLayout(new BorderLayout());
Menu m1 = new Menu("File");
MenuItem mi1 = new MenuItem("Exit");
m1.add(mi1);
mi1.addActionListener(this);
this.addWindowListener(closeWindow);
MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(m1);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
Graphics2D g = splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
for (int i = 0; i < 100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(90);
} catch (InterruptedException e) {
}
}
splash.close();
setVisible(true);
toFront();
}
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
private static WindowListener closeWindow = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
e.getWindow().dispose();
}
};
public static void main(String args[]) {
SplashDemo test = new SplashDemo();
}
}
Go to project properties (right click on a project, and choose properties).
Choose "run" item from the Categories list.
There you can setup the arguments, VM options etc.