I've been trying to create separate classes, 1 with methods, 1 with the main App and 1 with graphics.
But I keep getting this error "Exception in thread "main" java.lang.StackOverflowError" How can I solve this problem?
public class App {
public static void main(String[] args) {
Stopwatch sw = new Stopwatch();
sw.setVisible();
}
}
This is the frame class
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class Stopwatch {
Frame123 f = new Frame123 ();
private static final String imgIcon = "data/icon.png";
private static final int WIDTH = 300;
private static final int HEIGHT = 150;
private final JTextField fieldTime;
private final JButton buttonPlay;
private final JButton buttonPause;
private final Action actionPlay;
private final Action actionPause;
private final Action actionReset;
private final JFrame frame;
private final Runnable ticker = new Runnable() {
public void run() {
f.tick();
}
};
public JButton getButtonPlay() {
return buttonPlay;
}
public JButton getButtonPause() {
return buttonPause;
}
public Action getActionPlay() {
return actionPlay;
}
public Action getActionPause() {
return actionPause;
}
public Action getActionReset() {
return actionReset;
}
public Runnable getTicker() {
return ticker;
}
public Stopwatch() {
frame = new JFrame("Stop Watch V 1.2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setIconImage(new ImageIcon(imgIcon).getImage());
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
frame.setContentPane(mainPanel);
fieldTime = new JTextField(f.getResettime());
fieldTime.setEditable(false);
Font bigFont = fieldTime.getFont().deriveFont(Font.PLAIN, 50f);
fieldTime.setFont(bigFont);
mainPanel.add(fieldTime);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
actionPlay = new AbstractAction("Start") {
#Override
public void actionPerformed(ActionEvent e) {
f.start();
}
};
actionPause = new AbstractAction("Pause") {
#Override
public void actionPerformed(ActionEvent e) {
f.pause();
}
};
actionReset = new AbstractAction("Reset") {
#Override
public void actionPerformed(ActionEvent e) {
f.reset();
}
};
buttonPlay = new JButton(actionPlay);
buttonPanel.add(buttonPlay);
buttonPause = new JButton(actionPause);
buttonPanel.add(buttonPause);
buttonPanel.add(new JButton(actionReset));
}
public final void setVisible() {
frame.setVisible(true);
buttonPlay.requestFocusInWindow();
}
public void displayTime(final String todisplay) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
fieldTime.setText(todisplay);
}
});
}
}
And this is the method class
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class Frame123 {
Stopwatch a = new Stopwatch();
private long lasttick = 0L;
private boolean paused = false;
private long elapsed = 0L;
private final ReentrantLock lock = new ReentrantLock();
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
private ScheduledFuture<?> running = null;
private static final String RESETTIME = buildTime(0);
public void start() {
lock.lock();
try {
if (running!= null) {
return;
}
paused = false;
lasttick = System.currentTimeMillis();
running = executor.scheduleAtFixedRate(a.getTicker(), 10, 10, TimeUnit.MILLISECONDS);
a.getActionPlay().setEnabled(false);
a.getActionPause().setEnabled(true);
a.getActionReset().setEnabled(false);
a.getButtonPause().requestFocusInWindow();
} finally {
lock.unlock();
}
}
public void pause() {
lock.lock();
try {
if (running == null) {
return;
}
running.cancel(false);
paused = true;
running = null;
a.getActionPlay().setEnabled(true);
a.getActionPause().setEnabled(false);
a.getActionReset().setEnabled(true);
a.getButtonPlay().requestFocusInWindow();
} finally {
lock.unlock();
}
}
public void reset() {
lock.lock();
try {
if (running != null) {
return;
}
elapsed = 0;
a.displayTime(RESETTIME);
a.getActionPlay().setEnabled(true);
a.getActionPause().setEnabled(false);
a.getActionReset().setEnabled(true);
a.getButtonPlay().requestFocusInWindow();
} finally {
lock.unlock();
}
}
public String getResettime() {
return RESETTIME;
}
public static final String buildTime(final long elapsed) {
long hundredths = elapsed / 10;
long seconds = hundredths / 100;
long minutes = seconds / 60;
long hours = minutes / 60;
return String.format("%02d:%02d:%02d:%02d", hours, minutes % 60, seconds % 60, hundredths % 100);
}
public void tick() {
lock.lock();
try {
long now = System.currentTimeMillis();
long delta = now - lasttick;
lasttick = now;
if (!paused) {
elapsed += delta;
a.displayTime(buildTime(elapsed));
}
} finally {
lock.unlock();
}
}
}
And this is the working class, all classes together!
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Frame1 {
private static final int WIDTH = 700;
private static final int HEIGHT = 350;
private static final String RESETTIME = buildTime(0);
public class App {
public static void main(String[] args) {
Stopwatch sw = new Stopwatch();
sw.setVisible();
}
}
private static final String buildTime(final long elapsed) {
long hundredths = elapsed / 10;
long seconds = hundredths / 100;
long minutes = seconds / 60;
long hours = minutes / 60;
return String.format("%02d:%02d:%02d:%02d", hours, minutes % 60, seconds % 60, hundredths % 100);
}
private final JTextField fieldTime;
private final JTextField fieldTime_2;
private final JButton buttonPlay;
private final JButton buttonPause;
private final JButton buttonLaptime;
private final Action actionPlay;
private final Action actionPause;
private final Action actionReset;
private final Action actionLaptime;
private final JFrame frame;
private final ReentrantLock lock = new ReentrantLock();
private long lasttick = 0;
private boolean paused = false;
private long elapsed = 0;
private ScheduledFuture<?> running = null;
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
private final Runnable ticker = new Runnable() {
public void run() {
tick();
}
};
public Frame1() {
frame = new JFrame("Stop Watch");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
frame.setContentPane(mainPanel);
fieldTime = new JTextField(RESETTIME);
fieldTime.setEditable(false);
Font bigFont = fieldTime.getFont().deriveFont(Font.PLAIN, 110f);
fieldTime.setFont(bigFont);
mainPanel.add(fieldTime);
fieldTime_2 = new JTextField();
fieldTime_2.setEditable(false);
Font bigFont_2 = fieldTime_2.getFont().deriveFont(Font.PLAIN, 110f);
fieldTime_2.setFont(bigFont_2);
mainPanel.add(fieldTime_2);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
mainPanel.add(buttonPanel, BorderLayout.NORTH);
actionPlay = new AbstractAction("Start") {
#Override
public void actionPerformed(ActionEvent e) {
start();
}
};
actionPause = new AbstractAction("Pause") {
#Override
public void actionPerformed(ActionEvent e) {
pause();
}
};
actionReset = new AbstractAction("Reset") {
#Override
public void actionPerformed(ActionEvent e) {
reset();
}
};
actionLaptime = new AbstractAction("Laptime") {
#Override
public void actionPerformed(ActionEvent e) {
lap(buildTime(elapsed));
}
};
buttonPlay = new JButton(actionPlay);
buttonPanel.add(buttonPlay);
buttonPause = new JButton(actionPause);
buttonPanel.add(buttonPause);
buttonPanel.add(new JButton(actionReset));
buttonLaptime = new JButton(actionLaptime);
buttonPanel.add(buttonLaptime);
}
public final void setVisible() {
frame.setVisible(true);
buttonPlay.requestFocusInWindow();
}
private void start() {
lock.lock();
try {
if (running != null) {
return;
}
paused = false;
lasttick = System.currentTimeMillis();
running = executor.scheduleAtFixedRate(ticker, 10, 10, TimeUnit.MILLISECONDS);
actionPlay.setEnabled(false);
actionPause.setEnabled(true);
actionReset.setEnabled(false);
actionLaptime.setEnabled(true);
buttonPause.requestFocusInWindow();
} finally {
lock.unlock();
}
}
public void lap(final String todisplay) {
if (running != null) {
fieldTime_2.setText(todisplay);
} else {
}
}
public JTextField getFieldTime_2() {
return fieldTime_2;
}
private void pause() {
lock.lock();
try {
if (running == null) {
return;
}
running.cancel(false);
paused = true;
running = null;
actionPlay.setEnabled(true);
actionPause.setEnabled(false);
actionReset.setEnabled(true);
actionLaptime.setEnabled(false);
buttonPlay.requestFocusInWindow();
} finally {
lock.unlock();
}
}
private void reset() {
lock.lock();
try {
if (running != null) {
return;
}
elapsed = 0;
displayTime(RESETTIME);
fieldTime_2.setText(RESETTIME);
actionPlay.setEnabled(true);
actionPause.setEnabled(false);
actionReset.setEnabled(true);
buttonPlay.requestFocusInWindow();
} finally {
lock.unlock();
}
}
private void tick() {
lock.lock();
try {
long now = System.currentTimeMillis();
long delta = now - lasttick;
lasttick = now;
if (!paused) {
elapsed += delta;
displayTime(buildTime(elapsed));
}
} finally {
lock.unlock();
}
}
private void displayTime(final String todisplay) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
fieldTime.setText(todisplay);
}
});
}
}
Error lines
Exception in thread "main" java.lang.StackOverflowError
at jjhjh.Stopwatch.<init>(Stopwatch.java:18)
at jjhjh.Frame123.<init>(Frame123.java:11)
at jjhjh.Stopwatch.<init>(Stopwatch.java:18)
at jjhjh.Frame123.<init>(Frame123.java:11)
at jjhjh.Stopwatch.<init>(Stopwatch.java:18)
at jjhjh.Frame123.<init>(Frame123.java:11)
at jjhjh.Stopwatch.<init>(Stopwatch.java:18)
Related
When I start program without tcp server, my program work correctly but when tcp server gets involved my second gui screen is not working. I am asking why do I have such a problem.How to make server ready.
This my ServerClass;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket serverSocket;
public Server(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
}
public void startServer() {
try {
while (!serverSocket.isClosed()) {
Socket socket = serverSocket.accept();
System.out.println("Bağlandı");
ClientHandler clientHandler = new ClientHandler(socket);
}
} catch (IOException e) {
}
}
public static void main(String[] args) {
Svg svg = new Svg();
svg.getjBaslat().addActionListener(new ActionListener() {
int rectNo;
#Override
public void actionPerformed(ActionEvent e) {
if (svg.getRectNo().getText().equals("")) {
rectNo = 0;
} else {
rectNo = Integer.parseInt(svg.getRectNo().getText());
}
svg.setVis();
DrawShapes dShapes = new DrawShapes(rectNo);
try {
ServerSocket serverSocket = new ServerSocket(9090);
Server server = new Server(serverSocket);
server.startServer();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
}
ClientHandler Class;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
public class ClientHandler {
public static ArrayList<ClientHandler> clientHandlers = new ArrayList<>();
private Socket socket;
private BufferedReader bufferedReader;
private BufferedWriter bufferedWriter;
public ClientHandler(Socket socket) {
try {
this.socket = socket;
this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
clientHandlers.add(this);
}catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
}
}
public void removeClientHandler() {
clientHandlers.remove(this);
}
public void closeEverything(Socket socket, BufferedReader bufferedReader, BufferedWriter bufferedWriter) {
removeClientHandler();
try {
if(bufferedReader != null) {
bufferedReader.close();
}if (bufferedWriter != null) {
bufferedWriter.close();
}if(socket != null) {
socket.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
Gui1 Class;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Gui1 {
private JFrame jFrame;
private JLabel jRect;
private JButton jStart;
private JTextField rectNo;
public Gui1() {
jFrame = new JFrame("Title");
jRect = new JLabel("Rect Number:");
jStart = new JButton("Start");
rectNo = new JTextField();
jRect.setBounds(10, 10, 120, 30);
jStart.setBounds(150, 40, 80, 25);
rectNo.setBounds(150, 10, 80, 30);
rectNo.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
String value = rectNo.getText();
int i = value.length();
if (e.getKeyChar() >= '0' && e.getKeyChar() <= '9') {
rectNo.setEditable(true);
}else {
rectNo.setEditable(false);
rectNo.setText(""); }
}
});
jFrame.add(jRect);
jFrame.add(jStart);
jFrame.add(rectNo);
jFrame.setSize(250,125);
jFrame.setLayout(null);
jFrame.setDefaultCloseOperation(3);
jFrame.setResizable(false);
jFrame.setVisible(true);
}
public JButton getjBaslat() {
return jStart;
}
public JTextField getRectNo() {
return rectNo;
}
public JFrame getjFrame() {
return jFrame;
}
public void setVis() {
if(jFrame.isVisible()) {
jFrame.setVisible(false);
}else {
jFrame.setVisible(true);
}
}
}
DrawShapes Class;
import javax.swing.JFrame;
public class DrawShapes extends JFrame {
private final static int GENISLIK = 800;
private final static int YUKSEKLIK = 600;
public DrawShapes(int x) {
setSize(GENISLIK, YUKSEKLIK);
setTitle("Sunucu");
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Panel panel = new Panel(x);
add(panel);
setVisible(true);
}
}
Panel Class;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Panel extends JPanel implements ActionListener {
private List<Object> sekil = new ArrayList<>();
Timer timer;
public Panel(int x) {
this.setFocusable(true);
timer = new Timer(20, this);
timer.start();
addRect(x);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Object s : sekil) {
if (s instanceof Rect) {
((Rect) s).paint(g);
}
}
}
public void update() {
for (Object s : sekil) {
if (s instanceof Rect) {
((Rect) s).update();
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
repaint();
update();
}
private void addRect(int i) {
for (int a = 0; a < i; a++) {
sekil.add(new Rect());
}
}
}
React Class;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
public class Rect {
private final static int GENISLIK = 800;
private final static int YUKSEKLIK = 600;
private final static int eksi = 20;
Random r = new Random();
int x = r.nextInt(670);
int y = r.nextInt(525);
int genislik = (int) Math.floor(Math.random() * (70 - 20 + 1) + 20);
int yukseklik = (int) Math.floor(Math.random() * (50 - 15 + 1) + 15);
int adım = (int) Math.floor(Math.random() * (10 - 1 + 1) + 1);
float f1 = r.nextFloat();
float f2 = r.nextFloat() / 2f;
float f3 = r.nextFloat() / 2f;
public void paint(Graphics g) {
Color rastgeleRenk = new Color(f1, f2, f3);
g.setColor(rastgeleRenk);
g.fillRect(x, y, genislik, yukseklik);
}
public void update() {
if ((x + genislik) > (GENISLIK - eksi) || x < 0) {
adım = -adım;
}
x = x + adım;
}
}
I tried so many different ways to solve this problem but I can't see my fault. Maybe I made mistake thread section or made server connection false. I don't find any solution. Thanks to all concerned.
I'm working on a vertical scrolling game, and I'm using a thread to generate new enemies every 2 seconds. Each enemy is an image in a JPanel. For some reason, The generated enemies are not showing up in the JFrame, but they are present. When the player collides with one of the enemies, all the enemies show up.
This is the main class:
package asteroidblaster;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
import java.awt.*;
public class Main extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public Main() {
initUI();
}
private void initUI() {
add(new Board());
setResizable(false);
pack();
setTitle("Alien Blaster");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame ex = new Main();
ex.setVisible(true);
});
}
}
This is the main game logic:
package asteroidblaster;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class Board extends JPanel {
private static final long serialVersionUID = 1L;
private final int B_WIDTH = 1500;
private final int B_HEIGHT = 700;
private final int REFRESH_TIME = 150;
private AlienShip alien;
private PlayerShip player;
private ArrayList<AlienShip> enemies = new ArrayList<AlienShip>();
private Timer alienScrollTimer, mainTimer;
public Board() {
initBoard();
}
private void initBoard() {
setBackground(Color.BLACK);
setFocusable(true);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
setPlayer();
initAlienTimer();
gameLoop();
}
private void initAlienTimer() {
alienScrollTimer = new Timer(25, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(AlienShip as : enemies) {
as.scrollShip();
}
repaint();
}
});
alienScrollTimer.start();
}
private void setPlayer() {
player = new PlayerShip();
add(player);
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent e) {
player.followMouse(e.getX(), e.getY());
//checkCollision();
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
}
});
}
private void checkCollision() {
for(AlienShip as : enemies) {
if(player.getBounds().intersects(as.getBounds()))
player.setVisible(false);
}
}
private Thread alienGenerator() {
for(int i = 0; i < 3; i++) { //these two are being drawn
alien = new AlienShip();
add(alien);
enemies.add(alien);
}
return new Thread(new Runnable() {
#Override
public void run() {
int sleepTime = 2000;
while(true) {
try {
Thread.sleep(sleepTime);
} catch(InterruptedException e) {
System.out.println(e);
}
alien = new AlienShip();
add(alien);
enemies.add(alien);
System.out.println("Enemies: " + enemies.size());
}
}
});
}
private void gameLoop() {
alienGenerator().start();
mainTimer = new Timer(REFRESH_TIME, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
checkCollision();
repaint();
}
});
mainTimer.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
This is the AlienShip class:
package asteroidblaster;
import java.util.Random;
import java.awt.*;
import javax.swing.*;
public class AlienShip extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private final String ALIEN_SHIP_FILE = "images/alienShip.jpg";
private final int PANEL_WIDTH = 224, PANEL_HEIGHT = 250;
private int panelX, panelY;
private Image alienShipImage;
public AlienShip() {
initAlienShip();
}
private void loadImage() {
alienShipImage = Toolkit.getDefaultToolkit().getImage(ALIEN_SHIP_FILE);
}
public int getX() {
return panelX;
}
public int getY() {
return panelY;
}
private void setY(int yCoord) {
panelY = yCoord;
}
private int setX() {
Random r = new Random();
int rand = r.nextInt(14) + 1;
return panelX = rand * 100;
}
private void initAlienShip() {
panelX = setX();
panelY = 0;
setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
setBackground(Color.BLUE);
loadImage();
}
#Override
public Rectangle getBounds() {
return new Rectangle(panelX, panelY, PANEL_WIDTH, PANEL_HEIGHT);
}
public void scrollShip() {
setY(getY() + 1);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(alienShipImage, 0, 0, null);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class slide extends JFrame
{
ImageIcon[] iconArray = new ImageIcon[25];
int iconIndex = 0;
JLabel label;
JPanel panel;
slide ()
{
panel = new JPanel();
label = new JLabel();
add(panel);
setTitle("Slide Show");
panel.add(label);
for(int i = 0; i < iconArray.length; i++)
{
iconArray[i] = new ImageIcon("C:/SlideShow/slide0.jpg");
}
Timer timer = new Timer(1000, new TimerListener());
timer.start();
}
private class TimerListener implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
label.setIcon(iconArray[iconIndex]);
iconIndex++ ;
if(iconIndex == 25)
iconIndex = 0;
}
}
public static void main(String[] args)
{
slide frame = new slide();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
}
}
Any idea how to make a slideshow to show pictures with different > > time intervals? For example 1 sec for the first picture, 200 ms for > > the next, 3 sec for the third and etc. > > > > many thanks for the help!!!
A Swing timer has at most two delays. You can set the initial delay and the interval delay.
A Thread gives you more control over how long you sleep between images.
Here's one way to develop a slide show viewer that allows you to set the delay for each image. I used 3 images from the Internet to test the viewer.
package com.ggl.testing;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Slideshow implements Runnable {
private JFrame frame;
private SSImage[] imageArray;
private SSShower showImages;
private SSViewer imageViewer;
public Slideshow() {
this.imageArray = new SSImage[3];
Image image0 = null;
Image image1 = null;
Image image2 = null;
try {
image0 = ImageIO.read(new URL(
"http://www.ericofon.com/collection/collection1.jpg"));
image1 = ImageIO
.read(new URL(
"http://magiclinks1.wikispaces.com/file/view"
+ "/collection11_lg.jpg/219833158/collection11_lg.jpg"));
image2 = ImageIO
.read(new URL(
"http://www.pokelol.com/wp-content/uploads/2011/12"
+ "/my_pokemon_collection_by_pa_paiya-d4iiuo5.jpg"));
} catch (IOException e) {
e.printStackTrace();
return;
}
imageArray[0] = new SSImage(image0, 4000L);
imageArray[1] = new SSImage(image1, 2500L);
imageArray[2] = new SSImage(image2, 1500L);
}
#Override
public void run() {
frame = new JFrame("Check Box Test");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent event) {
exitProcedure();
}
});
imageViewer = new SSViewer(700, 700);
frame.add(imageViewer);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
showImages = new SSShower(imageArray, imageViewer);
new Thread(showImages).start();
}
private void exitProcedure() {
showImages.setRunning(false);
frame.dispose();
System.exit(0);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Slideshow());
}
public class SSImage {
private final long delay;
private final Image image;
public SSImage(Image image, long delay) {
this.image = image;
this.delay = delay;
}
public long getDelay() {
return delay;
}
public Image getImage() {
return image;
}
}
public class SSViewer extends JPanel {
private static final long serialVersionUID = -7893539139464582702L;
private Image image;
public SSViewer(int width, int height) {
this.setPreferredSize(new Dimension(width, height));
}
public void setImage(Image image) {
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, (this.getWidth() - image.getWidth(this)) / 2,
(this.getHeight() - image.getHeight(this)) / 2, this);
}
}
public class SSShower implements Runnable {
private int counter;
private volatile boolean running;
private SSViewer ssviewer;
private SSImage[] imageArray;
public SSShower(SSImage[] imageArray, SSViewer ssviewer) {
this.imageArray = imageArray;
this.ssviewer = ssviewer;
this.counter = 0;
this.running = true;
}
#Override
public void run() {
while (running) {
SSImage ssimage = imageArray[counter];
ssviewer.setImage(ssimage.getImage());
repaint();
sleep(ssimage.getDelay());
counter = ++counter % imageArray.length;
}
}
private void repaint() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ssviewer.repaint();
}
});
}
private void sleep(long delay) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
}
}
public synchronized void setRunning(boolean running) {
this.running = running;
}
}
}
I have just written a program in Netbeans that moves/copies/deletes files, and I wanted to give it a "diagnostic mode" where information about selected files, folders, variables, etc is displayed in a Text Area. Now, I could set this to only be visible when the "diagnostic mode" toggle is selected, but I think it would look awesome if the text area started behind the program, and "slid" out from behind the JFrame when the button is toggled. Is there any way to do this?
Thanks!
-Sean
Here is some starter code for you. This will right-slide a panel
of just about any content type. Tweak as necessary. Add error
checking and exception handling.
Tester:
static public void main(final String[] args) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
final JPanel slider = new JPanel();
slider.setLayout(new FlowLayout());
slider.setBackground(Color.RED);
slider.add(new JButton("test"));
slider.add(new JButton("test"));
slider.add(new JTree());
slider.add(new JButton("test"));
slider.add(new JButton("test"));
final CpfJFrame42 cpfJFrame42 = new CpfJFrame42(slider, 250, 250);
cpfJFrame42.slide(CpfJFrame42.CLOSE);
cpfJFrame42.setSize(300, 300);
cpfJFrame42.setLocationRelativeTo(null);
cpfJFrame42.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
cpfJFrame42.setVisible(true);
}
});
}
Use GAP & MIN to adjust spacing from JFrame and closed size.
The impl is a little long...it uses a fixed slide speed but
that's one the tweaks you can make ( fixed FPS is better ).
package com.java42.example.code;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
public class CpfJFrame42 extends JFrame {
public static int GAP = 5;
public static int MIN = 1;
public static final int OPEN = 0x01;
public static final int CLOSE = 0x02;
private JDialog jWindow = null;
private final JPanel basePanel;
private final int w;
private final int h;
private final Object lock = new Object();
private final boolean useSlideButton = true;
private boolean isSlideInProgress = false;
private final JPanel glassPane;
{
glassPane = new JPanel();
glassPane.setOpaque(false);
glassPane.addMouseListener(new MouseAdapter() {
});
glassPane.addMouseMotionListener(new MouseMotionAdapter() {
});
glassPane.addKeyListener(new KeyAdapter() {
});
}
public CpfJFrame42(final Component component, final int w, final int h) {
this.w = w;
this.h = h;
component.setSize(w, h);
addComponentListener(new ComponentListener() {
#Override
public void componentShown(final ComponentEvent e) {
}
#Override
public void componentResized(final ComponentEvent e) {
locateSlider(jWindow);
}
#Override
public void componentMoved(final ComponentEvent e) {
locateSlider(jWindow);
}
#Override
public void componentHidden(final ComponentEvent e) {
}
});
jWindow = new JDialog(this) {
#Override
public void doLayout() {
if (isSlideInProgress) {
}
else {
super.doLayout();
}
}
};
jWindow.setModal(false);
jWindow.setUndecorated(true);
jWindow.setSize(component.getWidth(), component.getHeight());
jWindow.getContentPane().add(component);
locateSlider(jWindow);
jWindow.setVisible(true);
if (useSlideButton) {
basePanel = new JPanel();
basePanel.setLayout(new BorderLayout());
final JPanel statusPanel = new JPanel();
basePanel.add(statusPanel, BorderLayout.SOUTH);
statusPanel.add(new JButton("Open") {
private static final long serialVersionUID = 9204819004142223529L;
{
setMargin(new Insets(0, 0, 0, 0));
}
{
addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
slide(OPEN);
}
});
}
});
statusPanel.add(new JButton("Close") {
{
setMargin(new Insets(0, 0, 0, 0));
}
private static final long serialVersionUID = 9204819004142223529L;
{
addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
slide(CLOSE);
}
});
}
});
{
//final BufferedImage bufferedImage = ImageFactory.getInstance().createTestImage(200, false);
//final ImageIcon icon = new ImageIcon(bufferedImage);
//basePanel.add(new JButton(icon), BorderLayout.CENTER);
}
getContentPane().add(basePanel);
}
}
private void locateSlider(final JDialog jWindow) {
if (jWindow != null) {
final int x = getLocation().x + getWidth() + GAP;
final int y = getLocation().y + 10;
jWindow.setLocation(x, y);
}
}
private void enableUserInput() {
getGlassPane().setVisible(false);
}
private void disableUserInput() {
setGlassPane(glassPane);
}
public void slide(final int slideType) {
if (!isSlideInProgress) {
isSlideInProgress = true;
final Thread t0 = new Thread(new Runnable() {
#Override
public void run() {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
disableUserInput();
slide(true, slideType);
enableUserInput();
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
isSlideInProgress = false;
}
});
t0.setDaemon(true);
t0.start();
}
else {
Toolkit.getDefaultToolkit().beep();
}
}
private void slide(final boolean useLoop, final int slideType) {
synchronized (lock) {
for (int x = 0; x < w; x += 25) {
if (slideType == OPEN) {
jWindow.setSize(x, h);
}
else {
jWindow.setSize(getWidth() - x, h);
}
jWindow.repaint();
try {
Thread.sleep(42);
} catch (final Exception e) {
e.printStackTrace();
}
}
if (slideType == OPEN) {
jWindow.setSize(w, h);
}
else {
jWindow.setSize(MIN, h);
}
jWindow.repaint();
}
}
}
Hey guys I'm new to Java game programming and I'm working with the Runnable interface right now. For some reason, my run() method never gets called and I'm not sure why. I've tried putting many System.out.println statements in there but they never get printed. Any help would be greatly appreciated!
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable
{
private final int WIDTH = 160;
private final int HEIGHT = WIDTH/12 *9;
private final int RATIO = 3;
private Thread animator;
private volatile boolean running;
private volatile boolean gameOver;
private double FPS = 60D;
private double period = 1000/FPS;
private Image dbImage;
private Graphics dbg;
public GamePanel()
{
setPreferredSize(new Dimension(WIDTH *3, HEIGHT*3));
setBackground(Color.WHITE);
setFocusable(true);
requestFocus();
terminate();
}
public void addNotify()
{
super.addNotify();
startGame();
}
public void startGame()
{
System.out.println("Thread started");
animator = new Thread();
animator.start();
}
public void stopGame()
{
System.out.println("Thread stopped");
running = false;
}
public void run()
{
long beforeTime, timeDiff, sleepTime;
beforeTime = System.currentTimeMillis();
System.out.println(beforeTime);
running = true;
while (running)
{
System.out.println("Running");
gameUpdate();
gameRender();
paintScreen();
timeDiff = System.currentTimeMillis() - beforeTime;
sleepTime = (long) period - timeDiff;
if(sleepTime <= 0)
sleepTime = 5;
try
{
Thread.sleep(sleepTime);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
beforeTime = System.currentTimeMillis();
}
System.exit(0);
}
public void gameRender()
{
if (dbImage == null)
{
dbImage = createImage(WIDTH, HEIGHT);
}
else
dbg = dbImage.getGraphics();
dbg.setColor(Color.WHITE);
dbg.fillRect(0, 0, WIDTH, HEIGHT);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(dbImage, 0, 0, null);
}
public void gameUpdate()
{
}
private void paintScreen()
{
Graphics g;
try
{
g = this.getGraphics();
if (g!= null && dbImage!= null)
g.drawImage(dbImage, 0, 0, null);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
public void terminate()
{
addKeyListener (new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_ESCAPE)
{
stopGame();
}
}
});
}
}
import javax.swing.JFrame;
public class GameFrame extends JFrame
{
private final int WIDTH = 160;
private final int HEIGHT = WIDTH/12*9;
private final int RATIO = 3;
public GameFrame()
{
setTitle("User Input Game");
setSize(WIDTH*3,HEIGHT*3);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
GamePanel mainPanel = new GamePanel();
add(mainPanel);
}
}
public class Main
{
public static void main(String[] args)
{
new GameFrame().setVisible(true);
}
}
You need to change your startGame() method:
animator = new Thread(new GamePanel());
You need to pass a Runnable (of which GamePanel is one) into the Thread constructor. The thread then runs the runnable when it starts.
You don't seem to have a main method anywhere. Either in this class or an external class you need a main method that creates an instance of GamePanel and pass it as an argument to a Thread class. Like so:
public class Test
{
public static void main(String[] args)
{
Thread t = new Thread(new GamePanel()).start();
}
}