Switch Between JPanels With Use of JButton? - java

Trying to make flashcard application. The JButton b_switchmode will be used to switch between panels (an edit mode and a test mode, both have panels created for separate use). Not quite sure how to go from the GUI I've created. Ideally I would click the JButton b_switchmode and I would be able to switch from "Edit Mode" to "Test Mode".
I'm aware that a CardLayout may be needed but I'm unable to implement the correct syntax to make the program executable.
So I want to know how to:
insert CardLayout to be able to switch between JPanels
allow JButton b_switchmode to execute the switch between JPanels
public class App2 {
private static JFrame frame;
private static JPanel editpanel;
private static JPanel testpanel;
private static JLabel l_appmode;
private static JLabel l_number;
private static JLabel l_question;
private static JLabel l_answer;
public static JTextField t_questions;
public static JTextField t_answer;
public static JButton b_switchmode;
public static JButton b_previous;
public static JButton b_next;
public static JButton b_add;
public static JButton b_save;
public static JButton b_question;
public static JButton b_answer;
static int width = 600;
static int height = 450;
public static void main(String[] args) {
// TODO Auto-generated method stub
gui();
}
private static void gui(){
frame = new JFrame("Assignment2");
frame.setTitle("Flash Cards");
frame.setSize(width,height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l_appmode = new JLabel("Current Mode: Edit");
l_number = new JLabel ("");
l_question = new JLabel("Question:");
l_answer = new JLabel("Answer:");
t_questions = new JTextField("");
t_answer = new JTextField("");
b_switchmode = new JButton("Switch Mode");
b_previous = new JButton("Previous");
b_next = new JButton("Next");
b_add = new JButton("Add");
b_save = new JButton("Save");
b_question = new JButton("Question");
b_answer = new JButton("Answer");
editpanel = new JPanel();
int rows = 6, columns = 1;
int hgap = 20; int vgap = 20;
editpanel.setLayout(new GridLayout(rows, columns, hgap,
vgap));
editpanel.add(l_appmode);
editpanel.add(l_number);
editpanel.add(l_question);
editpanel.add(t_questions);
editpanel.add(l_answer);
editpanel.add(t_answer);
editpanel.add(b_switchmode);
editpanel.add(b_previous);
editpanel.add(b_next);
editpanel.add(b_add);
editpanel.add(b_save);
//testpanel.add(b_question);
//testpanel.add(t_questions);
//testpanel.add(b_answer);
//testpanel.add(t_answer);
frame.add(editpanel);
//frame.add(testpanel);
frame.setVisible(true);
}

Related

Java Swing Event Handling between classes

I have a main frame class, and 2 panel classes.
One of the panels has input fields
The second panel has buttons
I am trying to figure out how to set up event handling such that when a button in the second panel is clicked, I am able to perform an operation which requires accessing components (text field) from the first panel.
The problem is I am unable to access the components from a different class
Code:
public class MainFrame extends JFrame {
private InputPanel input_panel;
private ButtonPanel button_panel;
public MainFrame() {
setTitle("Shop");
setSize(650,350);
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
input_panel = new InputPanel();
button_panel = new ButtonPanel();
add(input_panel, BorderLayout.CENTER);
add(button_panel, BorderLayout.SOUTH);
setVisible(true);
}
}
public class InputPanel extends JPanel {
private static JLabel item_num;
private static JLabel book_id;
private static JLabel quantity;
private static JLabel item_info;
private static JLabel subtotal;
private static JTextField t_item_num;
private static JTextField t_book_id;
private static JTextField t_quantity;
private static JTextField t_item_info;
private static JTextField t_subtotal;
public InputPanel() {
//Layout Manager
FlowLayout flow_input_layout = new FlowLayout(FlowLayout.TRAILING, 75, 10);
//Panel
setLayout(flow_input_layout);
setBackground(Color.yellow);
//Text Fields and Labels
item_num = new JLabel("Enter number of items in this order:");
add(item_num);
t_item_num = new JTextField(20);
add(t_item_num);
book_id = new JLabel("Enter Book ID for Item # 1:");
add(book_id);
t_book_id = new JTextField(20);
add(t_book_id);
quantity = new JLabel("Enter quantity for Item # 1:");
add(quantity);
t_quantity = new JTextField(20);
add(t_quantity);
item_info = new JLabel("Item # 1 Info:");
add(item_info);
t_item_info = new JTextField(20);
add(t_item_info);
subtotal = new JLabel("Order subtotal for X Items:");
add(subtotal);
t_subtotal = new JTextField(20);
add(t_subtotal);
}
}
public class ButtonPanel extends JPanel implements ActionListener {
private static JButton process_btn;
private static JButton confirm_btn;
private static JButton view_btn;
private static JButton finish_btn;
private static JButton new_btn;
private static JButton exit_btn;
public ButtonPanel() {
//Layout Manager
FlowLayout flow_input_layout = new FlowLayout();
//Button Panel
setLayout(flow_input_layout);
setBackground(Color.blue);
//Buttons
process_btn = new JButton("Process Item #1");
process_btn.addActionListener(this);
add(process_btn);
confirm_btn = new JButton("Confirm Item #1");
confirm_btn.addActionListener(this);
add(confirm_btn);
view_btn = new JButton("View Order");
view_btn.addActionListener(this);
add(view_btn);
finish_btn = new JButton("Finish Order");
finish_btn.addActionListener(this);
add(finish_btn);
new_btn = new JButton("New Order");
new_btn.addActionListener(this);
add(new_btn);
exit_btn = new JButton("Exit");
exit_btn.addActionListener(this);
add(exit_btn);
}
#Override
public void actionPerformed(ActionEvent event) {
;
}
}
Problem is I cannot access components from my other panel class. Not sure what to do
The easiest thing would be to add the InputPanel to the constructor of the ButtonPanel and then store it in a variable.
input_panel = new InputPanel();
button_panel = new ButtonPanel(input_panel);
And in the ButtonPanel:
public class ButtonPanel extends JPanel implements ActionListener {
...
private final InputPanel inputPanel;
public ButtonPanel(final InputPanel inputPanel) {
this.inputPanel = inputPanel;
...
}
#Override
public void actionPerformed(ActionEvent event) {
this.inputPanel.getItemNum().doSomething() // you will need to also create accessor methods in the inputPanel
}
And btw you should be using camelCase in Java.

Java - JPanel and/ or its contents not showing

At the moment I'm trying to implement a GUI. Unfortunately I'm only getting a frame with a menuBar. The Panel and its content I defined do not show up.
I would appreciate any advice about why the panel and its content are not shown and what I did wrong (most likely in the initialiseLeftPanel() method).
What I have tried so far:
changed the position of setVisible(true);
included some revalidate()'s;
public class Codebreakerz {
private static GameRenderer renderer;
public static void main(String[] args) {
renderer = new GameRenderer();
}
public class GameRenderer extends JFrame {
private final String TITLE = "Codebreakerz";
private Image ICON = getToolkit().getImage("res/confused.png");
private final int WIDTH = 900;
private final int HEIGHT = 800;
private final int ROUNDS = 12;
private final Color BACKGROUND = Color.lightGray;
private JPanel left;
private JPanel right;
private JLabel attemptsLabel;
private JLabel correctLabel;
private JLabel rightNumbLabel;
private JLabel[] roundLabels;
public GameRenderer() {
initialiseWindow();
initialiseMenu()
initialiseLabels();
initialiseLeftPanel();
}
private void initialiseWindow() {
setTitle(TITLE);
setIconImage(ICON);
setSize(WIDTH, HEIGHT);
setLocationRelativeTo(null);
setResizable(false);
setLayout(null);
setVisible(true);
}
private void initialiseMenu() {
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("Menu");
JMenuItem newGame = new JMenuItem("Neues Spiel");
JMenuItem close = new JMenuItem("Schließen");
file.add(newGame);
file.add(close);
menuBar.add(file);
setJMenuBar(menuBar);
}
private void initialiseLabels() {
attemptsLabel = new JLabel("0");
correctLabel = new JLabel("0");
rightNumbLabel = new JLabel("0");
roundLabels = new JLabel[ROUNDS];
for(int i=0; i<ROUNDS; i++) {
roundLabels[i] = new JLabel();
}
}
private void initialiseLeftPanel() {
left = new JPanel();
left.setLayout(null); // Tried other stuff aswell
JLabel heading = new JLabel("Codebreakerz");
JLabel tryNr = new JLabel("Anzahl Versuche: ");
JLabel correct = new JLabel("Richtig: ");
JLabel correctNumb = new JLabel("Richtige Nummer an falscher Stelle: ");
left.add(heading);
left.add(tryNr);
left.add(correct);
left.add(correctNumb);
add(left);
}
}
If you supress the line left.setLayout(null); in your method initialiseLeftPanel() and setLayout(null); in your method initialiseWindow() it will work.
You are obliged to have a Layout if you want display your panels. By default it uses a FlowLayout, but here you replaced it by null.

JPanels and GridLayouts

I have been attempting to recreate this in Java: http://imgur.com/pjt7SMZ
This is the code I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Display extends JFrame implements ActionListener {
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 350;
private static final int FRAME_X_ORIGIN = 100;
private static final int FRAME_Y_ORIGIN = 75;
private JButton readFileButton;
private JButton exitButton;
private JButton statsButton;
private JButton clearButton;
private JButton helpButton;
private JLabel headerLabel;
public Display() {
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setTitle("CSCE155A Course Offering Viewer");
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel header = new JPanel(new GridLayout(1, 1, 5, 5));
headerLabel = new JLabel("CSCE155A Course Offering Viewer");
header.add(headerLabel);
}
public static void main(String[] args) {
Display frame = new Display();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
}
}
My problem is with JPanel. As we were instructed, we are suppose to use the BorderLayout with GridLayout inside, but nothing happens whenever I run the code. Is JPanel even the best way to do this? Right now I'm just trying to get the header to work.
According to your design, you should not add JLabel on JPanel. Add headerLabel on top of JFrame and align the text CENTER.
headerLabel = new JLabel("CSCE155A Course Offering Viewer",JLabel.CENTER);
add(headerLabel,BorderLayout.NORTH);// Add it with JFrame.

Java GUI won't display a prompt I want it to

So my program is designed to take in 2 values, make a calculation, and give this calculations value. I want to display it as a prompt in the GUI in the actionPerformed section after the button is clicked. It looks like it should show up but I can't seem to find why it isn't? It's "prompt2" that isn't showing up. Thanks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Windchill extends JFrame implements ActionListener{
private static final int FRAME_WIDTH = 300;
private static final int FRAME_HEIGHT = 200;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 250;
private String degree;
private String wind;
private int degreeInt;
private int windInt;
private double windChillInt;
private JButton windButton;
private JLabel prompt;
private JLabel prompt1;
private JLabel prompt2;
private JTextField inputLine;
private JTextField inputLine1;
public Windchill(){
setTitle("Windchill");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
inputLine = new JTextField();
inputLine.setColumns(3);
inputLine.addActionListener(this);
contentPane.add(inputLine);
prompt = new JLabel();
prompt.setText("Enter the degrees in Farienheight ");
prompt.setSize(150,25);
contentPane.add(prompt);
inputLine1 = new JTextField();
inputLine1.setColumns(3);
inputLine1.addActionListener(this);
contentPane.add(inputLine1);
prompt1 = new JLabel();
prompt1.setText("Enter the wind speed in MPH");
prompt1.setSize(150,25);
contentPane.add(prompt1);
windButton = new JButton("Calculate windchill");
contentPane.add(windButton);
windButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event){
if (event.getSource() instanceof JButton){
JButton clickedButton = (JButton) event.getSource();
if (clickedButton == windButton){
degree = inputLine.getText();
degreeInt = Integer.parseInt(degree);
wind = inputLine1.getText();
windInt = Integer.parseInt(wind);
windChillInt = 0.08 * (degreeInt - 91.4)*(3.71* (Math.sqrt(windInt)) + 5.81 - 0.25 *windInt) + 91.4;
prompt2 = new JLabel();
prompt2.setText("The windchill is " + windChillInt);
prompt2.setSize(150,25);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(prompt2);
}
}
}
public static void main(String[] args) {
Windchill frame;
frame = new Windchill();
frame.setVisible(true);
}
}
prompt2 isn't showing up as Swing containers need to be validated for any newly added components can be visible. Also it's good practice to repaint. You could do:
contentPane.revalidate();
contentPane.repaint();
Side Notes:
It is unnecessary to set the layout again for the your ActionListener
contentPane.add(prompt2) can be simplified to add(prompt2)
Alternatively, you could just add the prompt2 JLabel to the contentPane on startup with empty String content and call setText to update.

Syntax error on token, 'Class', invalid type

The part with asterisks is what it shows error. Can anyone explain to me why this is happening?
I already have a public class in the beginning.
If I take off the bracket "()", the code following that all shows errors.
Thanks!
public class ButtonTester {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new adasdad();
}
//Setting up variables
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 600;
private JButton button = new JButton ("A");
private JButton button2 = new JButton ("B");
**class ExP12_4 () {**
//Creating a frame
//Creating a panel
...
...
//Display frame
...
}
You have to remove the parenthesis and create a constructor for the class:
class ExP12_4 {
private JFrame frame;
private JPanel panel;
private JButton button;
private JButton button2;
public ExP12_4 (){
button = new JButton ("A");
button2 = new JButton ("B");
frame = new JFrame ();
panel = new JPanel ();
panel.add(button);
panel.add(button2);
frame.add(panel);
...
}
}
Take a look at this tutorial for more info about Java Classes
There's no parenthesis allowed in a class definition. These belong in a constructor.
Also you need to put your statements in a code block such as the constructor or init method:
public class ExP12_4 {
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 300;
private JButton button;
private JButton button2;
public ExP12_4() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(button);
panel.add(button2);
frame.add(panel);
// etc.
}
}
It should be ["a"] instead of ("a").

Categories

Resources