I know this sounds like an easy question, but I am making a simple text adventure with buttons and such, and I cant figure out how to add my Jpanel into my JFrame. My JPanel has a bunch of buttons and graphics and stuff if that makes a difference. I have provided the code below. frame panel=new frame(); is the other class which extends JPanel. I know its confusing that its called "frame", its because I used to have it extend JFrame. Anyways my code doesnt produce the buttons, graphics etc, from the other class like it should. Thanks,
package sonomaroller;
import javax.swing.*;
import java.awt.*;
import static javax.swing.JFrame.*;
public class SonomaRoller extends JFrame {
public static Dimension size = new Dimension(550,550); //Dimension of Frame
public static String title = "Sonoma Roller v0.00" ;
public SonomaRoller(){
setTitle(title);
setSize(size);
setResizable(false);
setLocationRelativeTo(null); // null centers window on screen
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println("hello?");
//setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
SonomaRoller object1=new SonomaRoller();
frame panel=new frame();
}
}
Try
SonomaRoller object1=new SonomaRoller();
frame panel=new frame();
object1.getContentPane().add(panel);
or just simply
object1.add(panel);
From: JFrame#getContentPane()
and Container#add(Component)
Here's some code that works if it helps:
import java.awt.*;
import javax.swing.*;
public class MyFrame extends JFrame {
public MyFrame() {
add(new MyPanel());
setSize(640, 480);
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
#Override public void run() {
new MyFrame().setVisible(true);
}
});
}
}
class MyPanel extends JPanel {
#Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(20, 20, 80, 80);
}
}
maybe like this...?
package sonomaroller;
import javax.swing.*;
import java.awt.*;
import javax.swing.JFrame.*;
public class SonomaRoller extends JFrame {
public static Dimension size = new Dimension(550,550); //Dimension of Frame
public static String title = "Sonoma Roller v0.00" ;
public SonomaRoller(){
setTitle(title);
setSize(size);
setResizable(false);
setLocationRelativeTo(null); // null centers window on screen
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println("hello?");
//setLayout(null);
setVisible(true);
frame panel=new frame();
setContentPane(panel);
}
public static void main(String[] args) {
SonomaRoller object1=new SonomaRoller();
}
}
This is how I normally do it:
public class SonomaRoller extends JFrame {
public SonomaRoller(){
setLayout(new BorderLayout(0, 0));
JPanel newPanel = new JPanel();
getContentPane().add(newPanel);
}
}
this is the problem :
frame panel=new frame();
put this line instead of above code :
Frame frame = new Frame();
Panel panel = new Panel();
frame.add(panel);
Related
I'm not new to libgdx, but when i ended up with my previous university project, and started new one, Android studio or IDEA cannot resolve setScreen method, other stuff works fine. Any ideas ? Hope for help. (project absolutely clear).
Creating a project in LibGdx gives you your core file which implements the ApplicationListener.
What I gather you are referring to is extending the Game class with with you set Screen classes with.
With the ApplicationListener.
public class HelloWorld implements ApplicationListener {
private SpriteBatch batch;
private BitmapFont font;
#Override
public void create() {
batch = new SpriteBatch();
font = new BitmapFont();
font.setColor(Color.RED);
}
#Override
public void dispose() {
batch.dispose();
font.dispose();
}
#Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.begin();
font.draw(batch, "Hello World", 200, 200);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
What you're after: (taken from https://github.com/libgdx/libgdx/wiki/Extending-the-simple-game)
public class Drop extends Game {
public SpriteBatch batch;
public BitmapFont font;
public void create() {
batch = new SpriteBatch();
//Use LibGDX's default Arial font.
font = new BitmapFont();
this.setScreen(new MainMenuScreen(this));
}
public void render() {
super.render(); //important!
}
public void dispose() {
batch.dispose();
font.dispose();
}
}
Which allows you to change screens whenever you need:
public class MainMenuScreen implements Screen {
final Drop game;
OrthographicCamera camera;
public MainMenuScreen(final Drop game) {
this.game = game;
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
}
//...Rest of class omitted for succinctness.
}
For default, gdx main Class will extends ApplicationAdapter, you need extends Game class for get use of setScreen()
I want to have two stages on the same screen, but the problem is, the input listener of the second stage(static_stage) is not responding but no problem in drawing its actors.The first stage(stage) works and responds fine. Here is the code,and please tell me where am i going wrong?
package com.amal.arrange;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
public class gamescreen implements Screen {
final Mygame game;
OrthographicCamera camera;
Texture background;
Sprite sprite_back;
Stage stage;
Stage static_stage;
Label shuffle;
LabelStyle shuffle_style;
BitmapFont shuffle_font;
public gamescreen(final Mygame Game) {
game = Game;
camera = new OrthographicCamera();
camera.setToOrtho(false, Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
stage=new Stage();
static_stage=new Stage(stage.getViewport(),stage.getSpriteBatch());
static_stage.clear();
stage.clear();
Gdx.input.setInputProcessor(stage);
Gdx.input.setInputProcessor(static_stage);
Tile_manager.load();
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0.85f, 0.85f, 0.85f, 0.85f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
game.batch.draw(sprite_back, 0, 0);
game.batch.end();
stage.draw();
static_stage.draw();
}
#Override
public void resize(int width, int height) {
static_stage.getViewport().update(width, height, true);
stage.getViewport().update(width, height, true);
}
#Override
public void show() {
//System.out.println("in show");
background=new Texture(Gdx.files.internal("background/background.png"));
sprite_back=new Sprite(background);
sprite_back.setBounds(0, 0, background.getWidth(), background.getHeight());
Tile_manager.generate_tile();
Tile_manager.add_listener();
stage=Tile_manager.get_tile_stage();
shuffle_font=new BitmapFont(Gdx.files.internal("fonts/shuffle.fnt"), false);
shuffle_style=new LabelStyle(shuffle_font, null);
shuffle=new Label("SHUFFLE", shuffle_style);
shuffle.setPosition(190, 1330);
shuffle.addListener(new InputListener(){
#Override
public boolean touchDown(InputEvent event, float x, float y,
int pointer, int button) {
System.out.println("in down");
return true;
}
#Override
public void touchUp(InputEvent event, float x, float y,
int pointer, int button) {
System.out.println("in up");
}
});
static_stage.addActor(shuffle);
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
background.dispose();
stage.dispose();
}
}
I am facing the same problem. But to begin, you overright the input listener,
you have to set an inputmultiplexer to manage both the input
InputMultiplexer inputMultiplexer = new InputMultiplexer();
inputMultiplexer.addProcessor(stage);
inputMultiplexer.addProcessor(static_stage);
Gdx.input.setInputProcessor(inputMultiplexer);
But not sure this is enought...
If I have 1 main class and 2 subclasses
subclass 1: public class JPanel1 extends JPanel {....properly initialized}
subclass 2: public class JTextArea1 extends JTextArea {... properly initialized}
Why can I do jframe1.add(new JPanel1()) but not jframe1.add(new JTextArea1())? for a properly initialized JFrame jframe1 = new JFrame();?
My goal is to output data into both the jpanel and the jtextarea
Here on my side, the issue you raising, is working fine. Do let me know, if you think, this is not what you mean :-)
import java.awt.*;
import javax.swing.*;
public class SwingExample
{
private CustomPanel customPanel;
private CustomTextArea customTextArea;
private void displayGUI()
{
JFrame frame = new JFrame("Swing Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(
BorderFactory.createLineBorder(
Color.DARK_GRAY, 5));
customPanel = new CustomPanel();
customTextArea = new CustomTextArea();
contentPane.add(customPanel, BorderLayout.CENTER);
contentPane.add(customTextArea, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
new SwingExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class CustomPanel extends JPanel
{
private static final int GAP = 5;
public CustomPanel()
{
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(
Color.BLUE, GAP, true));
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(300, 300));
}
}
class CustomTextArea extends JTextArea
{
private static final int GAP = 5;
public CustomTextArea()
{
setBorder(BorderFactory.createLineBorder(
Color.RED, GAP, true));
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(100, 30));
}
}
OUTPUT :
Below is SSCCE to describe my problem.
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
public class APanel extends JPanel{
public APanel() {
this.setVisible(true);
this.setBackground(Color.red);
this.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
if(e.getClickCount()==2)
{
}
System.out.println("Child panel clicked!");
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) {}
});
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PPanel extends JPanel{
private APanel panel1;
private APanel panel2;
private APanel panel3;
public PPanel() {
this.setLayout(new GridLayout(0,1));
panel1 = new APanel();
panel2 = new APanel();
panel2.setBackground(Color.yellow);
panel3 = new APanel();
panel3.setBackground(Color.green);
this.add(panel1);
this.add(panel2);
this.add(panel3);
this.setBackground(Color.blue);
this.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
System.out.println("Parent panel clicked!");
}
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) {}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame();
PPanel panel = new PPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(350, 300));
frame.setTitle("Demo");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
How can I do the following:
If e.getClickCount()==1 then the parent MouseListener will active and it will print "parent panel clicked!".
If e.getClickCount()==2 then the children MouseListner will active and print out "child panel clicked!".
Edit1: Closer to the proposed solution.
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.Timer;
public class APanel extends JPanel {
private static final long serialVersionUID = 1L;
private Point pt;
public APanel() {
timer.setRepeats(false);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) {
System.out.println("double from child");
pt = null;
timer.stop();
} else {
pt = e.getPoint();
Component component = (Component)e.getSource();
component.getParent().dispatchEvent(e);
timer.restart();
}
}
});
setBackground(Color.red);
setVisible(true);
}
private Timer timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//System.out.println("single from child");
}
});
}
In case, a mouseEvent needs to pass through multiplevel of containers, this link might be of interest.
If you elect to interpret double clicks, consider using the user's preferred interval, as suggested here.
Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval");
I think (as I know) that not is possible redirect Mouse event from child to its parent, just get parent from Component that is under the MouseCursor, or get parent from Component that's received Events from MouseClick
sure maybe someone can help you with that :-), but here is code which you needed for success with that
parent:
import java.awt.*;
import javax.swing.*;
public class PPanel extends JPanel {
private static final long serialVersionUID = 1L;
private APanel panel1;
private APanel panel2;
private APanel panel3;
public PPanel() {
setLayout(new GridLayout(0, 1));
panel1 = new APanel();
panel2 = new APanel();
panel2.setBackground(Color.yellow);
panel3 = new APanel();
panel3.setBackground(Color.green);
add(panel1);
add(panel2);
add(panel3);
setBackground(Color.blue);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
PPanel panel = new PPanel();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(350, 300));
frame.setTitle("Demo");
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
});
}
}
Child:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.Timer;
public class APanel extends JPanel {
private static final long serialVersionUID = 1L;
private Point pt;
public APanel() {
timer.setRepeats(false);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (timer.isRunning() && !e.isConsumed() && e.getClickCount() > 1) {
System.out.println("double from child");
pt = null;
timer.stop();
} else {
pt = e.getPoint();
timer.restart();
}
}
});
setBackground(Color.red);
setVisible(true);
}
private Timer timer = new Timer(400, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("single from child");
}
});
}
The menu is displayed on game startup and works fine, but once in game you can hit escape to bring up the menu again and this will cause the program to minimize. After I unminimize the game I can hit escape again and the menu screen will appear as intended. The return button also works as intended. What is going on here?
EDIT
Here is my SSCCE:
You will just need to add the imports and unimplemented methods for BullsEyePanel. I hope this helps!
public class Board {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int B_WIDTH = (int) dim.getWidth();
int B_HEIGHT = (int) dim.getHeight();
JFrame f = new JFrame("Children of The Ape");
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
f.setUndecorated(true);
f.pack();
f.setBackground(Color.BLACK);
f.setVisible(true);
f.setResizable(false);
// Get graphics configuration...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
// Change to full screen
gd.setFullScreenWindow(f);
if (gd.isDisplayChangeSupported()) {
gd.setDisplayMode(new DisplayMode(B_WIDTH, B_HEIGHT, 32, DisplayMode.REFRESH_RATE_UNKNOWN));
}
MenuPanel menu = new MenuPanel(f);
f.getContentPane().add(menu);
f.validate();
}
}
class BullsEyePanel extends JPanel implements MouseInputListener, ActionListener {
JFrame frame;
public BullsEyePanel(JFrame f) {
frame = f;
addKeyListener(new TAdapter());
setFocusable(true);
setVisible(true);
repaint();
}
private void openMenu() {
frame.getContentPane().add(new MenuPanel(this));
setVisible(false);
}
private class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent arg0) {
if (arg0.getKeyCode() == 27) {
openMenu();
}
}
}
}
class MenuPanel extends JPanel {
JButton btnExit;
JButton btnNewGame;
JFrame f;
BullsEyePanel panel;
MenuPanel(JFrame frame) { //this menu constructor is only called on program startup
f = frame;
setBackground(Color.black);
setFocusable(true);
btnNewGame = new JButton("New Game");
btnExit = new JButton("Exit");
btnNewGame.addActionListener(new newGameListener());
btnExit.addActionListener(new exitListener());
add(btnNewGame);
add(btnExit);
setVisible(true);
}
MenuPanel(BullsEyePanel bullsEyePanel) { //this menu constructor is called when ESC is typed
f = bullsEyePanel.frame;
setBackground(Color.black);
setFocusable(true);
btnNewGame = new JButton("New Game");
btnExit = new JButton("Exit");
btnNewGame.addActionListener(new newGameListener());
btnExit.addActionListener(new exitListener());
add(btnNewGame);
add(btnExit);
setVisible(true);
}
public class exitListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
}
public class newGameListener implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
f.getContentPane().add(new BullsEyePanel(f), BorderLayout.CENTER);
}
}
}
Instead of variant constructors, let the menu panel undertake its removal and restoration, as suggested below. See also this related example.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Board {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Board().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
JFrame f = new JFrame("Children of The Board");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(Color.BLACK);
MenuPanel menu = new MenuPanel(f);
f.add(menu, BorderLayout.NORTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class MenuPanel extends JPanel {
private JButton btnExit = new JButton("Exit");
private JButton btnNewGame = new JButton("New Game");
private BullsEyePanel gamePanel;
private JFrame parent;
MenuPanel(JFrame parent) {
this.gamePanel = new BullsEyePanel(this);
this.parent = parent;
this.setBackground(Color.black);
this.setFocusable(true);
btnNewGame.addActionListener(new newGameListener());
btnExit.addActionListener(new exitListener());
this.add(btnNewGame);
this.add(btnExit);
this.setVisible(true);
}
public void restore() {
parent.remove(gamePanel);
parent.add(this, BorderLayout.NORTH);
parent.pack();
parent.setLocationRelativeTo(null);
}
private class exitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
}
private class newGameListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
parent.remove(MenuPanel.this);
parent.add(gamePanel, BorderLayout.CENTER);
parent.pack();
parent.setLocationRelativeTo(null);
gamePanel.requestFocus();
}
}
}
class BullsEyePanel extends JPanel {
private MenuPanel menuPanel;
public BullsEyePanel(MenuPanel menu) {
this.menuPanel = menu;
this.setFocusable(true);
this.addKeyListener(new TAdapter());
this.setPreferredSize(new Dimension(320, 240)); // placeholder
this.setVisible(true);
}
private class TAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent code) {
if (code.getKeyCode() == KeyEvent.VK_ESCAPE) {
menuPanel.restore();
}
}
}
}