Java GUI JPanel Not Working - java

I really can't figure out why this JPanel "p" isn't appearing?
I thought I coded it right for the JPanel p to be in the middle of the Jframe and should make the whole JFrame RED but it doesn't seem to do that and the buttons and JPanel aren't appearing. Sorry. I know I am probably stupid but please help. :?
Here is the code.
package com.gorillalogic.henry;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Notepad {
private JFrame f; // creates all GUI components
private JPanel p;
private JButton b1;
public Notepad() {
gui();
}
public void gui() {
f = new JFrame("Notepad");
p = new JPanel();
b1 = new JButton("Quit");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
f.setSize(600, 400);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
p.setBackground(Color.RED);
p.add(b1);
f.add(p, BorderLayout.CENTER);
}
public static void main(String[] args) {
new Notepad();
}
}
Thanks in advance. :)

p.setOpaque(true);
You need to do that.

Related

How do I get focus for a keypress in a CardLayout?

I had a CardLayout example working correctly with a button, then tried to convert it to work with keypress. I think the problem is that I don't have focus, but I can't set the focus to frame or panel successfully. Thanks!
I tried requestFocusInWindow from the frame and from the first panel shown, and that didn't help. I asked frame.getFocusOwner() and it returned null.
I thought that CardLayout would give the focus to the top element automatically, but while that worked when I had a button, it is not working now.
public class MyCardLayoutExample3 {
public static void main(String[] args){
MyCardLayoutExample3 game = new MyCardLayoutExample3();
game.display();
}
void display() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(300, 200);
CardLayout cardLayout = new CardLayout();
frame.getContentPane().setLayout(cardLayout);
MyGamePanel3 mgp3 = new MyGamePanel3("minigame A", Color.red);
frame.getContentPane().add(mgp3);
frame.getContentPane().add(new MyGamePanel3("minigame B", Color.green));
frame.getContentPane().add(new MyGamePanel3("minigame C", Color.blue));
frame.setVisible(true);
System.out.println("owner: " + frame.getFocusOwner()); //this prints null
}
}
class MyGamePanel3 extends JPanel implements KeyListener{
MyGamePanel3(String text, Color bg){
JLabel textLabel = new JLabel(text);
this.setBackground(bg);
this.add(textLabel);
}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed worked");
}
#Override
public void keyReleased(KeyEvent e) {}
}
Changing to key bindings made the example work easily, thanks Abra. I never got the keyListener to work, despite trying the links above and many other links.
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.WindowConstants;
class MyGamePanel extends JPanel{
MyGamePanel(ActionListener alNext, String text, Color bg){
JButton buttonNext = new JButton("next");
buttonNext.addActionListener(alNext);
JLabel textLabel = new JLabel(text);
this.setBackground(bg);
this.add(textLabel);
this.add(buttonNext);
}
}
public class MyCardLayoutKeyBindingExample {
public static void main(String[] args){
MyCardLayoutKeyBindingExample game = new MyCardLayoutKeyBindingExample();
game.display();
}
void display() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(300, 200);
CardLayout cardLayout = new CardLayout();
//frame.getContentPane().setLayout(cardLayout);
JPanel mainPanel = new JPanel(cardLayout);
frame.add(mainPanel);
ActionListener al1 = e -> cardLayout.next(mainPanel);
mainPanel.add(new MyGamePanel(al1, "minigame A", Color.red));
mainPanel.add(new MyGamePanel(al1, "minigame B", Color.green));
mainPanel.add(new MyGamePanel(al1, "minigame C", Color.blue));
mainPanel.getInputMap().put(KeyStroke.getKeyStroke("SPACE"), "space");
Action kp = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
System.out.println("key pressed");
}
};
mainPanel.getActionMap().put("space", kp);
frame.setVisible(true);
}
}

Consistently make a button visible on JFrame

