I am making a platformer game for a project for class and need to have a chicken character jump on some platforms. I have a start screen and a button, and when the button is clicked, it will change the frame to the first level. When I add the chicken character to the frame as well as the background image, all I can see is the background image. Should I be using a different layout or is there something else I can do. This is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Main extends JFrame {
public Main(){
//Creates Chicken Character
final JLabel chicken = new JLabel(" ");
ImageIcon chick1 = new ImageIcon("chicken.gif");
ImageIcon chick2 = new ImageIcon("chicken2.gif");
chicken.setIcon(chick1);
//Sets Chicken Location
chicken.setLocation(1, 1);
//Creates Title Image
JLabel title = new JLabel(" ");
ImageIcon tl = new ImageIcon("title.gif");
title.setIcon(tl);
//Creates Start Image
final JButton start = new JButton("");
ImageIcon st = new ImageIcon("start.gif");
start.setIcon(st);
//Creates Options Image
JButton options = new JButton("");
ImageIcon opt = new ImageIcon("options.gif");
options.setIcon(opt);
options.setBackground(Color.BLACK);
//Creates label for level 0 background image
JLabel background = new JLabel(" ");
ImageIcon back = new ImageIcon("level0.gif");
background.setIcon(back);
//Creates a panel for level 0
final JPanel p5 = new JPanel();
chicken.setLocation(1, 1);
p5.add(background);
//Create first frame for "Start" button
final JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 1));
p1.add(start, BorderLayout.CENTER);
//Create second panel for title label
final JPanel p2 = new JPanel(new BorderLayout());
p2.setLayout(new GridLayout(1, 3));
p2.add(title, BorderLayout.WEST);
//Create third panel for "Options" button
final JPanel p3 = new JPanel(new BorderLayout());
p3.setLayout(new GridLayout(1, 1));
p3.add(options, BorderLayout.SOUTH);
//Creates fourth panel to organize all other primary
final JPanel p4 = new JPanel(new BorderLayout());
p4.setLayout(new GridLayout(1, 3));
p4.add(p1, BorderLayout.WEST);
p4.add(p2, BorderLayout.CENTER);
p4.add(p3, BorderLayout.EAST);
//When button is clicked, it changes the level
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(start.isEnabled()) {
remove(p4);
add(new ContentPanel());
add(chicken);
chicken.setLocation(100, 100);
setSize(1440, 500);
setLocale(null);
chicken.isOpaque();
validate();
}
else {
return;
}
}
});
//Adds fourth panel to frame
add(p4, BorderLayout.CENTER);
}
public static void main(String arg[]) {
Main frame = new Main();
//Finds screen size of monitor
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//Creates the frame
frame.setTitle("Cockadoodle Duty: Awakening");
frame.setSize(screenSize);
frame.setLocale(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
String background = "#000000";
frame.setBackground(Color.decode(background));
}
}
class ContentPanel extends JPanel{
Image bgimage = null;
ContentPanel() {
MediaTracker mt = new MediaTracker(this);
bgimage = Toolkit.getDefaultToolkit().getImage("level0.gif");
mt.addImage(bgimage, 0);
try {
mt.waitForAll();
} catch (InterruptedException e){
e.printStackTrace();
}
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
int imwidth = bgimage.getWidth(null);
int imheight = bgimage.getHeight(null);
g.drawImage(bgimage, 1, 1, null);
}
}
Note: It's been a while since I used the Graphics API
Quick Answer:
You need to draw everything in your paintComponent method. Your drawing routine should check the state of all game objects and draw them accordingly. Right now the panel is drawing the background image - that's it. Add your chicken image the same way you added your bgImage.
Some more things to consider:
If you experience screen flicker look into Double Buffering.
Not to overwhelm you but you might want to do some light reading on game coding. Get a general idea on how to code your game loop and what happens each time the loop is executed.
Since you are using an OO language you should also probably make a Chicken class.
public class Chicken {
private int x;
private int y;
private Image chickenSprtie;
//add get / set for access
}
Or even a general Super Class - Sprite with int x, int y. Or even a "Drawable" interface to forces all your drawable game objects to have common methods....
Related
I'm making a simple POS system on NetBeans that would pop out a JPanel (quantity) asking for the quantity when the photo of the product is clicked. I am using a card layout and putting the panel inside the card layout doesn't seem to work as it is different in size. It's also very hard to position it since moving it makes a bigger panel (buy) absorb it and becomes a part of the panel, messing up the layout of that panel. I want to make the panel initially invisible and pop up only with this code:
public void mouseClicked(MouseEvent e) {
if (e.getSource() == bpie )
{
String name = "Banoffee Pie";
int price = 8;
quantity.setVisible(true);
}
}
I'm currently a beginner and have a hard time customizing JOptionPane dialogs and prefer the use of panels if possible. The problem could be solved with the use of another JFrame, however, the use of multiple frames according to experts, is bad practice.
Here is how I want the option pane to look:
I'm currently a beginner and have a hard time customizing JOptionPanes
The JOptionPane was made for utility rather than customizability. As soon as you start thinking 'How can I change a JOptionPane to..?' abandon the option pane and instead use a modal JDialog.
Here is an example of using a dialog. I've tweaked the layout along these lines:
The food icons centered below the title bar.
Abandoned the simpler button names for more descriptive ones.
Adding the question and answer in the same line with a spinner to choose the number.
Of course, colors need to be adjusted to suit the style seen above, which might (and might not - depending on further factors not immediately evident) best be approached by using a custom Pluggable Look and Feel.
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;
public class SweetShop {
private JComponent ui = null;
private static JFrame frame = new JFrame("Sweet Shop");
private final JDialog dialog = new JDialog(frame, "Choose Sweets", true);
Random random = new Random();
SpinnerNumberModel quantityModel = new SpinnerNumberModel(1, 1, 144, 1);
SweetShop() {
initUI();
}
public final void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout());
ui.setBorder(new EmptyBorder(40,100,40,100));
JButton button = new JButton("Buy Sweets");
ui.add(button);
ActionListener openChooserListener = (ActionEvent e) -> {
dialog.setLocationRelativeTo(button);
dialog.setVisible(true);
};
button.addActionListener(openChooserListener);
dialog.add(getSweetSelectionPanel());
dialog.pack();
}
private JPanel getSweetSelectionPanel() {
JPanel panel = new JPanel(new BorderLayout());
int pad = 10;
panel.setBorder(new EmptyBorder(pad, pad, pad, pad));
JPanel iconPanel = new JPanel();
for (int ii=0; ii<12; ii++) {
iconPanel.add(new JLabel(new ImageIcon(getSize16Image())));
}
panel.add(iconPanel, BorderLayout.PAGE_START);
JPanel buttonPanel = new JPanel();
JButton okButton = new JButton("Buy Delicious");
buttonPanel.add(okButton);
ActionListener okListener = (ActionEvent e) -> {
System.out.println("Yuuuummmmm.. x " +
quantityModel.getNumber().intValue());
dialog.setVisible(false);
};
okButton.addActionListener(okListener);
JButton cancelButton = new JButton("No Thanks");
buttonPanel.add(cancelButton);
ActionListener cancelListener = (ActionEvent e) -> {
System.out.println("I just like licking them.");
dialog.setVisible(false);
};
cancelButton.addActionListener(cancelListener);
panel.add(buttonPanel, BorderLayout.PAGE_END);
JPanel questionPanel = new JPanel();
questionPanel.setBorder(new EmptyBorder(20, 50, 20, 50));
panel.add(questionPanel); // automatically uses CENTER constraint
JLabel label = new JLabel("How many do you wish to buy?");
Font font = label.getFont();
label.setFont(font.deriveFont(Font.ITALIC));
label.setText("How many do you wish to buy?");
label.setBorder(new EmptyBorder(5, 5, 5, 5));
questionPanel.add(label);
JSpinner spinner = new JSpinner(quantityModel);
questionPanel.add(spinner);
return panel;
}
private Image getSize16Image() {
int w = 16;
int h = 16;
if (random.nextBoolean()) {
w = random.nextInt(12) + 4;
} else {
h = random.nextInt(12) + 4;
}
BufferedImage bi = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
return bi;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
SweetShop o = new SweetShop();
frame = new JFrame(o.getClass().getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setContentPane(o.getUI());
frame.pack();
frame.setMinimumSize(frame.getSize());
frame.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
I want to place the button below the "898 Food Restaurant" Jlabel. The setLocation() for button not working.
public class MainMenu extends JPanel{
JLabel picLabel,title;
JButton button;
public MainMenu() throws IOException
{
JPanel panel = new JPanel(new BorderLayout());
BufferedImage myPicture = ImageIO.read(new File("C:\\Users\\seng\\workspace\\FoodOrderingSystem\\ramen-noodles.png"));
Image scaled = myPicture.getScaledInstance(170,170,Image.SCALE_SMOOTH);
picLabel = new JLabel(new ImageIcon(scaled));
title = new JLabel("898 Food Restaurant");
title.setFont(new Font("Serif",Font.ITALIC+Font.BOLD,18));
title.setForeground(Color.BLUE);
button = new JButton("Order Food Now >>");
button.setLocation(40,380);
button.setSize(40,80);
panel.add(picLabel,BorderLayout.CENTER);
panel.add(title,BorderLayout.SOUTH);
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
add(buttonPanel);
add(panel);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
OrderMainPage order = new OrderMainPage();
}
});
}
public static void main(String args[]) throws IOException
{
MainMenu main = new MainMenu();
JFrame frame = new JFrame();
frame.setTitle("898 Food Ordering System");
frame.add(main);
// frame.setSize(120,130);
frame.pack(); // size
frame.setLocationRelativeTo(null); // place frame in center
frame.setVisible(true);
}
}
Each JComponent such as JPanel can only have one layout manager at a time. But since JComponents can be nested you can have different layout managers in your JFrame. Usually that is how you create complex layouts.
Now for your question about button placement. The setLocation won't do anything since your button is in JPanel and it by default uses FlowLayout that ignores location attribute. First step is to set buttonPanel layout to null. But that still might not be enough since the buttonPanel is positioned by another flow layout that will set it's bounds not within the location coordinates of the nested button.
You can always see your JPanel bounds by setting it's background to a different color.
My advice to always try to position your components using layout managers and avoid absolute positioning.
you can use BoxedLayout in place of FrameLayout :
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
class MainMenu extends Frame {
JLabel picLabel,title;
JButton button;
public MainMenu () {
JPanel panel = new JPanel(new BorderLayout());
try{
BufferedImage myPicture = ImageIO.read(new File("C:\\Users\\seng\\workspace\\FoodOrderingSystem\\ramen-noodles.png"));
Image scaled = myPicture.getScaledInstance(170,170,Image.SCALE_SMOOTH);
picLabel = new JLabel(new ImageIcon(scaled));}catch(Exception e){}
title = new JLabel("898 Food Restaurant");
title.setFont(new Font("Serif",Font.ITALIC+Font.BOLD,18));
title.setForeground(Color.BLUE);
button = new JButton("Order Food Now >>");
panel.add(picLabel,BorderLayout.CENTER);
panel.add(title,BorderLayout.SOUTH);
JPanel buttonPanel = new JPanel();
buttonPanel.add(button);
add(panel);
add(buttonPanel);
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}
public static void main(String args[]){
MainMenu main = new MainMenu();
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a java swing project that looks like this:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.Box;
import javax.swing.BoxLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class DiceGameReplaceDice extends JFrame
{
private JFrame gameFrame;
private JPanel mainPanel;
private JPanel centerPanel = new JPanel();
private JButton diceArray[];
private DiceListener diceListener = new DiceListener();
private ButtonListener buttonListener = new ButtonListener();
private Random rand = new Random();
private int NUM_DICE = 2;
private String diceImages[] = {"./src/1.png", "./src/2.png", "./src/3.png",
"./src/4.png", "./src/5.png", "./src/6.png"};
public static void main(String[] args)
{
new DiceGameReplaceDice();
}
public DiceGameReplaceDice()
{
// Initialize the frame that holds the game
gameFrame = new JFrame();
gameFrame.setSize(800, 600);
gameFrame.setLocation(300, 100);
gameFrame.setTitle("Dice Game");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add Panel
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
// Instantiate a ButtonListener
buttonListener = new ButtonListener();
// Add 1 Button and 1 Label to a newly created panel
// Add new panel to West
JButton buttonW1 = new JButton("Add Die");
buttonW1.setName("W1");
buttonW1.addActionListener(buttonListener);
JPanel panelWest = new JPanel();
panelWest.setLayout(new BoxLayout(panelWest,BoxLayout.Y_AXIS ));
panelWest.setBackground(new Color(0, 0, 122)); // set to blue
panelWest.add(Box.createVerticalGlue());
panelWest.add(buttonW1);
panelWest.add(Box.createVerticalGlue());
mainPanel.add(panelWest, BorderLayout.WEST);
// Create and display center panel with dice
displayCenterPanel();
// Add mainPanel to frame and display the frame
gameFrame.add(mainPanel);
gameFrame.setVisible(true);
}
private void displayCenterPanel()
{
centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel,BoxLayout.X_AXIS ));
centerPanel.setBackground(new Color(0, 122, 0)); // set to green
centerPanel.add(Box.createHorizontalGlue());
diceArray = new JButton[NUM_DICE];
// Add 2 Buttons to center panel with images of 2 random dice
for (int i=0; i<NUM_DICE; i++)
{
// Create dice button
int dieNum = rand.nextInt(6)+1;
diceArray[i] = new JButton(new ImageIcon(diceImages[dieNum-1]));
diceArray[i].setName("Dice" + i);
diceArray[i].addActionListener(diceListener);
// Add to center panel
centerPanel.add(diceArray[i]);
centerPanel.add(Box.createHorizontalGlue());
}
mainPanel.add(centerPanel, BorderLayout.CENTER);
// Add mainPanel to frame and display the frame
gameFrame.add(mainPanel);
gameFrame.setVisible(true);
}
// Implement an (inner) class that implements ActionListener
class DiceListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
NUM_DICE -= 1;
displayCenterPanel();
}
}
// Implement an (inner) class that implements ActionListener
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String button = ((JButton)e.getSource()).getName();
System.out.println("Button Pressed: " + button);
if (button.equals("W1"))
NUM_DICE ++;
System.out.println(NUM_DICE);
displayCenterPanel();
}
}
}
When Clicking the "Add Die" button, a die is added to the screen and is correctly formatted. However, when a die is pressed, and the NUM_DICE is decreased, clicking on the die button results in weird overlaps and "ghost buttons". How do you fix this?
The quick fix would be to remove the centerPanel prior to adding the new one. Add the line
mainPanel.remove(centerPanel);
as the first thing you do inside displayCenterPanel.
However, your way of manipulating the layout dynamically leaves a lot to be desired. Instead of creating a new panel each time, just modify the existing one:
public class DiceGame {
private JPanel centerPanel = new JPanel();
private Random rand = new Random();
private int numDice = 2;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new DiceGame());
}
public DiceGame() {
JFrame gameFrame = new JFrame();
gameFrame.setSize(800, 600);
gameFrame.setTitle("Dice Game");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JButton buttonW1 = new JButton("Add Die");
buttonW1.addActionListener(e -> {
numDice++;
updateCenterPanel();
});
JPanel panelWest = new JPanel();
panelWest.setLayout(new BoxLayout(panelWest, BoxLayout.Y_AXIS));
panelWest.setBackground(new Color(0, 0, 122));
panelWest.add(Box.createVerticalGlue());
panelWest.add(buttonW1);
panelWest.add(Box.createVerticalGlue());
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.X_AXIS));
centerPanel.setBackground(new Color(0, 122, 0));
mainPanel.add(panelWest, BorderLayout.WEST);
mainPanel.add(centerPanel);
gameFrame.add(mainPanel);
gameFrame.setVisible(true);
}
private void updateCenterPanel() {
centerPanel.removeAll();
centerPanel.add(Box.createHorizontalGlue());
JButton[] diceArray = new JButton[numDice];
for (int i = 0; i < numDice; i++) {
diceArray[i] = new JButton(Integer.toString(rand.nextInt(6) + 1));
diceArray[i].setName("Dice" + i);
diceArray[i].addActionListener(e -> {
numDice--;
updateCenterPanel();
});
centerPanel.add(diceArray[i]);
centerPanel.add(Box.createHorizontalGlue());
}
centerPanel.revalidate();
centerPanel.repaint();
}
}
Revalidating and repainting is necessary after invalidating the component hierarchy.
Notes:
Don't create fields when local variables will do.
NUM_DICE is not final, so it should be named numDice.
Calling gameFrame.setVisible(true); when it is already visible does nothing.
When you have a working version of whatever it is you are doing, replace setSize(...) on the JFrame with pack and be sure to calculate the size of its children properly.
I am making a platformer game for a class project and so far all I have been able to do is add the chicken character to the game. I need to be able to have him move forward on the press of "D" or right arrow. My code is:
public class Main extends JFrame {
public Main(){
//Creates Title Image
JLabel title = new JLabel(" ");
ImageIcon tl = new ImageIcon("title.gif");
title.setIcon(tl);
//Creates Start Image
final JButton start = new JButton("");
ImageIcon st = new ImageIcon("start.gif");
start.setIcon(st);
//Creates Options Image
JButton options = new JButton("");
ImageIcon opt = new ImageIcon("options.gif");
options.setIcon(opt);
options.setBackground(Color.BLACK);
//Create first frame for "Start" button
final JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 1));
p1.add(start, BorderLayout.CENTER);
//Create second panel for title label
final JPanel p2 = new JPanel(new BorderLayout());
p2.setLayout(new GridLayout(1, 3));
p2.add(title, BorderLayout.WEST);
//Create third panel for "Options" button
final JPanel p3 = new JPanel(new BorderLayout());
p3.setLayout(new GridLayout(1, 1));
p3.add(options, BorderLayout.SOUTH);
//Creates fourth panel to organize all other primary
final JPanel p4 = new JPanel(new BorderLayout());
p4.setLayout(new GridLayout(1, 3));
p4.add(p1, BorderLayout.WEST);
p4.add(p2, BorderLayout.CENTER);
p4.add(p3, BorderLayout.EAST);
//When button is clicked, it changes the level
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(start.isEnabled()) {
remove(p4);
setSize(1440, 500);
add(new ContentPanel1());
validate();
}
else {
return;
}
}
});
//Adds fourth panel to frame
add(p4, BorderLayout.CENTER);
}
public static void main(String arg[]) {
Main frame = new Main();
//Finds screen size of monitor
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//Creates the frame
frame.setTitle("Cockadoodle Duty: Awakening");
frame.setSize(screenSize);
frame.setLocale(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
String background = "#000000";
frame.setBackground(Color.decode(background));
}
}
class coordinate {
public static int x;
public static int y;
}
class ContentPanel1 extends JPanel{
Image back = Toolkit.getDefaultToolkit().getImage("level0.gif");
Image chick = Toolkit.getDefaultToolkit().getImage("chicken.gif");
ContentPanel1() {
MediaTracker mt = new MediaTracker(this);
mt.addImage(back, 0);
try {
mt.waitForAll();
} catch (InterruptedException e){
e.printStackTrace();
}
}
public void paintComponent(Graphics g){
coordinate.x = 20;
coordinate.y = 321;
super.paintComponent(g);
int imwidth = back.getWidth(null);
int imheight = back.getHeight(null);
g.drawImage(back, 1, 1, null);
g.drawImage(chick, coordinate.x, coordinate.y, null);
}
public void MoveDirection(KeyEvent e, Graphics g) {
coordinate.x = 20;
coordinate.y = 321;
super.paintComponent(g);
int key = e.getKeyCode();
if(key == 68) {
coordinate.x += 1;
g.drawImage(chick, coordinate.x, coordinate.y, null);
}
}
}
The main trouble I have been having with my code is the bit at the end with the MoveDirection method. The way I have it going is by adding a new chicken to the frame (This was mainly due to the fact that I was just testing to see if the code worked). Is there a better way to do that too?
Start by taking a look at How to Use Key Bindings
NEVER call super.paintComponent(g); (or paintComponent(g);) directly from outside the context of the paintComponent method, there is a lot more to painting then just painting the component background. See Painting in AWT and Swing and Performing Custom Painting for more details. Instead, simply call repaint when you want to, well, repaint the component.
The use of MediaTracker is out of date and you should be using the ImageIO API instead, which will block automatically while reading the image. See Reading/Loading an Image for more details
Don't use Toolkit.getDefaultToolkit().getScreenSize() in combination with JFrame#setSize, the getScreenSize method does not take into account things like the task bar or dock of some OS's, instead use the JFrame#setExtendedState and pass it JFrame.MAXIMIZED_BOTH
frame.setLocale(null); isn't doing what you think it is
I need to make a scrolling background for this platformer. It needs to scroll a 2400x500 image while the frame size is about 1440x900. If it could just gradually change over time that would be great. This is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class Main extends JFrame {
public Main() {
//Creates Title Image
JLabel title = new JLabel(" ");
ImageIcon tl = new ImageIcon("title.gif");
title.setIcon(tl);
//Creates Start Image
final JButton start = new JButton("");
ImageIcon st = new ImageIcon("start.gif");
start.setIcon(st);
//Creates Options Image
JButton options = new JButton("");
ImageIcon opt = new ImageIcon("options.gif");
options.setIcon(opt);
options.setBackground(Color.BLACK);
//Creates label for level 0 background image
JLabel background = new JLabel(" ");
ImageIcon back = new ImageIcon("level0.gif");
background.setIcon(back);
//Creates a panel for level 0
final JPanel p5 = new JPanel();
p5.setLayout (new BorderLayout(1, 1));
p5.add(background);
//Create first frame for "Start" button
final JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(1, 1));
p1.add(start, BorderLayout.CENTER);
//Create second panel for title label
final JPanel p2 = new JPanel(new BorderLayout());
p2.setLayout(new GridLayout(1, 3));
p2.add(title, BorderLayout.WEST);
//Create third panel for "Options" button
final JPanel p3 = new JPanel(new BorderLayout());
p3.setLayout(new GridLayout(1, 1));
p3.add(options, BorderLayout.SOUTH);
//Creates fourth panel to organize all other primary
final JPanel p4 = new JPanel(new BorderLayout());
p4.setLayout(new GridLayout(1, 3));
p4.add(p1, BorderLayout.WEST);
p4.add(p2, BorderLayout.CENTER);
p4.add(p3, BorderLayout.EAST);
//When button is clicked, it changes the level
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(start.isEnabled()) {
remove(p4);
add(p5, BorderLayout.CENTER);
invalidate();
validate();
}
else {
return;
}
}
});
//Adds fourth panel to frame
add(p4, BorderLayout.CENTER);
}
public static void main(String args[]) {
Main frame = new Main();
//Finds screen size of monitor
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//Creates the frame
frame.setTitle("Cockadoodle Duty: Awakening");
frame.setSize(screenSize);
frame.setLocale(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
String background = "#000000";
frame.setBackground(Color.decode(background));
}
}
Add the label containing the icon to a scroll panel
Use a Swing Timer to schedule the scrolling
When the Timer fires you can scroll background.
The scrolling code might be something like:
JViewport viewport = scrollPane.getViewport();
Point position = viewport.getViewPosition();
position.x += 2;
viewport.setViiewPosition( position );