Using ActionListener with JMenuBar and CardLayout - java

I'm testing out a basic java swing GUI setup with a navigation bar and a cardlayout. I'm trying to get the items in the JMenuBar to change what card is shown on the page. I've successfully created the navigation bar and the three cards. I've also added an actionlistener to detect when an item in the JMenuBar is pressed and then eventually change the card. Currently, when trying to retrieve the layout in the actionlistener i receive the error, Cannot Invoke "java.swing.JPanel.getLayout()" because "this.cards" is null. Code is pasted below. Thanks
import java.awt.event.*;
import javax.swing.*;
public class testgui extends JFrame implements Runnable, ActionListener {
JPanel cards; //a panel that uses CardLayout
final static String BUTTONPANEL = "Card 1";
final static String TEXTPANEL = "Card 2";
final static String CARD3 = "Card 3";
JMenu cardList;
JMenuItem card1, card2, card3;
public testgui(String title) {
super(title);
}
private JPanel card1(){
JPanel card1 = new JPanel();
card1.add(new JButton("Button 1"));
card1.add(new JButton("Button 2"));
card1.add(new JButton("Button 3"));
return card1;
}
private JPanel card2(){
JPanel card2 = new JPanel();
card2.add(new JTextField("TextField", 20));
return card2;
}
private JPanel card3(){
JPanel card3 = new JPanel();
JLabel label = new JLabel("Card 3");
card3.add(label);
return card3;
}
private JMenuBar navbar(){
JMenuBar navbar = new JMenuBar();
card1 = new JMenuItem("Card 1");
card2 = new JMenuItem("Card 2");
card3 = new JMenuItem("Card 3");
card1.addActionListener(this);
card2.addActionListener(this);
card3.addActionListener(this);
cardList = new JMenu("Cards");
cardList.add(card1);
cardList.add(card2);
cardList.add(card3);
navbar.add(cardList);
return navbar;
}
public void addComponentToPane(Container pane) {
//Cards are created using separate methods
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1(), BUTTONPANEL);
cards.add(card2(), TEXTPANEL);
cards.add(card3(), CARD3);
setVisible(true);
//Everything is added to a pane.
// pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e){
CardLayout layout = (CardLayout) cards.getLayout();
//Why is the above line giving me the error saying that this.cards is null?
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("CardLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the navbar
//Create and set up the content pane.
testgui demo = new testgui("hello");
demo.addComponentToPane(frame.getContentPane());
//Display the window.
frame.setJMenuBar(navbar());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new testgui("test gui"));
}
public void run() {
setSize(700, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createAndShowGUI();
}
}

You're problem is here:
testgui demo = new testgui("hello");
demo.addComponentToPane(frame.getContentPane());
You're creating one too many JFrame/GUI unnecessarily, setting the JPanel on one and displaying the other (the one with the still null JPanel). The solution is to not do this, to change the above lines to:
// testgui demo = new testgui("hello");
this.addComponentToPane(frame.getContentPane());
or more simply:
addComponentToPane(frame.getContentPane());

Related

Java Button Placement using BorderLayout

This code displays nothing, I have exhausted many avenues but it does not display anything on the GUI (I have a main class that calls this as well already). Please help. I am trying to put the two JButtons horizontally at the bottom of the page and the JTextField and JLabel at the center of the screen.
package test;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("");
textfield = new JTextField("enter text here");
JPanel bottom = new JPanel(new BorderLayout());
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel (new BorderLayout());
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom, BorderLayout.PAGE_END);
centre.add(subCentre, BorderLayout.CENTER);
}
}
Your code is a bit over-complicated. You only need two panels, centre, and buttons. There are two reasons your UI is not showing up:
You never added the panels to the frame
You never set visible to true(Achieve this by using setVisible(true)), unless you did this in the class you ran it in.
One simple way to achieve your desired UI is like so(I added a main method to show the window):
import javax.swing.*;
import java.awt.*;
public class test extends JFrame {
public Test() {
super("test");
JPanel buttons = new JPanel();
JPanel centre = new JPanel();
add(buttons, BorderLayout.SOUTH); //these lines add the
add(centre, BorderLayout.CENTER); //panels to the frame
JButton clear = new JButton("Clear"); // No need
JButton copy = new JButton("Copy"); // to declare
JLabel label = new JLabel("Label"); // these
JTextField textfield = new JTextField("enter text here"); // privately
buttons.add(copy);
buttons.add(clear);
centre.add(label);
centre.add(textfield);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
} //end constructor
//added main method to run the UI
public static void main(String[] args) {
new Experiments();
} //end main
} //end class
And it shows the window:
I got closer but its not pretty code, the JFrame is 500x500 so this works based on that... any better suggestions than what I have?
package lab6;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("label");
textfield = new JTextField("enter text here");
JPanel masterPanel = new JPanel(new BorderLayout());
JPanel top = new JPanel();
top.setPreferredSize(new Dimension(100, 200));
JPanel bottom = new JPanel();
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel ();
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom);
centre.add(subCentre);
masterPanel.add(bottom, BorderLayout.PAGE_END);
masterPanel.add(top, BorderLayout.PAGE_START);
masterPanel.add(centre, BorderLayout.CENTER);
add(masterPanel);
}
}