My program complies and displays a blank frame. I have tried multiple ways, but I am thinking this should work, I don't understand why it doesn't?
The code is simple it just shows a blank box and a button that informs the user the action Listener is working.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Udemy {
public Udemy() {
JFrame f = new JFrame();
f.setTitle("La's Frame");
f.setSize(400,400);
f.setVisible(true);
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
f.getContentPane().add(panel);
JButton b1 = new JButton("Click me");
panel.add(b1);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Action Listener is working");
}
});
}
public static void main(String[] args){
Udemy ud = new Udemy();
}
}
Here, I moved f.setVisible(true); to the bottom and everything works fine
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Udemy {
public Udemy(){
JFrame f = new JFrame();
f.setTitle("La's Frame");
f.setSize(400,400);
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
f.getContentPane().add(panel);
JButton b1 = new JButton("Click me");
panel.add(b1);
f.setVisible(true);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Action Listener is working");
}
});
}
public static void main(String[] args){
Udemy ud = new Udemy();
}
}

How to execute a .java file on clicking a jbutton in jframe?

On clicking the jbutton in a jframe, I want Start.java file to be executed;what to do?
The Start.java is executing well. I want the same execution to be done when clicked on jbutton in jframe, please help me out.
My jframe code has jbutton
private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {
// i want to execute Start.java file on clicking the button
Start s = new Start();
String in = s.getTxt;
System.out.println(in);
repaint();
}
My Start.java file is :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Start extends JPanel{
public String getTxt;
public Start()
{
final JTextField jf = new JTextField(20);
jf.setBounds(30, 30, 250, 30);
final JButton j1 = new JButton("OK");
j1.setBounds(80, 80, 100, 30);
setLayout(null);
add(jf);
add(j1);
j1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getTxt = jf.getText();
System.out.println(getTxt);
}
});
}
public static void main(String[] args) {
JFrame f = new JFrame("Interest");
f.getContentPane().add(new Start());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(310,250));
f.setMaximumSize(new Dimension(310,250));
f.setMinimumSize(new Dimension(310,250));
f.pack();
f.setVisible(true);
}
}
So, based on what you seem to be doing in your code, I would strongly recommend that you have a look at How to Make Dialogs, the main reason for this is, a modal dialog will cause the execution of your program to stop at the point where the dialog is made visible and resume when it's closed, this way, allowing you to inspect the values the user might have changed.
So, when I first tried to get your program to work, this is what happened...
So, after digging into your code, I noticed you'd done setLayout(null);. This is going to keep on coming back to haunt you and I strongly recommend that you don't do this and learn how to use the layout management API.
So, I jumped into you code and add a layout manager...
public class Start extends JPanel {
public String getTxt;
public Start() {
final JTextField jf = new JTextField(20);
final JButton j1 = new JButton("OK");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(jf, gbc);
add(j1, gbc);
j1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getTxt = jf.getText();
System.out.println(getTxt);
}
});
}
public static void main(String[] args) {
JFrame f = new JFrame("Interest");
f.getContentPane().add(new Start());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(310, 250));
f.setMaximumSize(new Dimension(310, 250));
f.setMinimumSize(new Dimension(310, 250));
f.pack();
f.setVisible(true);
}
}
Now I get...
Okay, but now there's two buttons, and unless the user clicks the middle button, the text is never set!
The fact is, for this kind of thing, you don't need the button! You just need a method which can return the current text of the JTextField, for example...
public class Start extends JPanel {
final JTextField jf = new JTextField(20);
public Start() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(jf, gbc);
}
public String getText() {
return jf.getText();
}
public static void main(String[] args) {
JFrame f = new JFrame("Interest");
f.getContentPane().add(new Start());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(310, 250));
f.setMaximumSize(new Dimension(310, 250));
f.setMinimumSize(new Dimension(310, 250));
f.pack();
f.setVisible(true);
}
}
And then I can use...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Surprise");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Start start = new Start();
JOptionPane.showMessageDialog(TestPane.this, start, "Surprise", JOptionPane.PLAIN_MESSAGE);
System.out.println(start.getText());
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
to show it!
I'd strongly recommend that you take the time to have a look at Laying Out Components Within a Container

