How to use CardLayout with multiple JButtons? - java

I need to make a GUI that asks the users for details and then save them in a linked list. I wanted to use the CardLayout to switch from one frame to another, which is something I'm doing for the first time. I have done probably less half of what I need to do and here I am quite lost in this part. The code below compiles and executes but when I click the buttons, the desired change does not happen . What could be wrong?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyDatabaseWindow extends JPanel{
public static final String FRONT_PAGE = "Front Page";
public static final String BROWSE_MEMORIES = "Browse Memories";
public static final String ADD_EDIT = "Add Edit";
public static final String VIEW_MEMORY = "View Memory";
public static void createAndShowGUI() {
final MyDatabaseWindow mdbw = new MyDatabaseWindow();
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(null);
final JButton addButton = new JButton("Add");
final JButton editButton = new JButton("Edit");
final JButton deleteButton = new JButton("Delete");
final JButton browseButton = new JButton("Browse");
final JButton searchButton = new JButton("Search");
addButton.setBounds(100, 400, 100, 100);
editButton.setBounds(200, 400, 100, 100);
deleteButton.setBounds(300, 400, 100, 100);
browseButton.setBounds(400, 400, 100, 100);
searchButton.setBounds(500, 400, 100, 100);
buttonPanel.add(addButton);
buttonPanel.add(editButton);
buttonPanel.add(deleteButton);
buttonPanel.add(browseButton);
buttonPanel.add(searchButton);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mdbw.goToAddPage();
}
});
editButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mdbw.goToBrowse();
}
});
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mdbw.goToBrowse();
}
});
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mdbw.goToBrowse();
}
});
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mdbw.goToSearch();
}
});
JFrame frame = new JFrame("Memory Files");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 540);
frame.setLocation(250, 100);
frame.getContentPane().add(mdbw);
frame.getContentPane().add(buttonPanel);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private CardLayout cardLayout = new CardLayout();
private JPanel cardShowingPanel = new JPanel(cardLayout);
public MyDatabaseWindow() {
Window1 win1 = new Window1();
cardShowingPanel.add(win1, FRONT_PAGE);
Window2 win2 = new Window2();
cardShowingPanel.add(win2, BROWSE_MEMORIES);
Window3 win3 = new Window3();
cardShowingPanel.add(win3, ADD_EDIT);
Window4 win4 = new Window4();
cardShowingPanel.add(win4, VIEW_MEMORY);
setLayout(new BorderLayout());
add(cardShowingPanel, BorderLayout.NORTH);
}
public void goToAddPage() {
cardLayout.first(cardShowingPanel);
}
public void goToBrowse() {
cardLayout.first(cardShowingPanel);
cardLayout.next(cardShowingPanel);
}
public void goToSearch() {
cardLayout.last(cardShowingPanel);
}
public void showCard(String key) {
cardLayout.show(cardShowingPanel, key);
}
}
class Window1 extends JPanel {
public Window1() {
init();
}
private void init() { //dummy details
JLabel title = new JLabel("Memory Files");
title.setBounds(0, 0, 500, 500);
add(title);
}
}
class Window2 extends JPanel {
public Window2() {
init();
}
private void init() { //dummy details
JLabel title = new JLabel("Memory Files");
title.setBounds(0, 0, 500, 500);
add(title);
}
}
class Window3 extends JPanel {
public Window3() {
init();
}
private void init() {//dummy details
JLabel title = new JLabel("Memory Files");
title.setBounds(0, 0, 500, 500);
add(title);
}
}
class Window4 extends JPanel {
public Window4() {
init();
}
private void init() {//dummy details
JLabel title = new JLabel("Memory Files");
title.setBounds(0, 0, 500, 500);
add(title);
}
}