How can I display multiple JPanel's from different classes onto my JFrame?

I will have a menu bar in which I can select multiple choices, in which will display a different JPanel for me onto my JFrame. Whenever I choose another option from my menu bar, a different JPanel will occupy the JFrame's space.
However, with this code, every time I issue the following code frame.getJPanelOne();, it creates a new JFrame, which I don't want. I only want the panel to be displayed on my existing JFrame.
Keep in mind, when my program starts, a JFrame is created from the JFrameTest class and also displays my menu bar at the top so I can select between Panel one and Panel two.
How can I successfully do this with the following code?
public class MenuActionListener implements ActionListener {
private MyFrame frame;
public MenuActionListener (MyFrame frame) {
this.frame = frame;
}
public void displayPanelOne() {
JFrameTest frame = new JFrameTest();
frame.getJPanelOne();
}
public void displayPanelTwo() {
JFrameTest frame = new JFrameTest();
frame.getJPanelTwo();
}
#Override
public void actionPerformed(final ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
//Display panel one when I select the option on the menu bar
case "Panel One":
displayPanelOne();
break;
//Display panel two when I select the option on the menu bar
case "Panel Two":
displayPanelTwo();
break;
default:
}
}
}
Here is my JFrameTest class:
public class JFrameTest extends JFrame {
private JPanel panelMain;
private JPanelOne panel1;
private JPanelTwo panel2;
private JMenuBar menuBar;
public JFrameTest() {
MenuBar menuBarInstance = new MenuBar();
frame = new JFrame();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setPreferredSize(new Dimension(720, 480));
setJMenuBar(menuBarInstance.getMenuBar());
menuBar.getMenu(0).getItem(0).addActionListener(new MenuActionListener(this));
menuBar.getMenu(0).getItem(1).addActionListener(new MenuActionListener(this));
pack();
setLocationRelativeTo(null);
setVisible(true);
panelMain = new JPanel();
panelMain.setBounds(0, 0, 420, 90);
panelMain.setPreferredSize(new Dimension(200, 40));
add(panelMain);
}
public JPanel getJPanelOne() {
panel1 = new JPanelOne();
panelMain.add(panel1);
return panelMain;
}
public JPanel getJPanelTwo() {
panel2 = new JPanelTwo();
panelMain.add(panel2);
return panelMain;
}
}
Here is both my JPanel classes in which will be added whenever I select the appropriate item from the menu bar:
public class JPanelOne extends JPanel
{
public JPanelOne()
{
// setting up black JPanel
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(220, 40));
panel.setBackground(Color.BLACK);
JLabel label = new JLabel("Panel One");
// adding button to the black JPanel
panel.add(label);
// adding blackJPanel
add(panel);
}
}
And a separate class for my other panel.
public class JPanelTwo extends JPanel
{
public JPanelTwo()
{
// setting up black JPanel
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(220, 40));
panel.setBackground(Color.RED);
JLabel label = new JLabel("Panel One");
// adding button to the black JPanel
panel.add(label);
// adding blackJPanel
add(panel);
}
}
Create menu action listener and add it to my GUI:
public class MenuBar {
private JMenuBar menuBar;
private MyFrame frame;
public MenuBar() {
System.out.println("menuBar");
//Creates a menubar for a JFrame
menuBar = new JMenuBar();
//Define addMenu items
JMenuItem addPanelOneItem = new JMenuItem("Panel One");
addPanelOneItem.setActionCommand("Panel One");
//Define addMenu items
JMenuItem addPanelTwoItem = new JMenuItem("Panel Two");
addPanelTwoItem.setActionCommand("Panel Two");
JMenu menu = new JMenu("Test");
menuBar.add(menu);
menu.add(addPanelOneItem);
menu.add(addPanelOneItem);
public JMenuBar getMenuBar()
{
return menuBar;
}
}
My question is, how can I successfully display multiple JPanel's from different classes onto my main JFrame without creating new instances of said JFrame?
Thank you in advance.
Your use case, seems perfect for CardLayout.
In card layout you can add multiple panels in the same place, but then show or hide, one panel at a time.
It's creating a new JFrame each time because you are telling it to (new JFrameTest();). Instead, do something like:-
JFrameTest frame = new JFrameTest();
public void displayPanelOne() {
// todo - remove existing panel if required?
frame.getJPanelOne();
}
your MenuActionListener class should look like this:
public class MenuActionListener implements ActionListener {
private JFrameTest frame;
public MenuActionListener(JFrameTest frame){
this.frame=frame;
}
public void displayPanelOne() {
frame.getJPanelOne();
}
public void displayPanelTwo() {
frame.getJPanelTwo();
}
#Override
public void actionPerformed(final ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
//Display panel one when I select the option on the menu bar
case "Panel One":
displayPanelOne();
break;
//Display panel two when I select the option on the menu bar
case "Panel Two":
displayPanelTwo();
break;
default:
}
}
}
and again we are missing the crucial part of the code, on which you create the MenuActionListener and add it to your GUI. if you post that code, we can solve your question. And also don't make a new question to the exact same problem as before
Copy the following code of your MenuBar
public class MenuBar {
private JMenuBar menuBar;
private MyFrame frame;
public MenuBar() {
System.out.println("menuBar");
//Creates a menubar for a JFrame
menuBar = new JMenuBar();
//Define addMenu items
JMenuItem addPanelOneItem = new JMenuItem("Panel One");
addPanelOneItem.setActionCommand("Panel One");
//Define addMenu items
JMenuItem addPanelTwoItem = new JMenuItem("Panel Two");
addPanelTwoItem.setActionCommand("Panel Two");
JMenu menu = new JMenu("Test");
menuBar.add(menu);
menu.add(addPanelOneItem);
menu.add(addPanelOneItem);
}
public JMenuBar getMenuBar()
{
return menuBar;
}
}
and in your JFrameTest class you then after
setJMenuBar(menuBarInstance.getMenuBar());
add these lines of code:
menuBar.getMenu(0).getItem(0).addActionListener(new MenuActionListener(this));
menuBar.getMenu(0).getItem(1).addActionListener(new MenuActionListener(this));
public JFrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setPreferredSize(new Dimension(720, 480));
menuBar=new MenuBar().getMenuBar();
menuBar.getMenu(0).getItem(0).addActionListener(new MenuActionListener(this));
menuBar.getMenu(0).getItem(1).addActionListener(new MenuActionListener(this));
pack();
setLocationRelativeTo(null);
setVisible(true);
panelMain = new JPanel();
panelMain.setBounds(0, 0, 420, 90);
panelMain.setPreferredSize(new Dimension(200, 40));
add(panelMain);
setJMenuBar(menuBar);
}