How do I make java game options?

I m trying to make a main menu with START button, CONTROLS button and HELP button.
I made a backboard for it but I need help with making options.
I tried to make it, but the error says that local variable gameFrame is accessed from within inner class; needs to be declared final
import java.util.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import static java.lang.System.*;
public class GameFrame {
public static void main(String[] args) {
JFrame gameFrame = new JFrame("PoopMan");
gameFrame.setSize(900, 800);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setResizable(false);
gameFrame.setVisible(true);
gameFrame.getContentPane().setBackground(Color.yellow);
JPanel panel = new JPanel();
JButton button1 = new JButton();
gameFrame.add(panel);
panel.add(button1);
gameFrame.setVisible(true);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(gameFrame.getComponent(0), "START");
}
});
}
}
I believe you would like to initialize your Game in a non-static context. Do the following.
public class Main {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GameFrame();
}
});
}
}
And
import java.util.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import static java.lang.System.*;
public class GameFrame extends JFrame {
private void init() {
this.setSize(900, 800);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
this.getContentPane().setBackground(Color.yellow);
JPanel panel = new JPanel();
JButton button1 = new JButton("START");
this.add(panel);
panel.add(button1);
this.setLayout(new FlowLayout());
this.setMinimumSize(new Dimension(300, 300));
this.pack();
this.setVisible(true);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(getComponent(0), "START");
}
});
}
public GameFrame() {
super("PoopMan");
init();
}
}
This way, you start the GameFrame on another thread, and you can continue your work within the GameFrame class.
That is quite simple. Please note that this is a place to inquire about issues regarding your code, and not a place to look for answers.
What you should be researching is known as JMenuBar (refer to This Tutorial for Assitance)
Seeing as you are new, I will assist you this once. Below is the code that will accomplish what you ask. (Tried and Tested)
import java.util.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import static java.lang.System.*;
public class GameFrame
{
static private JMenuBar menuBar;
static private JMenu startMenu, controlsMenu, helpMenu;
static private JMenuItem startBtn;
static private JMenuItem controls;
static private JMenuItem hlpBtn;
public static void main(String[] args)
{
JFrame gameFrame = new JFrame("PoopMan");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.getContentPane().setBackground(Color.yellow);
menuBar = new JMenuBar();
startMenu = new JMenu("File");
controlsMenu = new JMenu("Controls");
helpMenu = new JMenu("Help");
startBtn = new JMenuItem("Start");
controls = new JMenuItem("Controls");
hlpBtn = new JMenuItem("Help");
gameFrame.add(menuBar, BorderLayout.PAGE_START);
menuBar.add(startMenu);
menuBar.add(controlsMenu);
menuBar.add(helpMenu);
startMenu.add(startBtn);
controlsMenu.add(controls);
helpMenu.add(hlpBtn);
gameFrame.pack();
gameFrame.setResizable(false);
gameFrame.setVisible(true);
gameFrame.setSize(900,800);
}
}
I am not certain as to why you are receiving a Final error. It works fine.
From later edits to the question:
JButton button1 = new JButton("Button");
JPanel panel = new JPanel();
panel.setBackground(Color.yellow);
gameFrame.add(panel);
panel.add(button1);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(gameFrame.getComponent(0), "START");
}
});

JPanel transition, what is wrong with my code?