The main problem is the use of null-layouts and these lines of code:
frame.getContentPane().add(mdbw);
frame.getContentPane().add(buttonPanel);
First you add the panel using the CardLayout to BorderLayout.CENTER, then you "overlay" it with your buttonPanel, which is using null-layout.
I would go with a simple FlowLayout (the default layout-manager for a JPanel) for the buttonPanel and add it to the BorderLayout.SOUTH of the contentPane. I would also strongly recommend reading this tutorial.
So remove the following lines of code:
buttonPanel.setLayout(null);
...
addButton.setBounds(100, 400, 100, 100);
editButton.setBounds(200, 400, 100, 100);
deleteButton.setBounds(300, 400, 100, 100);
browseButton.setBounds(400, 400, 100, 100);
searchButton.setBounds(500, 400, 100, 100);
and change frame.getContentPane().add(buttonPanel); to frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);.
Also forget about the null-layout / setBounds() in your Window-classes.
(Note that you still won't see the text change if you press a button because you always add a JLabel with the same text ("Memory Files") to your Windows.)

Related

Position Not Moving Despite of Key Listener

I made the Card Layout Working completely fine but what happened now is I added a keylistener to the object character which is a JLabel so whenever the person presses up the character should move up but it does absolutely nothing!
I also tried replacing it with a button which moves it when clicked and it worked completely fine. Also I tried changing the event meaning I changed that if they press up then the image of the town map would change but still no effect so it seems there is something wrong with my KeyListener
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.*;
import javax.swing.*;
#SuppressWarnings({ "unused", "serial" })
public class FinalBlowzXC extends JFrame implements KeyListener{
public static JPanel game=new JPanel();
public static JPanel mainmenu=new JPanel(null);
public static JPanel loginpanel=new JPanel(null);
public static JPanel tutorial=new JPanel(null);
public static JPanel registration=new JPanel(null);
public static JPanel town_map=new JPanel(null);
public JTextField username= new JTextField("Username");
public JTextField password=new JTextField("Password");
public JLabel bglogin=new JLabel();
public JLabel character=new JLabel();
public JButton log_in=new JButton();
public JButton register=new JButton();
CardLayout page= new CardLayout();
public String level="";
public int charx=350;
public int chary=435;
public static void main(String []args)
{
new FinalBlowzXC().setVisible(true);
}
public FinalBlowzXC()
{
super("Final Blowz Xchanged");
setSize(640,510);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
game.setLayout(page);
game.add(mainmenu, "1");
game.add(loginpanel, "2");
game.add(tutorial, "3");
game.add(registration, "4");
game.add(town_map, "5");
add(game);
opening();
}
public void opening()
{
page.show(game, "1");
JLabel bgmainmenu;
JButton start;
JButton exit;
bgmainmenu = new JLabel();
start = new JButton();
exit = new JButton();
bgmainmenu.setIcon(new ImageIcon(getClass().getResource("/FF-XV.jpg")));
bgmainmenu.setBounds(0,0,640,480);
mainmenu.add(bgmainmenu);
mainmenu.add(start);
start.setBounds(280, 360, 70, 20);
start.setBorder(null);
start.setBorderPainted(false);
start.setContentAreaFilled(false);
start.setOpaque(false);
start.addActionListener(new Start());
exit.setBounds(280, 385, 70, 20);
mainmenu.add(exit);
exit.setBorder(null);
exit.setBorderPainted(false);
exit.setContentAreaFilled(false);
exit.setOpaque(false);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
class Start implements ActionListener{
public void actionPerformed(ActionEvent e) {
login();
}
}
public void login()
{
page.show(game, "2");
bglogin.setIcon(new ImageIcon(getClass().getResource("/FF-XV Login.jpg")));
bglogin.setBounds(0, 0, 640, 480);
username.setBounds(300, 285, 85, 15);
username.setBorder(null);
username.setForeground(Color.WHITE);
username.setOpaque(false);
password.setBounds(300, 310, 85, 20);
password.setBorder(null);
password.setForeground(Color.WHITE);
password.setOpaque(false);
log_in.setBounds(280, 335, 50, 45);
log_in.setBorder(null);
log_in.setBorderPainted(false);
log_in.setContentAreaFilled(false);
log_in.setOpaque(false);
log_in.addActionListener(new Log_in());
register.setBounds(335, 335, 55, 45);
register.setBorder(null);
register.setBorderPainted(false);
register.setContentAreaFilled(false);
register.setOpaque(false);
register.addActionListener(new Register());
loginpanel.add(username);
loginpanel.add(password);
loginpanel.add(bglogin);
loginpanel.add(log_in);
loginpanel.add(register);
}
class Log_in implements ActionListener{
public void actionPerformed(ActionEvent e)
{
Tutorial();
}
}
class Register implements ActionListener{
public void actionPerformed(ActionEvent e)
{
page.show(game, "4");
}
}
public void Tutorial()
{
page.show(game, "3");
JLabel bgtutorial=new JLabel();
JLabel animeforward=new JLabel();
JLabel animeright=new JLabel();
JLabel animeleft=new JLabel();
JButton next=new JButton();
JLabel animebackward=new JLabel();
bgtutorial.setIcon(new ImageIcon(getClass().getResource("/FF-XV Tutorial.jpg")));
bgtutorial.setBounds(0, 0, 640, 480);
animeforward.setIcon(new ImageIcon(getClass().getResource("walkanimofficialfront.gif")));
animeforward.setBounds(115, 230, 30, 30);
animeright.setIcon(new ImageIcon(getClass().getResource("walkanimofficialright.gif")));
animeright.setBounds(190, 315, 30, 30);
animeleft.setIcon(new ImageIcon(getClass().getResource("walkanimofficialleft.gif")));
animeleft.setBounds(45, 315, 30, 30);
animebackward.setIcon(new ImageIcon(getClass().getResource("walkanimofficialback.gif")));
animebackward.setBounds(115, 405, 30, 30);
next.setBounds(530, 430, 100, 30);
next.setBorder(null);
next.setBorderPainted(false);
next.setContentAreaFilled(false);
next.setOpaque(false);
next.addActionListener(new Next());
tutorial.add(next);
tutorial.add(animeright);
tutorial.add(animeleft);
tutorial.add(animebackward);
tutorial.add(animeforward);
tutorial.add(bgtutorial);
}
class Next implements ActionListener{
public void actionPerformed(ActionEvent e)
{
town();
}
}
public void town()
{
page.show(game, "5");
JLabel map=new JLabel();
map.setIcon(new ImageIcon(getClass().getResource("/FF-XV Town.jpg")));
map.setBounds(0, 0, 640, 480);
character.setIcon(new ImageIcon(getClass().getResource("standfront.png")));
character.setBounds(charx, chary, 30, 35);
town_map.add(character);
town_map.add(map);
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_UP)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialfront.gif")));
character.setLocation(character.getX(), character.getY()+5);
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialright.gif")));
character.setLocation(character.getX()+5, character.getY());
}
if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialleft.gif")));
character.setLocation(character.getX()-5, character.getY()+5);
}
if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
character.setIcon(new ImageIcon(getClass().getResource("walkanimofficialback.gif")));
character.setLocation(character.getX(), character.getY()-5);
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
Add following code in your programme.
public static JPanel mainmenu = new JPanel();
public static JPanel loginpanel = new JPanel();
or initialize mainmenu & loginpanel before adding them into the game panel.
when you call game.add(loginPanel, "2") loginPanel is null

Setting Action Listener and changing background

I've created 3 buttons. They are each displayed twice in a JFrame. I'm having trouble changing the background of the frame. I've set ActionListeners but upon clicking, nothing is changing. May I ask for some help.
public class MyButtons extends JPanel {
public static JFrame frame;
private JButton Red = new JButton("Red");
private JButton Green = new JButton("Green");
private JButton Blue = new JButton("Blue");
public void InitializeButton()
{
Blue.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setBackground(Color.BLUE);
}
});
Green.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setBackground(Color.GREEN);
}
});
Red.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setBackground(Color.RED);
}
});
}
public MyButtons() {
InitializeButton();
add(Red);
add(Green);
add(Blue);
}
public static void main(String[] args) {
frame = new JFrame();
JPanel row1 = new MyButtons();
JPanel row2 = new MyButtons();
row1.setPreferredSize(new Dimension(250, 100));
row2.setPreferredSize(new Dimension(250, 100));
frame.setLayout(new GridLayout(3,2));
frame.add(row1);
frame.add(row2);
frame.pack();
frame.setVisible(true);
}
}
This code works, but probably not as you expected:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyButtons extends JPanel {
//public static JFrame frame;
// static is rarely a solution of problems in a GUI. ToDo! Change!
static JPanel ui = new JPanel(new GridLayout(2, 0, 20, 20));
private JButton Red = new JButton("Red");
private JButton Green = new JButton("Green");
private JButton Blue = new JButton("Blue");
public void InitializeButton() {
Blue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.BLUE);
}
});
Green.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.GREEN);
}
});
Red.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ui.setBackground(Color.RED);
}
});
}
public MyButtons() {
InitializeButton();
add(Red);
add(Green);
add(Blue);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 100);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel row1 = new MyButtons();
JPanel row2 = new MyButtons();
//row1.setPreferredSize(new Dimension(250, 100));
//row2.setPreferredSize(new Dimension(250, 100));
//frame.setLayout(new GridLayout(3, 2,10,10));
ui.add(row1);
ui.add(row2);
frame.add(ui);
frame.pack();
frame.setVisible(true);
}
}
N.B. Please learn common Java nomenclature (naming conventions - e.g. EachWordUpperCaseClass, firstWordLowerCaseMethod(), firstWordLowerCaseAttribute unless it is an UPPER_CASE_CONSTANT) and use it consistently.