Duplication of JButtons in JFrame

I have created a "Main Menu" JFrame with different JButtons for different periods. If I click on one of the buttons a new JFrame opens up but whenever I dispose of it and go back to the main menu and open it back up it it seems as if it more buttons and I don't know why.
Main Menu
public class GUI extends JFrame implements ActionListener {
public static final int WIDTH=1000;
public static final int LENGTH=900;
public static JFrame myFrame = new JFrame("TOK Discussion Participation");
static JPanel myPanel = new JPanel();
public static JComponent buttonPanel;
public static JPanel IPanel = new JPanel();
public static JFrame Period7 = new JFrame("Period 7");
JPanel myPanel1 = new JPanel();
public static Object createPanelPERIOD7;
public JFrame getMyFrame()
{
return myFrame;
}
public void setWindow()
{
//// Creates Icon in frame
JLabel Image = new JLabel();
ImageIcon myIcon = new ImageIcon(new ImageIcon("/users/Antti/Desktop/GUI/TOKParticipation/src/TOK.jpg").getImage().getScaledInstance(200, 200, 1));
Image.setIcon(myIcon);
//set window
Color backgroundColor = new Color(5,149,251);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setBounds(550,200,1000,600);
myFrame.getContentPane().setBackground(Color.LIGHT_GRAY);
myFrame.setLayout(new BorderLayout());
myFrame.add(myPanel1,BorderLayout.NORTH);
myFrame.add(new JLabel(new ImageIcon("/users/Antti/Desktop/GUI/TOKParticipation/src/TOK.jpg")), BorderLayout.CENTER);
//myFrame.setIconImage("/users/Antti/Desktop/GUI/TOKParticipation/src/TOK.jpg");
myFrame.getContentPane().setBackground(backgroundColor);
myFrame.setVisible(true);
//set label
JLabel myLabel = new JLabel("TOK Discussion Participation");
JLabel myLabel1= new JLabel("");
JLabel myLabel2 = new JLabel("");
//set button (PERIOD 7)
JButton Period_7_BUTTON = new JButton("Period 7");
//set Listener (PERIOD 7)
Period_7_BUTTON.addActionListener(new GUI());
//2nd button (PERIOD 5)
JButton Period_5_BUTTON = new JButton("Period 5");
//set Listener PERIOD 5)
Period_5_BUTTON.addActionListener(new GUI());
//2nd button (PERIOD 2)
JButton Period_2_BUTTON = new JButton("Period 2");
//set Listener PERIOD 2)
Period_2_BUTTON.addActionListener(new GUI());
//2nd button (PERIOD 2)
JButton Period_4_BUTTON = new JButton("Period 4");
//set Listener PERIOD 4)
Period_4_BUTTON.addActionListener(new GUI());
//Setting Button FONT/SIZE
Period_2_BUTTON.setFont(new Font("Ubuntu", Font.BOLD,24));
Period_4_BUTTON.setFont(new Font("Ubuntu", Font.BOLD,24));
Period_5_BUTTON.setFont(new Font("Ubuntu", Font.BOLD,24));
Period_7_BUTTON.setFont(new Font("Ubuntu", Font.BOLD,24));
//Bundle button to panel
myPanel1.setLayout(new BoxLayout(myPanel1, BoxLayout.X_AXIS));
myPanel1.add(Period_7_BUTTON);
myPanel1.add(Period_5_BUTTON);
myPanel1.add(Period_2_BUTTON);
myPanel1.add(Period_4_BUTTON);
//add content to window and make it visible
myFrame.add(myPanel1,BorderLayout.NORTH);
myFrame.setVisible(true);
}
public void dispose(){
myFrame.dispose();
}
Other JFrame that duplicates buttons once reopened
//Method to create Period 7 Frame
public static void createFramePERIOD7() {
//Creates Panel + Buttons
JPanel P7_Panel = new JPanel();
JButton Column = new JButton("Add Columns");
JButton Insert = new JButton("Insert Student 7");
JButton Back = new JButton("Home");
//Adding Buttons and Layout to Period 7 Frame
Period7.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Period7.setBounds(550,200,1000,600);
Period7.setLayout(new FlowLayout());
Period7.add(Back);
Period7.add(Column);
Period7.add(Insert);
//Add ActionListener to Buttons
Back.addActionListener(new GUI());
Insert.addActionListener(new GUI());
Column.addActionListener(new GUI());
//Adding Panel to Frame
//Period7.add(P7_Panel);
Period7.setVisible(true);
}
And finally my ending listener code
public void actionPerformed(ActionEvent e)
{
String buttonCommand = e.getActionCommand();
//Main menu Period 7 button
if(buttonCommand.equals("Period 7"))
{
myFrame.dispose();
createFramePERIOD7();
}
if(buttonCommand.equals("Home"))
{
setWindow();
Period7.dispose();
}
Your method adds 3 buttons everytime... You can fix it by changing your
createFramePERIOD7() method
By inserting the line indicated below.
public static void createFramePERIOD7() {
//Creates Panel + Buttons
JPanel P7_Panel = new JPanel();
JButton Column = new JButton("Add Columns");
JButton Insert = new JButton("Insert Student 7");
JButton Back = new JButton("Home");
Period7 = new JFrame(); //<-------------------------- Insert this line
//Adding Buttons and Layout to Period 7 Frame
Period7.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Period7.setBounds(550,200,1000,600);
Period7.setLayout(new FlowLayout());
Period7.add(Back);
Period7.add(Column);
Period7.add(Insert);
//Add ActionListener to Buttons
Back.addActionListener(new GUI());
Insert.addActionListener(new GUI());
Column.addActionListener(new GUI());
//Adding Panel to Frame
//Period7.add(P7_Panel);
Period7.setVisible(true);
}

Gridlayout button click then load under the buttons a form Java

I really didn't now how to form the question i have a gridlayout with 4 buttons. When the user press Add module i want under the buttons a form instead of a new windows if this is possible.
frame = new JFrame("ModuleViewer");
makeMenu(frame);
Container contentPane = frame.getContentPane();
// Specify the layout manager with nice spacing
contentPane.setLayout(new GridLayout(0, 2));
addModule = new JButton("Toevoegen Module");
contentPane.add(addModule);
overview = new JButton("Overzicht Modules");
contentPane.add(overview);
addSchoolweeks = new JButton("Aapassen schoolweken");
contentPane.add(addSchoolweeks);
weekheavy = new JButton("Weekbelasting");
contentPane.add(weekheavy);
frame.pack();
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(d.width/2 - frame.getWidth()/2, d.height/2 - frame.getHeight()/2);
frame.setVisible(true);
I know that i first need to add een action method for the buttons i know how to do that so that isn't important. I only want to know how i could create a layout under the buttons so when a user clicks the layout will be draw.
Each panel can only have one layout, but you can use multiple panels for the desired effect: a top panel using GridLayout to hold your buttons, and a bottom panel using CardLayout to hold multiple other panels, one for each button click. Each of these panels can use whatever layout you want, depending on its contents.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutDemo implements Runnable
{
final static String CARD1 = "Red";
final static String CARD2 = "Green";
final static String CARD3 = "Blue";
JPanel cards;
CardLayout cardLayout;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new CardLayoutDemo());
}
public void run()
{
JButton btnRed = createButton("Red");
JButton btnGreen = createButton("Green");
JButton btnBlue = createButton("Blue");
JPanel buttons = new JPanel(new GridLayout(1,3));
buttons.add(btnRed);
buttons.add(btnGreen);
buttons.add(btnBlue);
JPanel card1 = new JPanel();
card1.setBackground(Color.RED);
JPanel card2 = new JPanel();
card2.setBackground(Color.GREEN);
JPanel card3 = new JPanel();
card3.setBackground(Color.BLUE);
cardLayout = new CardLayout();
cards = new JPanel(cardLayout);
cards.add(card1, CARD1);
cards.add(card2, CARD2);
cards.add(card3, CARD3);
JFrame f = new JFrame("CardLayout Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(buttons, BorderLayout.NORTH);
f.add(cards, BorderLayout.CENTER);
f.setSize(300, 200);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private JButton createButton(final String name)
{
JButton button = new JButton(name);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
cardLayout.show(cards, name);
}
});
return button;
}
}

