Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: Button in borderlayout

  1. #1
    Junior Member
    Join Date
    Feb 2022
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Exclamation Button in borderlayout

    I'm new to java and are working on my first big projekt which is a game. In this tower defence game I want a couple of menues, to both display information and have bottuns. To make this i'm using BorderLayout(), but I can't figure out how to use it proberly. Here are my code:

    Main class:

    public class VectorTD{
     
        public static void main(String[] args) {
     
            // Creates the display
            GameFrame frame = new GameFrame();
     
        }
    }

    GameFrame class that draws everthing:

     
    /pakke der styrer farver
    import java.awt.Color;
    import javax.swing.*;
    //Pakke der hjælper med at lave vinduet
    import javax.swing.JFrame;
     
    import java.awt.*;
     
    public class GameFrame extends JFrame {
     
        static final int SCREEN_WIDTH = 1000;
        static final int SCREEN_HEIGHT = 1000;
     
     
        GameFrame() {
            this.setLayout(new BorderLayout());
     
            //the bottun
            this.add(new Menu(), BorderLayout.NORTH);
     
     
            //the game
            this.add(new GamePanel(), BorderLayout.CENTER);
     
     
            pack();
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
     
            this.setBackground(Color.BLACK);
     
            setVisible(true);
     
     
            setResizable(false);
     
     
     
        }
     
    }

    Class that should make the bottun


     
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Graphics;
    import javax.swing.JButton;
     
    public class Menu extends JPanel{
     
     
     
        Menu() {
            JButton b=new JButton("Click Here");
            b.setBounds(50,100,95,30);  
            this.add(b);  
     
     
        }
     
        private void makeTopMenu() {
     
     
        }
     
    }

    GamePanel class:

     
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Graphics;
     
    public class GamePanel extends JPanel implements Runnable {
     
        static Graphics graphics;
        final static int FPS = 100;
        final static public long SKIP_TICKS = 1000000000 / FPS;
     
        static public int lives = 25;
        static public int money = 100;
        static public boolean roundStart = false;
     
        GamePanel() {
            new Thread(this).start();
     
            Square.makeGrid();
            Vectoid.makeVectoids();
     
        }
     
        public void paint(Graphics g) {
            Image image = createImage(GameFrame.SCREEN_WIDTH, GameFrame.SCREEN_HEIGHT);
            graphics = image.getGraphics();
            draw(graphics);
            g.drawImage(image, 0, 0, this);
     
        }
     
        public void draw(Graphics g) {
            Square.drawGrid(g);
            if (roundStart==true){
            for (int i = 0; i < Vectoid.currentNumberOfVectoids; i++) {
                if (Vectoid.listOfVectoids[i].dead == false) {
                    Vectoid.listOfVectoids[i].draw(g);
                    Vectoid.listOfVectoids[i].move();
                }
            }
        }
            Toolkit.getDefaultToolkit().sync();
        }
     
        // Gameloop
        public void run() {
            // long then = System.nanoTime();
            // The gameloop runs until the program is closed
            while (true) {
                // Saves the current time
                long now = System.nanoTime();
     
                repaint();
     
                // After the game has been updated, the program needs to wait until next
                // gameupdate. This waiting time is determined by the FPS variable.
                long sleeptime = SKIP_TICKS - (System.nanoTime() - now);
                if (sleeptime >= 0) {
                    try {
                        Thread.sleep(sleeptime / 1000000);
                    } catch (Exception e) {
                        System.out.println("Error: Can't sleep.");
                    }
                }
                // If sleeptime < 0, the program is not updated fast enough
                else {
                    System.out.println("We are running behind");
                }
            }
        }
     
    }

    Square class:

     
    import java.awt.*;
    import java.awt.Color;
     
    public class Square extends Rectangle {
     
      static int rows = 15;
      static int collums = 15;
     
      public static Square grid[][] = new Square[rows][collums];
      public static int[][] makeMap = { { 0, 0 }, { 5, 0 }, { 5, 5 }, { 3, 5 }, { 3, 3 }, { 0, 3 }, { 0, 10 }, { 10, 10 },
          { 10, 5 }, { 14, 5 } };
     
      int x, y;
      static int width = 50;
      int strokeWeigth = 2;
     
      Color bodyColor = new Color(29, 69, 64);
      Color strokeColor = new Color(0, 0, 0);
      boolean isTowerPlacebel = true;
     
      public static int[][] vectoidRoute;
     
      Square(int x, int y) {
        this.x = x;
        this.y = y;
      }
     
      private void draw(Graphics g) {
        g.setColor(strokeColor);
        g.fillRect(x, y, width, width);
        g.setColor(bodyColor);
        g.fillRect(x + strokeWeigth, y + strokeWeigth, width - strokeWeigth * 2, width - strokeWeigth * 2);
      }
     
      public static void makeGrid() {
        for (int i = 0; i < collums; i++) {
          for (int j = 0; j < rows; j++) {
     
            grid[i][j] = new Square(i * 50, j * 50 + 130);
          }
        }
        makeMap();
        calculateRouteLength();
        makeVectoidRoute();
      }
     
      public static void drawGrid(Graphics g) {
        for (int i = 0; i < collums; i++) {
          for (int j = 0; j < rows; j++) {
            grid[i][j].draw(g);
          }
        }
      }
     
      private static void makeMap() {
     
        for (int i = 1; i < makeMap.length; i++) {
     
          if (makeMap[i - 1][0] < makeMap[i][0]) {
     
            for (int j = makeMap[i - 1][0]; j <= makeMap[i][0]; j++) {
     
              grid[j][makeMap[i][1]].isTowerPlacebel = false;
              grid[j][makeMap[i][1]].bodyColor = new Color(0, 41, 0);
            }
          } else if (makeMap[i - 1][1] < makeMap[i][1]) {
     
            for (int j = makeMap[i - 1][1]; j <= makeMap[i][1]; j++) {
     
              grid[makeMap[i][0]][j].isTowerPlacebel = false;
              grid[makeMap[i][0]][j].bodyColor = new Color(0, 41, 0);
            }
     
          } else if (makeMap[i - 1][0] > makeMap[i][0]) {
     
            for (int j = makeMap[i - 1][0]; j >= makeMap[i][0]; j--) {
     
              grid[j][makeMap[i][1]].isTowerPlacebel = false;
              grid[j][makeMap[i][1]].bodyColor = new Color(0, 41, 0);
            }
     
          } else if (makeMap[i - 1][1] > makeMap[i][1]) {
     
            for (int j = makeMap[i - 1][1]; j >= makeMap[i][1]; j--) {
     
              grid[makeMap[i][0]][j].isTowerPlacebel = false;
              grid[makeMap[i][0]][j].bodyColor = new Color(0, 41, 0);
            }
          }
        }
      }
     
      private static void calculateRouteLength() {
        int length = 0;
     
        for (int i = 1; i < makeMap.length; i++) {
     
          length += Math.abs(grid[makeMap[i][0]][makeMap[i][1]].x - grid[makeMap[i - 1][0]][makeMap[i - 1][1]].x);
          length += Math.abs(grid[makeMap[i][0]][makeMap[i][1]].y - grid[makeMap[i - 1][0]][makeMap[i - 1][1]].y);
     
        }
        length += width * 2;
     
        vectoidRoute = new int[length + 1][2];
      }
     
      private static void makeVectoidRoute() {
     
        int number = 0;
        int x2 = 0;
        int y2 = 0;
     
        for (int i = 1; i < makeMap.length; i++) {
     
          int x1 = grid[makeMap[i - 1][0]][makeMap[i - 1][1]].x;
          int y1 = grid[makeMap[i - 1][0]][makeMap[i - 1][1]].y;
     
          x2 = grid[makeMap[i][0]][makeMap[i][1]].x;
          y2 = grid[makeMap[i][0]][makeMap[i][1]].y;
     
          int xDist = x2 - x1;
          int yDist = y2 - y1;
     
          if (i == 1) {
     
            if (xDist > 0) {
              x1 -= 50;
              xDist += 50;
            } else if (xDist < 0) {
     
              x1 += 50;
              xDist -= 50;
            } else if (yDist > 0) {
              y1 -= 50;
              yDist += 50;
     
            } else {
              y1 += 50;
              yDist -= 50;
            }
          } else if (i == makeMap.length - 1) {
     
            if (xDist > 0) {
              x2 += 50;
              xDist += 50;
            } else if (xDist < 0) {
     
              x2 -= 50;
              xDist -= 50;
            } else if (yDist > 0) {
              y2 += 50;
              yDist += 50;
     
            } else {
              y2 -= 50;
              yDist -= 50;
            }
          }
     
          if (xDist > 0 || yDist > 0) {
     
            for (int j = 0; j != xDist + yDist; j++) {
     
              if (yDist == 0) {
                vectoidRoute[number][0] = x1 + j;
                vectoidRoute[number][1] = y1;
     
              } else {
                vectoidRoute[number][0] = x1;
                vectoidRoute[number][1] = y1 + j;
     
              }
              number++;
            }
          } else {
     
            for (int j = 0; j != Math.abs(xDist + yDist); j++) {
     
              if (yDist == 0) {
                vectoidRoute[number][0] = x1 - j;
                vectoidRoute[number][1] = y1;
     
              } else {
                vectoidRoute[number][0] = x1;
                vectoidRoute[number][1] = y1 - j;
     
              }
              number++;
            }
          }
     
        }
     
        vectoidRoute[number][0] = x2;
        vectoidRoute[number][1] = y2;
     
      }
     
    }



    Last class:

    import java.awt.*;
    import java.awt.Color;
     
    public class Vectoid {
     
        static int maxNumberOfVectoids = 10;
        static int currentNumberOfVectoids = 0;
        public static Vectoid listOfVectoids[] = new Vectoid[10];
     
        int radius = 50;
        float distance = 0;
        int x = Square.vectoidRoute[Math.round(distance)][0];
        int y = Square.vectoidRoute[Math.round(distance)][1];
        float speed = 3;
        int timer = 0;
        int slowTime = 0;
        float slowSpeed = 0;
        int health = 100;
        Color bodyColor = new Color(255, 0, 0);
        boolean dead = false;
     
        public void draw(Graphics g) {
            x = Square.vectoidRoute[Math.round(distance)][0];
            y = Square.vectoidRoute[Math.round(distance)][1];
            g.setColor(bodyColor);
            g.fillOval(x, y, radius, radius);
        }
     
        public void move() {
            distance += speed;
            outOfMap();
        }
     
        private void outOfMap() {
            if (distance >= Square.vectoidRoute.length) {
                dead = true;
                GamePanel.lives -= 1;
     
            }
        }
     
        public void takeDamage(int damage) {
            health -= damage;
     
            if (health <= 0) {
                dead = true;
                GamePanel.money += 10;
            }
        }
     
        public static void makeVectoids() {
            for (int i = 0; i < maxNumberOfVectoids; i++) {
                listOfVectoids[i] = new Vectoid();
            }
        }
     
        public static void newRound() {
            GamePanel.roundStart = true;
     
            for (int i = 0; i < maxNumberOfVectoids; i++) {
                listOfVectoids[i].dead = false;
                listOfVectoids[i].health = 100;
                currentNumberOfVectoids++;
     
            }
     
        }
     
    }
    Last edited by luckduck312; March 1st, 2022 at 01:01 PM.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Button in borderlayout

    Please edit your post and wrap your code with code tags:

    [code]
    **YOUR CODE GOES HERE**
    [/code]

    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Feb 2022
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Button in borderlayout

    Thanks for the reply, I have done as you have requested.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Button in borderlayout

    There is a missing class definition: GamePanel

    Where is the code using the BorderLayout for building the GUI?

    Have you read the API doc for the BorderLayout class? It has sample code.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Feb 2022
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Button in borderlayout

    I have read it, my problom is that I still dont know what to do when I put classes in my borderlayout.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Button in borderlayout

    what to do when I put classes in my borderlayout.
    First decide where in the different BorderLayout regions of GUI you want the classes to be held.
    Then use the BorderLayout class's corresponding constants to tell the layout manager where to put the GUI component that is being added. See the API doc for several examples.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Feb 2022
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Button in borderlayout

    In region NORTH I want a simple menu that hold a bottun (to start rounds) and a couple of info boxes that display information. I region CENTER I want my actully game to run. I region EAST I also want a menu with a couple of bottuns and some boxes that display infomation. I have triede to put these 3 regions in different casses (right now its only 2 of them), and this is were I got stuck.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Button in borderlayout

    In region NORTH I want a simple menu that hold a bottun (to start rounds) and a couple of info boxes that display information. I region CENTER I want my actully game to run. I region EAST I also want a menu with ...
    I have triede to put these 3 regions in different casses
    Where is the code that is trying to do that? I do not see it.

    Please see the API doc for coding samples.
    Also read the tutorial: https://docs.oracle.com/javase/tutor...ybigindex.html
    Search for BorderLayout
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Feb 2022
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Button in borderlayout

    I have uploadet the wrong code in GameFrame, but it should be fixed now. I have also read the oracle turtorial and have tried and implement it into my code, it still not the way I want it but its progress.

    I was thinking having a class specific for the NORTH and EAST menu, where there is 2 function 1 that make NORTH menu and 1 that make EAST menu, would you reccomend doing it this way or just having all the code in GameFrame or a third option?

     
    //pakke der styrer farver
    import java.awt.Color;
    import javax.swing.*;
    //Pakke der hjælper med at lave vinduet
    import javax.swing.JFrame;
     
    import java.awt.*;
     
    public class GameFrame extends JFrame {
     
        static final int SCREEN_WIDTH = 1000;
        static final int SCREEN_HEIGHT = 1000;
     
        Container pane = this.getContentPane();
     
     
        GameFrame() {
            pane.setLayout(new BorderLayout());
     
            //the bottun
            pane.add(new Menu(), BorderLayout.NORTH);
     
            /*
           I will later add this
     
            pane.add(new Menu(), BorderLayout.EAST);
            */
     
            //the game
            pane.add(new GamePanel(), BorderLayout.CENTER);
     
     
            pack();
     
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
     
            setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
     
     
            this.setBackground(Color.BLACK);
     
     
     
            setVisible(true);
     
            setResizable(false);
     
     
     
        }
     
    }

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Button in borderlayout

    Sorry, I am not very good at designing GUI layouts. Most of my programs have a very simple GUI with a few text fields and a few buttons. The user selects some folders and options and presses a Button to do some job.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Junior Member
    Join Date
    Feb 2022
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Button in borderlayout

    Do you know any other tools that can make menu with text and buttons? Not even sure Borderlayout is able to solve my problem. The best solution migt just be hardcoding every element and making my own buttons I gueese

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Button in borderlayout

    There are several layout managers available in java. Some are quite complicated.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Junior Member
    Join Date
    Feb 2022
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Button in borderlayout

    I tried using af grid inside my NORTH region which seems to work, thanks for the help

Similar Threads

  1. BorderLayout displays only Center area
    By j831526 in forum AWT / Java Swing
    Replies: 4
    Last Post: June 11th, 2014, 04:27 PM
  2. problem with BorderLayout
    By Harry Blargle in forum AWT / Java Swing
    Replies: 5
    Last Post: March 8th, 2014, 08:12 AM
  3. BorderLayout makes everything disappear
    By jason3460 in forum AWT / Java Swing
    Replies: 1
    Last Post: December 6th, 2013, 03:35 AM
  4. [SOLVED] Sinple GUI Program which uses the BorderLayout.
    By javahelp123456 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: September 3rd, 2012, 03:25 PM
  5. BorderLayout and getHeight/getWidth
    By DOLZero in forum Java Theory & Questions
    Replies: 2
    Last Post: May 5th, 2012, 08:59 AM

Tags for this Thread