Navigating through an applet with Card Layout (Need some guidance and code fixing)

First of all I would like to say that in terms of my java knowledge I am a total beginner. So, I am developing an applet which would have different pages using Card Layout. I managed to gather some code from an online sources, however, I am struggling to accomplish a few things. I will split it into questions.
How do I make it so that when the button is pressed, the user would be taken to a specified card rather than a next one?
In the 'Main' class, how do I set visibility to a card that I want rather than the first one on the list?
In pages classes (Menu, FirstPage, etc), how can I only have a single method for button handling rather than having to repeat the same code?
Will my page classes work if I will have paint methods in them?
How do I turn this application into an applet? As at the moment it is a JFrame.
I would really appreciate if someone could help me with this.
Main class
public class Main
{
private Menu menu;
private FirstPage page1;
private SecondPage page2;
private ThirdPage page3;
private FourthPage page4;
private void showGUI()
{
JFrame frame = new JFrame();
JPanel contentPane = new JPanel();
contentPane.setLayout(new CardLayout());
contentPane.setPreferredSize(new Dimension(240,600));
menu = new Menu(contentPane);
page1 = new FirstPage(contentPane);
page2 = new SecondPage(contentPane);
page3 = new ThirdPage(contentPane);
page4 = new FourthPage(contentPane);
contentPane.add(menu, "Menu");
contentPane.add(page1, "First page");
contentPane.add(page2, "Second page");
contentPane.add(page3, "Third page");
contentPane.add(page4, "Fourth page");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Main().showGUI();
}
});
}
}
Menu page class
class Menu extends javax.swing.JPanel
{
private javax.swing.JLabel textLabel;
private JPanel contentPane;
private JButton pageOne;
private JButton pageTwo;
private JButton pageThree;
private JButton pageFour;
public Menu(JPanel cp)
{
this.contentPane = cp;
initComponents();
}
private void initComponents()
{
setBackground(Color.WHITE);
setLayout(null);
textLabel = new JLabel("This is the menu page", JLabel.CENTER);
textLabel.setForeground(Color.BLACK);
pageOne = new JButton("Flowers");
pageTwo = new JButton("Trees");
pageThree = new JButton("Rivers");
pageFour = new JButton("Seas");
pageOne.addActionListener(new ActionListener(){ #Override public void actionPerformed(ActionEvent ae) { pageOneAction(ae); } });
pageTwo.addActionListener(new ActionListener(){ #Override public void actionPerformed(ActionEvent ae) { pageTwoAction(ae); } });
pageThree.addActionListener(new ActionListener(){ #Override public void actionPerformed(ActionEvent ae) { pageThreeAction(ae); } });
pageFour.addActionListener(new ActionListener(){ #Override public void actionPerformed(ActionEvent ae) { pageFourAction(ae); } });
textLabel.setBounds(20, 20, 200, 60);
pageOne.setBounds(20, 100, 200, 60);
pageTwo.setBounds(20, 170, 200, 60);
pageThree.setBounds(20, 240, 200, 60);
pageFour.setBounds(20, 310, 200, 60);
add(pageOne);
add(pageTwo);
add(pageThree);
add(pageFour);
add(textLabel);
}
private void pageOneAction(ActionEvent ae)
{
CardLayout layout = (CardLayout)contentPane.getLayout();
layout.next(contentPane);
}
private void pageTwoAction(ActionEvent ae)
{
CardLayout layout = (CardLayout)contentPane.getLayout();
layout.next(contentPane);
}
private void pageThreeAction(ActionEvent ae)
{
CardLayout layout = (CardLayout)contentPane.getLayout();
layout.next(contentPane);
}
private void pageFourAction(ActionEvent ae)
{
CardLayout layout = (CardLayout)contentPane.getLayout();
layout.next(contentPane);
}
}
First page class
class FirstPage extends javax.swing.JPanel
{
private javax.swing.JLabel textLabel;
private JPanel contentPane;
private JButton menu;
private JButton pageTwo;
private JButton pageThree;
private JButton pageFour;
public FirstPage(JPanel cp)
{
this.contentPane = cp;
this.setSize(500, 500);
initComponents();
}
private void initComponents()
{
setBackground(Color.WHITE);
setLayout(null);
textLabel = new JLabel("This is the flowers page", JLabel.CENTER);
textLabel.setForeground(Color.BLACK);
menu = new JButton("Back to Menu");
pageTwo = new JButton("Trees");
pageThree = new JButton("Rivers");
pageFour = new JButton("Seas");
menu.addActionListener(new ActionListener(){ #Override public void actionPerformed(ActionEvent ae) { menuAction(ae); } });
pageTwo.addActionListener(new ActionListener(){ #Override public void actionPerformed(ActionEvent ae) { pageTwoAction(ae); } });
pageThree.addActionListener(new ActionListener(){ #Override public void actionPerformed(ActionEvent ae) { pageThreeAction(ae); } });
pageFour.addActionListener(new ActionListener(){ #Override public void actionPerformed(ActionEvent ae) { pageFourAction(ae); } });
textLabel.setBounds(20, 20, 200, 60);
menu.setBounds(20, 100, 200, 60);
pageTwo.setBounds(20, 170, 200, 60);
pageThree.setBounds(20, 240, 200, 60);
pageFour.setBounds(20, 310, 200, 60);
add(menu);
add(pageTwo);
add(pageThree);
add(pageFour);
add(textLabel);
}
private void menuAction(ActionEvent ae)
{
CardLayout layout = (CardLayout)contentPane.getLayout();
layout.next(contentPane);
}
private void pageTwoAction(ActionEvent ae)
{
CardLayout layout = (CardLayout)contentPane.getLayout();
layout.next(contentPane);
}
private void pageThreeAction(ActionEvent ae)
{
CardLayout layout = (CardLayout)contentPane.getLayout();
layout.next(contentPane);
}
private void pageFourAction(ActionEvent ae)
{
CardLayout layout = (CardLayout)contentPane.getLayout();
layout.next(contentPane);
}
}
The other pages are the same as the ones above.

Open a JFrame into another JFrame

I am creating a program, and I have my main class that works with all the JButtons, but I can't get my second class that calls the first class launch with the buttons. The JFrame will launch, but the buttons won't.
I am using eclipse just for the information.
Here is the code of my main class:
public class Unescapable extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private static final Font font1 = new Font("FONT", Font.BOLD, 75);
protected JButton b1;
protected JButton b2;
protected JButton b3;
protected JButton b5;
protected JTextField t1;
public Unescapable()
{
t1 = new JTextField("Unescapable");
t1.setText("Unescapable");
t1.setBounds(225, 50, 750, 100);
t1.setForeground(Color.LIGHT_GRAY);
t1.setOpaque(true);
t1.setVisible(true);
t1.setEditable(false);
t1.setBackground(Color.BLACK);
t1.setFont(font1);
b1 = new JButton("Open Window");
b1.setActionCommand("open");
b1.setBackground(Color.GRAY);
b1.setForeground(Color.white);
b1.setOpaque(true);
b1.setBorderPainted(false);
b1.setBounds(280, 200, 390, 40);
b1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b1.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b1.setBackground(Color.GRAY);
}
});
b2 = new JButton("Delete File");
b2.setActionCommand("delete");
b2.setBackground(Color.GRAY);
b2.setForeground(Color.white);
b2.setOpaque(true);
b2.setBorderPainted(false);
b2.setBounds(280, 255, 390, 40);
b2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b2.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b2.setBackground(Color.GRAY);
}
});
b3 = new JButton("Info...");
b3.setActionCommand("info");
b3.setBackground(Color.GRAY);
b3.setForeground(Color.white);
b3.setOpaque(true);
b3.setBorderPainted(false);
b3.setBounds(278, 330, 185, 40);
b3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b3.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b3.setBackground(Color.GRAY);
}
});
b5 = new JButton("Quit Game");
b5.setActionCommand("close");
b5.setBackground(Color.GRAY);
b5.setForeground(Color.white);
b5.setOpaque(true);
b5.setBorderPainted(false);
b5.setBounds(485, 330, 185, 40);
b5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b5.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b5.setBackground(Color.GRAY);
}
});
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b5.addActionListener(this);
b1.setToolTipText("Opens Another JWindow");
b2.setToolTipText("Deletes \"text.txt\"");
b3.setToolTipText("Give's some information.");
add(b1);
add(b2);
add(b3);
add(b5);
add(t1);
System.out.println("Main Window Is Running");
}
public void actionPerformed(ActionEvent e)
{
if ("open".equals(e.getActionCommand()))
{
File f = new File("text.txt");
try
{
PrintWriter out = new PrintWriter(f);
out.println("TheBestMacTutorials");
out.close();
}
catch (Exception e2)
{
}
}
else if ("delete".equals(e.getActionCommand()))
{
File f = new File("text.txt");
f.delete();
}
else if ("info".equals(e.getActionCommand()))
{
InfoBook add = new InfoBook();
add.call();
}
else
{
System.out.println("Window Is Now Closing");
System.exit(0);
}
}
private static void createAndShowGUI()
{
JFrame program = new JFrame("My Program");
program.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Unescapable newContentPane = new Unescapable();
program.setContentPane(newContentPane);
program.setLayout(null);
program.setVisible(true);
program.setLocation(850, 445);
program.setSize(900, 580);
program.setTitle("Unescapable 1.0");
program.setBackground(Color.GREEN);
program.isOpaque();
program.isForegroundSet();
program.getContentPane().setBackground(Color.BLACK);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
The code for the "Info Book":
public class InfoBook extends JFrame
{
private static final long serialVersionUID = 1L;
private static final Font font1 = new Font("FONT", Font.BOLD, 75);
protected JButton b1;
protected JButton b2;
protected JTextField t1;
public InfoBook()
{
b1 = new JButton("Cancel");
b1.setActionCommand("cancel");
b1.setBackground(Color.GRAY);
b1.setForeground(Color.white);
b1.setOpaque(true);
b1.setBorderPainted(false);
b1.setBounds(280, 200, 390, 40);
b1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b1.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b1.setBackground(Color.GRAY);
}
});
b2 = new JButton("More Info");
b2.setBackground(Color.GRAY);
b2.setForeground(Color.WHITE);
b2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
b2.setBackground(Color.BLUE);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
b2.setBackground(Color.GRAY);
}
});
t1 = new JTextField("Info");
t1.setText("Info...");
t1.setBounds(225, 50, 750, 100);
t1.setForeground(Color.LIGHT_GRAY);
t1.setOpaque(true);
t1.setVisible(true);
t1.setEditable(false);
t1.setBackground(Color.BLACK);
t1.setFont(font1);
b1.setToolTipText("Opens Another JWindow");
b2.setToolTipText("Gives More Infomation");
add(b1);
add(b2);
add(t1);
System.out.println("Info is now running");
}
public static void creatAndShowGUI()
{
JFrame frame = new JFrame("Info Panel");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
InfoBook newContentPane = new InfoBook();
frame.setLayout(null);
frame.setVisible(true);
frame.setLocation(850, 445);
frame.setSize(900, 580);
frame.setTitle("Unescapable 1.0");
frame.setBackground(Color.GREEN);
frame.isOpaque();
frame.isForegroundSet();
frame.getContentPane().setBackground(Color.BLACK);
}
public static void call()
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
creatAndShowGUI();
}
});
}
}
I believe thats all the code, and I am not very used to how to format the code in stack overflow, so I might of messed something up. I am probably just getting something messed up, so i am sorry for that but thanks in advance.
The main problem is in your createAndShowGUI in your InfoBook class...
public static void creatAndShowGUI() {
JFrame frame = new JFrame("Info Panel");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
InfoBook newContentPane = new InfoBook();
frame.setLayout(null);
frame.setVisible(true);
frame.setLocation(850, 445);
frame.setSize(900, 580);
frame.setTitle("Unescapable 1.0");
frame.setBackground(Color.GREEN);
frame.isOpaque();
frame.isForegroundSet();
frame.getContentPane().setBackground(Color.BLACK);
}
Essentially, you create an instance of newContentPane, but you never use it.
But, you're about to run into a second problem...
} else if ("info".equals(e.getActionCommand())) {
InfoBook add = new InfoBook();
add.call();
Here you create an instance of InfoBook, but this instance will have no relationship to the one that is created in your creatAndShowGUI and which I assume you want to show on the screen, so getting information from the class will be impossible
I suspect, you actually want to use a JDialog of some kind instead, which will allow you to present a window to the user, BUT which will block the execution of the code until the user closes the window, at which time you could then interrogate the object for it's information.
See How to Make Dialogs for more details
As a general rule of thumb, you don't want to extend from top level containers like JFrame or JDialog, instead, you want to use a JPanel as the base component and add these to what ever container you need.
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
You might also like to have a look at The Use of Multiple JFrames, Good/Bad Practice?

Java hangman. How to create multiple buttons and actionlisteners?

I am trying to create a hangman game with a button for each letter of the alphabet. I have done this the hard way, using absolute positioning and multiple actionlisteners. Is there any way I can do both with a for loop?
Also, how can I implement my hangman using a polymorphic array? The way I have it now, I will use an if statement for each of the limbs. I'd wrather create the man on his own panel, then set the visibility for each limg to true as the use fails at guessing.
Any help is appreciated.
public class HangmanGui extends JFrame{
private JLabel headerLabel;
private JPanel man;
private Graphics gobj;
private JButton aButton ;
private JButton bButton ;
private JButton cButton ;
private JButton dButton ;
private JButton eButton ;
private JButton fButton ;
private JButton gButton ;
private JButton hButton ;
private JButton iButton ;
private JButton jButton ;
private JButton kButton ;
private JButton lButton ;
private JButton mButton ;
private JButton nButton ;
private JButton oButton ;
private JButton pButton ;
private JButton qButton ;
private JButton rButton ;
private JButton sButton ;
private JButton tButton ;
private JButton uButton ;
private JButton vButton ;
private JButton wButton ;
private JButton xButton ;
private JButton yButton ;
private JButton zButton ;
private JButton newWButton ;
private JButton showWButton ;
private JButton quitButton ;
private JButton startButton ;
private JLabel blankWord;
private JLabel titleWord;
private JFrame frame;
private JPanel hangman;
private FlowLayout layout;
private Container container;
/*
public static void main (String[] args){
GUITest gui = new GUITest();
gui.setSize(800,900);
gui.setVisible(true);
}
*/
//
// public GUITest()
// {
// }
public HangmanGui(){
buildGui();
}
public void buildGui(){
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.setBackground(Color.WHITE);
frame.setBounds(100, 100, 450, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
Font lblFont= new Font("Serif", Font.BOLD, 30);
JLabel[] uscore = new JLabel[15];
Man man = new Man();
titleWord = new JLabel("A Game of Hangman.");
titleWord.setBounds(260,10,500,150);
titleWord.setFont(lblFont);
add(titleWord);
// add(blankWord);
//frame.add(man);
this.add(man);
man.setBounds(100,100,400,400);
JPanel panel = new JPanel();
panel.setBounds(6, 232, 400, 400);
frame.getContentPane().add(panel);
layout = new FlowLayout();
container = getContentPane();
setLayout(null);
aButton = new JButton("A");
add(aButton);
aButton.setBounds(30, 520, 50, 29);
aButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
bButton = new JButton("B");
add(bButton);
bButton.setBounds(80, 520, 50, 29);
bButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
cButton = new JButton("C");
add(cButton);
cButton.setBounds(130, 520, 50, 29);
cButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
dButton = new JButton("D");
add(dButton);
dButton.setBounds(180, 520, 50, 29);
dButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
eButton = new JButton("E");
add(eButton);
eButton.setBounds(230, 520, 50, 29);
eButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
fButton = new JButton("F");
add(fButton);
fButton.setBounds(280, 520, 50, 29);
fButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
gButton = new JButton("G");
add(gButton);
gButton.setBounds(330, 520, 50, 29);
gButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
hButton = new JButton("H");
add(hButton);
hButton.setBounds(380, 520, 50, 29);
hButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
iButton = new JButton("I");
add(iButton);
iButton.setBounds(430, 520, 50, 29);
iButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
jButton = new JButton("J");
add(jButton);
jButton.setBounds(480, 520, 50, 29);
jButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
kButton = new JButton("K");
add(kButton);
kButton.setBounds(530, 520, 50, 29);
kButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
lButton = new JButton("L");
add(lButton);
lButton.setBounds(580, 520, 50, 29);
lButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
mButton = new JButton("M");
add(mButton);
mButton.setBounds(630, 520, 50, 29);
mButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
nButton = new JButton("N");
add(nButton);
nButton.setBounds(680, 520, 50, 29);
nButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
oButton = new JButton("O");
add(oButton);
oButton.setBounds(30, 550, 50, 29);
oButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
pButton = new JButton("P");
add(pButton);
pButton.setBounds(80, 550, 50, 29);
pButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
qButton = new JButton("Q");
add(qButton);
qButton.setBounds(130, 550, 50, 29);
qButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
rButton = new JButton("R");
add(rButton);
rButton.setBounds(180, 550, 50, 29);
rButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
sButton = new JButton("S");
add(sButton);
sButton.setBounds(230, 550, 50, 29);
sButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
tButton = new JButton("T");
add(tButton);
tButton.setBounds(280, 550, 50, 29);
tButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
uButton = new JButton("U");
add(uButton);
uButton.setBounds(330, 550, 50, 29);
uButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
vButton = new JButton("V");
add(vButton);
vButton.setBounds(380, 550, 50, 29);
vButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
wButton = new JButton("W");
add(wButton);
wButton.setBounds(430, 550, 50, 29);
wButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
xButton = new JButton("X");
add(xButton);
xButton.setBounds(480, 550, 50, 29);
xButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
yButton = new JButton("Y");
add(yButton);
yButton.setBounds(530, 550, 50, 29);
yButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
zButton = new JButton("Z");
add(zButton);
zButton.setBounds(580, 550, 50, 29);
zButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
startButton = new JButton("Start Game");
add(startButton);
startButton.setBounds(100, 700, 120, 29);
startButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
newWButton = new JButton("New Word");
add(newWButton);
newWButton.setBounds(250, 700, 120, 29);
newWButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
showWButton = new JButton("Show Word");
add(showWButton);
showWButton.setBounds(400, 700, 120, 29);
showWButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
quitButton = new JButton("Quit Game");
add(quitButton);
quitButton.setBounds(550, 700, 120, 29);
quitButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
}
}
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel;
public class Man extends JPanel {
protected void paintComponent(Graphics g ){
super.paintComponent(g);
//gallows
g.fillRect(10, 250, 150, 20);
g.fillRect(40,70,10,200);
g.fillRect(40,70,60,10);
g.setColor(Color.yellow);
g.fillRect(95,70,5,25);
//head
g.setColor(Color.black);
g.drawOval(82,95,30,30);
//body
g.drawLine(97,125,97,150);
//left leg
g.drawLine(97,150,117,183);
//right leg
g.drawLine(97,150,77,183);
// right arm
g.drawLine(97,125,117,135);
//left arm
g.drawLine(97,125,77,135);
}
}
Use a layout manager to manage the sizing of your buttons, don't use setBounds(). You currently create one but don't set it and so its not used.
layout = new FlowLayout();
setLayout(null); // Why set null and not layout
Set the layout correctly and then you could can use a char in your for loop like
for(char c = 'A'; c <= 'Z'; c++)
{
JButton button = new JButton("" + c);
// add action listener also
add(button); // adding will add it using the layout manager
}
You can learn more about layout managers here.
You could try something like this:
// create a JPanel to hold the buttons that uses a GridLayout with 3 rows
JPanel buttonPanel = new JPanel(new GridLayout(3, ));
for (int i = 0; i < 26; ++i)
{
wButton = new JButton('A' + i);
buttonPanel.add(wButton);
// wButton.setBounds(30 + i * 50, 550, 50, 29); // avoid this
wButton.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
}
}
);
}
// here add the buttonPanel to the main GUI
To break this down:
1) We use a for loop to go thru the 26 letters of the alphabet.
2) We create a button with the title being the letter. Because characters are actually just integers, adding 1 to 'A' yields 'B'. So, we can use 'A'+i as a little trick. Also, you could use an array of all the letters instead and do something like letter[i] there.
3) Avoid use of setBounds but rather use the layout managers to more easily and simply place and size the buttons.
Disclaimer: I haven't actually tested this, it's just something to get you on the right track.
Suggestions:
Yes, use an array or a collection such as either a simple array of JButton or a List<JButton> or its concrete implementation, an ArrayList<JButton>
Yes, create your letter JButtons in a for loop as many have suggested.
But don't create your special buttons there, buttons such as your reset button or your exit button.
Create one AbstractAction or ActionListener class for all the letter buttons to share and a unique AbstractAction or ActionListener class for each special JButton
Use layout managers, but not just one -- nest them. For instance, the overall GUI can use a BorderLayout with the drawing held BorderLayout.CENTER and the buttons in the SOUTH or PAGE_END position, the JPanels that hold your buttons could be held in a BoxLayout using JPanel, the letter buttons in a GridLayout using JPanel and the same for the specialty buttons.
Use a separate JPanel for drawing the hangman image. Keep its logic separate from everything else. All it cares about is the number of wrong letters guessed, and then it should draw the appropriate images depending on this value. So I'd give it a public method for incrementing this number as well as a public method for resetting the number and its drawing.
For instance
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class LayoutFoo extends JPanel {
// using a List of JButtons to hold my collection
private List<JButton> letterButtons = new ArrayList<>();
private DrawingPanel drawingPanel = new DrawingPanel();
public LayoutFoo() {
JPanel letterButtonPanel = new JPanel(new GridLayout(3, 0, 3, 3));
letterButtonPanel.setBorder(BorderFactory.createTitledBorder("Letters"));
ButtonListener buttonListener = new ButtonListener();
for (char c = 'A'; c <= 'Z'; c++) {
String text = String.valueOf(c);
JButton button = new JButton(text);
button.addActionListener(buttonListener);
letterButtons.add(button); // add JButton to List<JButton>
letterButtonPanel.add(button); // and add to GridLayout-using JPanel
}
// JPanel to hold non-letter JButtons
JPanel specialBtnsPanel = new JPanel(new GridLayout(1, 0, 3, 3));
specialBtnsPanel.add(new JButton(new ResetAction("Reset", KeyEvent.VK_R)));
specialBtnsPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
// JPanel to hold non-drawing JPanels. It uses BoxLayout
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.PAGE_AXIS));
bottomPanel.add(letterButtonPanel);
bottomPanel.add(specialBtnsPanel);
// set layout and border of main JPanel and add other JPanels to it
setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
setLayout(new BorderLayout(3, 3));
add(drawingPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button pressed: " + e.getActionCommand());
((AbstractButton) e.getSource()).setEnabled(false);
}
}
private class ResetAction extends AbstractAction {
public ResetAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
for (JButton button : letterButtons) {
button.setEnabled(true);
}
}
}
private class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(component);
win.dispose();
}
}
private static void createAndShowGui() {
LayoutFoo mainPanel = new LayoutFoo();
JFrame frame = new JFrame("LayoutFoo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class DrawingPanel extends JPanel {
private static final int PREF_W = 500;
private static final int PREF_H = PREF_W;
private int wrongLetterCount = 0;
public DrawingPanel() {
setBorder(BorderFactory.createTitledBorder("Hang Man"));
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// TODO: draw hangman here based on wrong letter count!
}
public void incrementWrongLetterCount() {
wrongLetterCount++;
repaint();
}
public void reset() {
wrongLetterCount = 0;
repaint();
}
}

Categories

Resources