CardLayout (swing) with action listeners on buttons?

I've been trying to figure out CardLayout with action listeners on button
(so like - starts on a load-up page- and on a button click switches to a different "card"
my code won't even run right now i'm not entirely sure why - most implementations I can find use ItemListeners and Combo Boxes
The basic process I've done is create a master JPanel, but my cards JPanel onto the master JPanel, but my different cards into the cards JPanel, then add the master JPanel to the frame to display...
Also, for one of my cards I only need to display a picture - I previously implemented this by just creating a new pop-up window but It would be nice to be able to switch the frame to show it... I don't know why I can't figure this out
Here's my code:
import java.awt.*;
/**
* Game
* Main class that specifies the frame and widgets of the GUI
*/
public class Game implements Runnable {
public void run(){
final String ON_OPEN = "Welcome!"; //Opening frame
final String GAME = "Play!"; // Game Frame
final String STATS = "Stats"; // Post-Game Stat Frame
final String HELP = "Help"; //tutorial frame
JPanel cards = new JPanel();
JPanel master; // a panel for the card layout
final JFrame frame = new JFrame(ON_OPEN);
frame.setLocation(500,200);
//Create the master layout for the program
master = (JPanel) frame.getContentPane();
master.setLayout(new BorderLayout()); // creating master layout
//Create panel for all the cards in CardLayout
final CardLayout cLay = new CardLayout();
cards.setLayout(cLay);
// all the cards
final JPanel help = new JPanel();
final JPanel stats = new JPanel();
final JPanel game = new JPanel (new BorderLayout());
final JPanel open = new JPanel (new FlowLayout());
// setting up ON_OPEN layout - uses JPanel open
final ImageIcon img = new ImageIcon("Instructions.png", "My Instructions..."); // the image I want shown under HELP card
final JButton info = new JButton("Help");
info.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// cLay.show(help, HELP); // WHAT I NORMALLY SHOULD BE DOING, RATHER JUST MAKE A NEW FRAME FOR THIS THOUGH
// frame.pack();
final JFrame infoFrame = new JFrame("Tutorial");
infoFrame.setLocation(500,50);
JLabel tutorialImg = new JLabel(img);
// int w = img.getIconWidth();
// int h = img.getIconHeight();
//infoFrame.setSize(w, h);
infoFrame.pack();
infoFrame.add(tutorialImg);
infoFrame.setVisible(true);
}
});
open.add(info); // the open-tutorial button
//Add them to the cards JPanel
cards.add(open, ON_OPEN);
cards.add(help, HELP);
cards.add(stats, STATS);
cards.add(game, GAME);
//Add the cards panel to the Master layout panel
master.add(cards);
// This code is all commented out because I'm not sure what I'm doing here...
// frame.add(cards);
// cLay.show(cards, ON_OPEN);
// frame.add(open, BorderLayout.CENTER);
// Main playing area - I want this to be shown in the GAME card...
GridLayout tileGrid = new GridLayout(4,4);
final JPanel grid = new JPanel(tileGrid);
// game.add(grid, BorderLayout.CENTER);
// grid.setLayout(tileGrid);
// frame.add(grid, BorderLayout.CENTER);
// Input - holds typing box
// final JPanel status_panel = new JPanel();
// frame.add(cards, BorderLayout.CENTER);
// frame.add(open, BorderLayout.CENTER);
final JTextField typingArea = new JTextField();
typingArea.setFocusTraversalKeysEnabled(false);
typingArea.setEditable(true);
typingArea.setFocusable(true);
typingArea.requestFocus();
frame.add(typingArea, BorderLayout.SOUTH);
typingArea.addKeyListener(new KeyAdapter() {
public void keyPressed (KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) { // enter key is pressed
String userWord = typingArea.getText().toLowerCase();
typingArea.setText("");
}
}
});
final JLabel status = new JLabel("Running...");
// status_panel.add(status);
// Reset button
final JPanel control_panel = new JPanel();
frame.add(control_panel, BorderLayout.NORTH);
]
// Put the frame on the screen
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Game());
}
}
Problems:
Your code doesn't compile for us since we don't have the JLetterField class.
You're trying to add the JFrame's contentPane back on itself, and causes an exception and doesn't make sense.
Edit 1:
Your latest code shows you putting everything into one very large run() method but in doing so, you loose much and gain nothing.
I suggest getting rid of the Runnable interface, there's no need for it, and creating a true OOP compliant class, one with private fields and public and private methods.
Your actionPerformed method shows no attempt at changing the CardLayout's displayed card.
I suggest that you get rid of the code to show a new window and try to place card swapping code there.
Make your CardLayout and the card-displaying JPanel fields of the class so that other methods can access them and call their methods.
Edit 2:
For example the following code shows the swapping of cards using 3 JButtons. One to get the previous card, one to get the next card, and one to show how to get a specific card (here the 2nd):
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class CardLayoutEg extends JPanel {
private static final String[] CARD_LABELS = { "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine", "ten" };
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private CardLayout cardlayout = new CardLayout();
private JPanel cardHolder = new JPanel(cardlayout);
private Action[] actions = { new ShowPreviousAction(), new ShowNextAction(),
new ShowTwoCardAction() };
public CardLayoutEg() {
for (String cardLabelText : CARD_LABELS) {
JLabel cardLabel = new JLabel(cardLabelText, SwingConstants.CENTER);
cardHolder.add(cardLabel, cardLabelText);
}
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
for (Action action : actions) {
btnPanel.add(new JButton(action));
}
setLayout(new BorderLayout());
add(cardHolder, BorderLayout.CENTER);
add(btnPanel, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private class ShowPreviousAction extends AbstractAction {
public ShowPreviousAction() {
super("Previous");
}
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.previous(cardHolder);
}
}
private class ShowNextAction extends AbstractAction {
public ShowNextAction() {
super("Next");
}
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.next(cardHolder);
}
}
private class ShowTwoCardAction extends AbstractAction {
public ShowTwoCardAction() {
super("Show Two");
}
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(cardHolder, CARD_LABELS[1]);
}
}
private static void createAndShowGui() {
CardLayoutEg mainPanel = new CardLayoutEg();
JFrame frame = new JFrame("CardLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_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();
}
});
}
}

Categories