I am trying to create Pong game and I need to add two figures. I used add() method but it only shows the second figure and clear the first one. My code is below:
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class Demo extends JFrame{
Paddle playerPaddle = new Paddle(26);
Paddle aiPaddle = new Paddle(576);
public Demo() {
super("Ping Pong");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(624, 351);
add(aiPaddle);
add(playerPaddle);
}
public static void main(String[] args){
Demo gui = new Demo();
gui.setBackground(Color.BLACK);
gui.setVisible(true);
}
}
So, it only shows playerPaddle. How can I write it to show both aiPaddle and playerPaddle? Thanks in advance))).
A JFrame by default, uses BorderLayout. When you jframe.add(component) with a border layout, it is equals to jframe.add(component, BorderLayout.CENTER). So you are adding 2 components to CENTER border layout constraints. However, BorderLayout can have only one component in its center. That's why you see this "override".
Change the layout, and you will see both components. Or change the constraints of at least one component:
add(aiPaddle,BorderLayout.PAGE_START);
add(playerPaddle);
I suggest you to take a look at a visual guide to layout managers.
Related
I have a problem when i try to create an extended class from jframe. When i add a panel to the created class with a specific dimension and position it will fill all the window. My code is:
package tuto;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class test extends JFrame{
public test(){
super();
initComponents();
}
private void initComponents() {
setBounds(0, 0, 1000, 618);
panel = new JPanel();
panel.setBounds(10, 10, 100, 100);
panel.setBackground(Color.blue);
add(panel);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new test().setVisible(true);
}
});
}
//Components
JPanel panel;
}
After executing the code all the window become blue. Some help please.
JFrame by default, uses a BorderLayout, which is why you component fills the full size of the window. See How to Use BorderLayout for more details.
In fact, I'd recommend also reading through Laying Out Components Within a Container to get a better understanding of how the layout management system.
You should beware that "manual" placement of components is generally discouraged in most cases, instead, you should make use of one or more layout managers.
As a general recommendations, you should also avoid extending from top level containers like JFrame, as it looks you into a single use case, top level containers tend to be complicated, compound components and you're just not adding any new functionality to the class generally. Better to simply create them when you need them and fill them with the components you need.
If you want to use absolute positioning you should set the layout to null.
setLayout(null)
But it’s recommended you have a look at the different layouts. Everything is better than null layouts.
E.g. https://docs.oracle.com/javase/tutorial/uiswing/layout/border.html
this is a very easy code because I just started learning java.
how do I move the button to specific position/points. Please be brief and make your answer simple and easy to understand because I just started learning java.
this is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class finals extends JFrame implements ActionListener{
JButton login = new JButton("Log-In");
JButton enroll = new JButton("Enroll");
JPanel con = new JPanel();
JFrame frame = new JFrame();
public finals(){
frame.setTitle("Enrollment");
setContentPane(con);
setLayout(new FlowLayout());
login.setLocation(122, 120);
con.add(login);
System.out.println(login.getLocation());
frame.add(con);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,150);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e){
}
public static void main(String Args[]){
new finals();
}
}
make your answer simple and easy to understand
Don't attempt to specify a pixel location of a component! What is so special about (122, 12)? Nothing, its just a random number you picked.
Let the layout manager do its job. For example you can use a FlowLayout and set the alignment to CENTER so the component is centered on the row.
Or if you don't like that you can use a BoxLayout, and add a "horizontal strut" to the panel to help control positioning.
Read the section from the Swing tutorial on Layout Managers for more information and working examples.
I just started learning java.
Don't forget to check out the Table of Contents from the above tutorial link for more basic information about creating GUI's.
You have to put your JPanel layout to "null".
Just add this : con.setLayout(null);
Right now i can only have one of my two components show up on the screen the second one always just overlaps the first so the second is only showing.
How can I get both of them to show up at the same time.
package Game;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Amazing {
private final int width = 300;
private final int height = width / 16 * 9;
private int scale = 3;
private static Graphics g;
private static JFrame frame = new JFrame();
public Amazing(){
Dimension size = new Dimension(width*scale, height*scale);
frame.setPreferredSize(size);
frame.setResizable(false);
frame.setTitle("Amazing!");
Character character = new Character(50,50,scale,width,height);
Map map = new Map(scale, width, height);
frame.add(map);
frame.add(character);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
character.requestFocus();
}
public static void main(String[] args){
Amazing amazing = new Amazing();
}
}
I figured you don't need to see the other two classes(if you want i can also post them) but I think all you need to know about them are that the map class creates and paints with paintComponent(Graphics g) 2 randomly generated rectangles while the Character class creates and uses the paintComponent(Graphics g) method to show and Image on the screen.
Since you didn't specify a layout, you were using BorderLayout which only displays 1 component in each section. Unless you specify a different location as an additional arg when using the default BorderLayout, the add(component) method will "overwrite" whatever was there previously. Therefore, when you add your second component to your frame it overwrites the first.
I noticed that you imported GridLayout, but i don't see it used in your code. If you add a statement in the constructor like:
this.setLayout(new GridLayout(4, 2));
it will change the layout from the default BorderLayout to the GridLayout, and you will have 4 rows of 2 compartments each in which to place components. Calling the add(component) method will add a component in the next available section, starting with row 1 spot 1.
If you only want to add those two items, try putting in the statement
this.setLayout(new GridLayout(1, 2));
before you add your components. This will place them side by side.
When adding components to a panel in Swing you should choose a LayoutManager for the panel (FlowLayout is simple, GridBoxLayout flexible, but there are many more). Depending on the layout chosen you also associate data with the component to tell the LayoutManager where to place the component.
The "main" problem you're having is the fact that by default JFrame uses a BorderLayout. BorderLayout will only only a single component to occupy each of its five available positions. By default, BorderLayout will place components at the CENTER position.
You should explore a different layout manager which meets your requirements.
Take a look at Laying Out Components Within a Container
When I create my GUI I use a cardlayout to hold my different panels as I'm sure many know. This sets my screen to the width and height of my largest panel. This causes problems with the aesthetics of my first to screens, which are much smaller than SudokuPanel and CalkuroPanel.
I have tried setting the preferred size when I change to the larger screens, but to no avail.
Any help with links to good info or anything that will just generally help would be greatly appreciated :).
Please find my main class (where I draw the GUI) below:
import java.awt.*; import javax.swing.*; import java.util.*;
public class puzzleGUI{
private static JPanel screens;
public static String username;
static public void main (String[] args){
JFrame puzzle = new JFrame ("Sudoku/Calkuro Pro");
...
PuzzleStartPanel startPanel = new PuzzleStartPanel();
PuzzleChoosePanel choosePanel = new PuzzleChoosePanel();
PuzzleSudokuPanel sudokuPanel = new PuzzleSudokuPanel();
PuzzleCalkuroPanel calkuroPanel = new PuzzleCalkuroPanel();
screens = new JPanel(new CardLayout());
screens.add(startPanel, "start");
screens.add(choosePanel, "choosePuzzle");
screens.add(sudokuPanel, "sudoku");
screens.add(calkuroPanel, "calkuro");
screens.setPreferredSize (new Dimension(250, 80));
puzzle.setJMenuBar(menuBar);
puzzle.getContentPane().add(screens);
puzzle.pack();
puzzle.setVisible(true);
puzzle.setResizable(false);
puzzle.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
static public void getUsername(String str){
username = str;
}
static public void openWindow(String newFrame){
CardLayout cl = (CardLayout)(screens.getLayout());
cl.show(screens, newFrame);
}
}
Edit
brainblast tried to pack the frame after resetting the preferred size when openWindow is called, and wolah, new frame size :D
static public void openWindow(String newFrame, int a, int b){
CardLayout cl = (CardLayout)(screens.getLayout());
cl.show(screens, newFrame);
screens.setPreferredSize (new Dimension(a, b));
puzzle.pack();
}
can i set the size of individual panels in a cardlayout
Certainly. But the layout will ignore them and make every card the same size. The best you can hope for is to add the smaller panels to another panel (with a layout) that allows the content to shrink.
This answer shows this technique using a single label. Swap the label for the 'small panels' and using the layouts on the right, it will be centered.
I had a similar problem and I resolved it by a little cheat ("dirty code").
I had two panels: SmallOne and HugeOne. I set visibility of HugeOne to false. In this case the SmallOne sets the size of whole CardPanel. You can make a method that is called when user selects HugeOne panel and in this method you put HugeOne visibility on true. And CardPanel will resize.
Works like a charm :)
I have followed thenewbostons java game tutorials on youtube and managed to create a base class which will be in full screen mode using a screenmanager class. Well all works just fine, I can draw images and strings and so on, but how the heck can I add JButtons etc etc.
I have uploaded my code on pastie.org so you can see it :)
Main.java
Screen
BaseFrame [the abstract frame]
Menu Frame [Inheritted from BaseFrame]
consider following code :
import javax.swing.JButton;
import javax.swing.JFrame;
public class NewClass5 extends JFrame
{
JButton b=new JButton("button");
NewClass5(){
this.add(b);
this.setSize(200, 200);
this.setVisible(true);
}
public static void main(String a[]){
new NewClass5();
}
}
Consider adding the button in ahead of time. Don't make it visible. Then when you want to give that option, setVisible(true). Unless you have many buttons that are dynamic and need to change on the fly or something, I think this should work.