I am new to java, and learning new things everyday.
Today i stumbled upon an error i just can not get fixed.
So i've got a JFrame with a JPanel inside, now I want to remove the Jpanel when i click on my Start game JLabel, and make it transition into my game JPanel ( for now i use a test JPanel)
JFrame class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainMenu extends JFrame {
JPanel panel;
JFrame frame;
JButton playlabel;
public void mainmenu() {
frame = new JFrame();
panel = new JPanel();
playlabel = new JButton ("Nieuw Spel");
//frame
frame.setSize(new Dimension(800, 600));
frame.getContentPane().setBackground(new Color(14,36,69));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(frame.getMinimumSize());
frame.setVisible(true);
//panel
Dimension expectedDimension = new Dimension(690, 540);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setPreferredSize(expectedDimension);
panel.setMaximumSize(expectedDimension);
panel.setMinimumSize(expectedDimension);
panel.setBackground(new Color(14, 36, 69));
panel.add(playlabel);
playlabel.setAlignmentX(JComponent.CENTER_ALIGNMENT);
//playlabel
playlabel.setFont(new Font("Old English Text MT", Font.BOLD, 40));
playlabel.setBounds(250, 350, 50, 20);
playlabel.setForeground(new Color(217,144,39));
playlabel.setBackground(new Color(14,36,69));
playlabel.setBorderPainted(false);
playlabel.setFocusPainted(false);
playlabel.addActionListener(new PlayListener());
}
private class PlayListener extends JFrame implements ActionListener {
public void actionPerformed(ActionEvent e) {
JPanel panelgame = Game.Game();
this.remove(panel);
this.add(panelgame);
this.revalidate();
}
}
}
Game class:
package labyrinthproject.View;
import java.awt.Color;
import javax.swing.JPanel;
public class Game {
public static JPanel Game(){
JPanel panel = new JPanel();
panel.setSize(690, 540);
panel.setBackground(new Color(255,36,69));
return panel;
}
}
if anyone could explain this to me why this doesn't work, it would be greatly appreciated!
Thank you very much!
Sincerely,
A beginner java student.
There are quite some issues in your code
Create the GUI on the event dispatch thread
Don't extend JFrame (you have three (three!) JFrames floating around there!)
Follow the naming conventions
Don't overuse static methods
Only store the instance variables that you really need to represent your class state
Don't use manual setSize or setBounds calls. Use a LayoutManager instead
The call to frame.setVisible(true) should be the last call, after the frame has been completely assembled
Consider a CardLayout for switching between panels ( http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html )
Slightly cleaned up, but the exact structure depends on what you actually want to achieve at the end:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainMenu extends JPanel
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainMenu = new MainMenu();
mainFrame.getContentPane().add(mainMenu);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
}
MainMenu()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
Dimension expectedDimension = new Dimension(690, 540);
setPreferredSize(expectedDimension);
setBackground(new Color(14, 36, 69));
JButton newGameButton = new JButton ("Nieuw Spel");
newGameButton.setAlignmentX(JComponent.CENTER_ALIGNMENT);
newGameButton.setFont(new Font("Old English Text MT", Font.BOLD, 40));
newGameButton.setForeground(new Color(217,144,39));
newGameButton.setBackground(new Color(14,36,69));
newGameButton.setBorderPainted(false);
newGameButton.setFocusPainted(false);
newGameButton.addActionListener(new PlayListener());
add(newGameButton);
}
private class PlayListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
removeAll();
GamePanel gamePanel = new GamePanel();
add(gamePanel);
revalidate();
}
}
}
class GamePanel extends JPanel
{
GamePanel()
{
setBackground(new Color(255,36,69));
}
}
You should use a JButton and not a JLabel. Then:
you add to your JButton : Your_JB.addActionListener(this); (don't forget to implement ActionListener to your class).
Now, we are gonna add the detector:
#Override
public void actionPerformed(ActionEvent e){
Object src = e.getSource();
if(src == Your_JB){
panel.setVisible(false);
}
}
When you click the button, it will make your panel disapear.
Try this:
this.remove(panel);
this.validate();
this.repaint(); //if you use paintComponent
this.add(panelgame);
this.revalidate();
Swing is hard to making nice UI. You just need to use validate() after remove().
I hope it's helpfull.

Categories