JFrame: navigate to another frame using JButton - java

I'm trying to navigate with buttons in Java Swing.
I want to go to another existing frame when i click on a button.
I will attach first the Menu Panel:
public class MenuPanel extends JFrame implements ActionListener {
JLabel l1,l2;
JButton btn1,btn2,btn3,btn4;
MenuPanel()
{
setVisible(true);
setSize(600, 300);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Menu Panel For Final Project");
l1 = new JLabel("Menu Panel Bitches: ");
l2 = new JLabel("This Program Made By Ghetto K");
l1.setForeground(Color.RED);
l1.setFont(new Font("Arial", Font.BOLD, 28));
l2.setForeground(Color.RED);
l2.setFont(new Font("Arial", Font.ITALIC,22));
btn1 = new JButton("Add Child");
btn2 = new JButton("Add Worker");
btn3 = new JButton("Add Class");
btn4 = new JButton("Add Task");
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
btn4.addActionListener(this);
l1.setBounds(150, 30, 400, 30);
l2.setBounds(150, 80, 400, 30);
btn1.setBounds(0, 230, 120, 30);
btn2.setBounds(160, 230, 120, 30);
btn3.setBounds(465, 230, 120, 30);
btn4.setBounds(320, 230, 120, 30);
add(l1);
add(l2);
add(btn1);
add(btn2);
add(btn3);
add(btn4);
}
public static void main(String[] args) {
new MenuPanel();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn1)
{
}
else if(e.getSource()==btn2)
{
}
else if(e.getSource()==btn3)
{
}
}
I want to navigate to this panel:
public class AddWorkerPanel extends JFrame implements ActionListener {
static Connection con = DatabaseConnection.getConnection();
JLabel l1, l2, l3;
JTextField tf1, tf2;
JButton btn1, btn2;
AddWorkerPanel()
{
setVisible(true);
setSize(600, 300);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Add Worker form in Java");
l1 = new JLabel("Add Worker Form - Type Details Below:");
l1.setForeground(Color.blue);
l1.setFont(new Font("Serif", Font.BOLD, 20));
l2 = new JLabel("Worker-Name:");
l3 = new JLabel("Worker-Class-Number:");
tf1 = new JTextField();
tf2 = new JTextField();
btn1 = new JButton("Submit");
btn2 = new JButton("Clear");
btn1.addActionListener(this);
btn2.addActionListener(this);
l1.setBounds(100, 30, 400, 30);
l2.setBounds(80, 70, 200, 30);
l3.setBounds(80, 110, 200, 30);
tf1.setBounds(300, 70, 200, 30);
tf2.setBounds(300, 110, 200, 30);
btn1.setBounds(80, 230, 200, 30);
btn2.setBounds(300, 230, 200, 30);
add(l1);
add(l2);
add(tf1);
add(l3);
add(tf2);
add(btn1);
add(btn2);
}
public static void main(String[] args) {
new AddWorkerPanel();
}
}

A JFrame is the actual frame that sits on the screen. So what you want to do is derive your MenuPanel and AddWorkerPanel classes from JPanel, so that they can both sit inside of one frame. Then, in your main frame class, you can have a CardLayout holding both of your panels, and have a button that cycles through the cards on the card layout, using the next() method in the card layout instance that you have stored.

If you just want to close one JFrame and then open the other you should be avble by just simply doing this in the calling method of your button:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new AddWorkerPanel();
super.dispose();
}
}

Related

Error while controling visibility with setVisible method

While controlling the visibility of some components through a button, I am getting stackoverflow error.
I am setting setVisible(true) for some components based on the click of a button with actionperformed() method.
I am getting stackoverflow error on line 25 and 55.
import java.awt.event.*;
public class Expanse extends Frame {
Label l1, l2;
Button b1, b2, b3;
Frame f1;
TextField tf1, tf2;
Expanse() {
l1 = new Label("welcome user");
Font font1 = new Font("SansSerif", Font.BOLD, 25);
Font font2 = new Font("SansSerif", Font.BOLD, 18);
l1.setFont(font1);
addWindowListener(new myWindowAdapter());
l1.setBounds(100, 25, 300, 50);
add(l1);
l2 = new Label("please click any button from below");
l2.setBounds(75, 100, 500, 50);
l2.setFont(font2);
add(l2);
b1 = new Button("add data");
b1.setBounds(70, 175, 100, 50);
add(b1);
b1.addActionListener(new addListener());
b2 = new Button("retrive data");
b2.setBounds(275, 175, 100, 50);
add(b2);
setLayout(null);
setSize(500, 500);
setVisible(true);
tf1 = new TextField("enter amount");
tf2 = new TextField("enter reason");
tf1.setBounds(70, 260, 150, 30);
add(tf1);
tf2.setBounds(70, 320, 150, 30);
add(tf2);
b3 = new Button("write");
b3.setBounds(100, 380, 80, 35);
add(b3);
tf1.setVisible(false);
tf2.setVisible(false);
b3.setVisible(false);
}
public static void main(String a[]) {
Expanse e1 = new Expanse();
}
}
class myWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
class addListener extends Expanse implements ActionListener {
public void actionPerformed(ActionEvent ae) {
tf1.setVisible(true);
tf2.setVisible(true);
b3.setVisible(true);
}
}
Within Expanse constructor you have:
b1.addActionListener(new addListener());
which constructs an addListener object. 1
addListener extends Expanse so you are creating another Expanse object withing the Expanse constructor.
As pointed out by trashgod this is an endless process which causes the stackoverflow.
The cure is simple: there is no reason for addListener to extend Expanse.
class addListener implements ActionListener {...}
I assume the extends Expanse was added to gain access to tf1 and other class variables, but it is not the way to do it.
Alternatively simply have addListener class, an inner class in Expanse.
1Side note: see Java Naming Conventions

Updating Jlabel text from another class

I am trying to update the text of a Jlabel from another class. I tried using the setText method, which results in the program compiling fine, and running, however when I press the button nothing happens.
Here is the code from my Menu.class, where the Jlabel resides.
public class Menu extends JFrame {
private JPanel contentPane;
private JLabel lblOthello;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
Menu frame = new Menu();
frame.setVisible(true);
}
});
}
public Menu() {
//Sets program icon
ImageIcon img = new ImageIcon("icon.png");
//Creates the frame
setForeground(Color.RED);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 384, 475);
contentPane = new JPanel();
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lblOthello = new JLabel("Othello");
lblOthello.setForeground(Color.YELLOW);
lblOthello.setFont(new Font("Franklin Gothic Medium Cond", Font.BOLD, 33));
lblOthello.setHorizontalAlignment(SwingConstants.CENTER);
lblOthello.setBounds(0, 0, 366, 59);
contentPane.add(lblOthello);
JButton btnNewButton = new JButton("New Singleplayer Game");
btnNewButton.setForeground(Color.BLACK);
btnNewButton.setBackground(UIManager.getColor("Button.background"));
btnNewButton.setBounds(10, 72, 344, 45);
btnNewButton.addActionListener(new ButtonListener());
contentPane.add(btnNewButton);
JButton btnNewMultiplayerGame = new JButton("New Dualplayer Game");
btnNewMultiplayerGame.setBounds(10, 130, 344, 45);
btnNewMultiplayerGame.addActionListener(new ButtonListener());
contentPane.add(btnNewMultiplayerGame);
JSeparator separator = new JSeparator();
separator.setBounds(0, 57, 366, 2);
contentPane.add(separator);
JButton btnNewNetworkGame = new JButton("New Network Game");
btnNewNetworkGame.setBounds(10, 188, 344, 45);
btnNewNetworkGame.addActionListener(new ButtonListener());
contentPane.add(btnNewNetworkGame);
JButton btnAbout = new JButton("AI vs AI Game");
btnAbout.setBounds(10, 246, 344, 45);
btnAbout.addActionListener(new ButtonListener());
contentPane.add(btnAbout);
JButton btnNewButton_1 = new JButton("QUIT");
btnNewButton_1.setBounds(10, 446, 344, 25);
btnNewButton_1.addActionListener(new ButtonListener());
contentPane.add(btnNewButton_1);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setIcon(new ImageIcon("C:\\Users\\User\\workspace\\Othello\\src\\Othello.jpg"));
lblNewLabel.setBounds(0, -36, 366, 507);
contentPane.add(lblNewLabel);
JButton button = new JButton("QUIT");
button.setBounds(10, 390, 344, 25);
button.addActionListener(new ButtonListener());
contentPane.add(button);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(0, 375, 366, 2);
contentPane.add(separator_1);
}
public void setText(String text) {
lblOthello.setText(text);
System.out.println("executed");
contentPane.validate();
contentPane.repaint();
}
}
And here is the part of the code that executes the settext method from my buttonlistener class
case PLAYER_VS_AI:
Menu men = new Menu();
men.setText("Now");
men.revalidate();
men.repaint();
break;
Can anyone tell me why this doesn't work?
You are creating a new Menu object whenever the button is pressed instead of modifying the already existing Menu object.

Cannot get JLabel to display JTextField Input

I have my ProfileInput class to store a JTextField input from a Dialog box. Then I transfer that to the setter and getter methods. From there I am calling the setter and getter methods in my AppFrame class.
The the problem that I am having is when I want the input to be displayed as a JLabel on the GUI nothing is showing up. I have no errors that are displayed when I run the code either. Any ideas as to what I have done wrong.
Please note that I am new to Java and am trying to learn. Any ideas/help to improve anything is also great.
ProfileInput Class
package GUI;
//Library imports
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ProfileInput extends Dialog {
//array for the active drop down box
String[] activeLabels = {"Select One", "Not Active", "Slightly Active", "Active", "Very Active"};
public String firstNameString;
//intilizing aspects used in the user profile dialog box
JPanel Panel = new JPanel();
JButton saveButton = new JButton("Save");
JLabel firstName = new JLabel("First Name: ");
JLabel lastName = new JLabel("Last Name: ");
JLabel age = new JLabel("Age: ");
JLabel weight = new JLabel("Weight: ");
JLabel height = new JLabel("Height: ");
JLabel weightGoal = new JLabel("Weight Goal: ");
JLabel activeLevel = new JLabel("Active Level: ");
JLabel completion = new JLabel("Completion By: ");
JTextField firstNameInput = new JTextField();
JTextField lastNameInput = new JTextField();
JTextField ageInput = new JTextField();
JTextField weightInput = new JTextField();
JTextField heightInputFeet = new JTextField();
JTextField heightInputInches = new JTextField();
JTextField weightGoalInput = new JTextField();
JComboBox activeCombo = new JComboBox(activeLabels);
JTextField completionInput = new JTextField();
//setup of the dialog panel
public ProfileInput(Frame parent) {
super(parent,true);
userProfileInput();
setSize(315, 380);
setTitle("Profile Creator");
setLocationRelativeTo(null);
}
public void userProfileInput() {
//sets up the main panel for the dialog box (only panel to add to)
Panel.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
Panel.setLayout(null);
//sets the location of the aspects inside the panel
firstName.setBounds(35, 15, 150, 20);
lastName.setBounds(35, 50, 150, 20);
firstNameInput.setBounds(115, 15, 150, 20);
lastNameInput.setBounds(115, 50, 150, 20);
age.setBounds(35, 85, 120, 20);
ageInput.setBounds(115, 85, 150, 20);
weight.setBounds(35, 115, 150, 20 );
weightInput.setBounds(115, 115, 150, 20);
height.setBounds(35, 150, 150, 20);
heightInputFeet.setBounds(115, 150, 72, 20);
heightInputInches.setBounds(193, 150, 72, 20);
weightGoal.setBounds(35, 185, 150, 20);
weightGoalInput.setBounds(115, 185, 150, 20);
activeLevel.setBounds(35, 220, 150, 20);
activeCombo.setBounds(115,220, 150, 20);
completion.setBounds(35, 255, 150, 20);
completionInput.setBounds(130, 255, 120, 20);
saveButton.setBounds(135, 310, 65, 20);
saveButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//converts the inputs to a string
firstNameString = firstNameInput.getText();
System.out.println(firstNameString);
}
});
//adds the items to the main panel on the dialog box
Panel.add(firstName, null);
Panel.add(lastName, null);
Panel.add(firstNameInput, null);
Panel.add(lastNameInput, null);
Panel.add(age, null);
Panel.add(ageInput, null);
Panel.add(weight, null);
Panel.add(weightInput, null);
Panel.add(height, null);
Panel.add(heightInputFeet, null);
Panel.add(heightInputInches, null);
Panel.add(weightGoal, null);
Panel.add(weightGoalInput, null);
Panel.add(activeLevel, null);
Panel.add(activeCombo, null);
Panel.add(completion, null);
Panel.add(completionInput, null);
Panel.add(saveButton, null);
//adds the panel to the dialog frame
add(Panel);
}//end of userProfileInput method
public String getFirstName() {
return this.firstNameString;
}
public void setFirstName(String firstNameString) {
this.firstNameString = firstNameString;
}
}
AppFrame Class
public class AppFrame extends JFrame {
private static final long serialVersionUID = 1L;
ProfileInput profileInput = new ProfileInput(null);
String firstNameTest = profileInput.getFirstName();
/**
* Starts the frame from AppFrame method below.
*
* #param args
*/
public static void main(String[] args) {
new AppFrame().setVisible(true);
}//end of main Method
/**
*
*
*/
private AppFrame() {
//Initialization of panels and bars used in the main app
JMenuBar menuBar = new JMenuBar();
JPanel contentPane = new JPanel(new BorderLayout());
JPanel rightPanel = new JPanel();
JPanel profileInfo = new JPanel();
//aspects used in the left toolbar panel
JToolBar toolBarPanel = new JToolBar();
JButton bloodPressureTool = new JButton();
JButton heartRateTool = new JButton();
JButton weightTool = new JButton();
JButton bmiTool = new JButton();
JButton medicationTool = new JButton();
JButton appointmentTool = new JButton();
JButton noteTool = new JButton();
JButton profileTool = new JButton();
Border etched = BorderFactory.createEtchedBorder();
Icon bloodPIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/BloodPressure.png");
Icon heartRateIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/HeartRate.png");
Icon weightIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Weight.png");
Icon bmiIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/BMI.png");
Icon medicationIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Medications.png");
Icon appointmentIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/DoctorAppointment.png");
Icon noteIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Notes.png");
Icon profileIcon = new ImageIcon("/Users/BrandonGrow/git/Health-Application/src/Icons/Profile.png");
//aspects of the user profile panel
JLabel firstName = new JLabel("First Name: ");
JLabel lastName = new JLabel("Last Name: ");
JLabel height = new JLabel("Height: ");
JLabel weight = new JLabel("Weight: ");
JLabel age = new JLabel("Age: ");
JLabel weightGoal = new JLabel("Weight Goal: ");
JLabel activeLevel = new JLabel("Active Level: ");
JLabel completion = new JLabel("Completion Date: ");
//Menu Bar Headers
JMenu file = new JMenu("File");
JMenu go = new JMenu("Go");
JMenu help = new JMenu("Help");
//file drop down
JMenuItem newEntry = new JMenuItem("Profile Creator");
JMenuItem exportReport = new JMenuItem("Export Report");
JMenuItem exportNotes = new JMenuItem("Export Notes");
JMenuItem preferences = new JMenuItem("Preferences");
JMenuItem exit = new JMenuItem("Exit");
file.add(newEntry);
file.addSeparator();
file.add(exportReport);
file.addSeparator();
file.add(exportNotes);
file.addSeparator();
file.add(preferences);
file.addSeparator();
file.add(exit);
//action used when the user presses the enter profile input button
newEntry.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
profileInput.setVisible(true);
}
});
//allows for the program to exit when exit is clicked
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
exitDialog();
}
});
//go drop down
JMenuItem bloodPressure = new JMenuItem("Blood Pressure");
JMenuItem heartRate = new JMenuItem("Heart Rate");
JMenuItem medication = new JMenuItem("Medication");
JMenuItem weightDisplay = new JMenuItem("Weight");
JMenuItem bmi = new JMenuItem("BMI");
JMenuItem docAppoints = new JMenuItem("Doctor's Appointments");
JMenuItem notes = new JMenuItem("Notes");
JMenuItem resources = new JMenuItem("Profile");
go.add(bloodPressure);
go.addSeparator();
go.add(heartRate);
go.addSeparator();
go.add(medication);
go.addSeparator();
go.add(weight);
go.addSeparator();
go.add(bmi);
go.addSeparator();
go.add(docAppoints);
go.addSeparator();
go.add(notes);
go.addSeparator();
go.add(resources);
//help drop down
JMenuItem usersGuide = new JMenuItem("Users Guide");
JMenuItem about = new JMenuItem("About Personal Health Application");
help.add(usersGuide);
help.addSeparator();
help.add(about);
//adds Items to Frame
menuBar.add(file);
menuBar.add(go);
menuBar.add(help);
setJMenuBar(menuBar);
//Panel that allows for all GUI to be ad added here
contentPane.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
contentPane.setBackground(Color.WHITE);
contentPane.add(toolBarPanel, BorderLayout.WEST);
contentPane.add(rightPanel);
//stores the buttons for application (left)
toolBarPanel.setOrientation(JToolBar.VERTICAL);
toolBarPanel.setBackground(Color.white);
toolBarPanel.setFloatable(false);;
toolBarPanel.setBorder(etched);
//sets the large panel on the right side of the frame.
rightPanel.setBackground(Color.WHITE);
rightPanel.setBorder(etched);
rightPanel.setLayout(null);
rightPanel.add(profileInfo, null);
//adds the user profile info to the main screen
profileInfo.setBounds(0, 0, 1104, 100);
profileInfo.setBackground(Color.WHITE);
profileInfo.setLayout(null);
profileInfo.setBorder(etched);
firstName.setBounds(80, 10, 80, 20);
firstName.setFont(new java.awt.Font("Dialog", 1, 11));
lastName.setBounds(80, 50, 80, 20);
lastName.setFont(new java.awt.Font("Dialog", 1, 11));
weightDisplay.setBounds(310, 10, 80, 20);
weightDisplay.setFont(new java.awt.Font("Dialog", 1, 11));
height.setBounds(330, 50, 80, 20);
height.setFont(new java.awt.Font("Dialog", 1, 11));
age.setBounds(550, 10, 80, 20);
age.setFont(new java.awt.Font("Dialog", 1, 11));
weightGoal.setBounds(550, 50, 80, 20);
weightGoal.setFont(new java.awt.Font("Dialog", 1, 11));
activeLevel.setBounds(780, 10, 80, 20);
activeLevel.setFont(new java.awt.Font("Dialog", 1, 11));
completion.setBounds(780, 50, 120, 20);
completion.setFont(new java.awt.Font("Dialog", 1, 11));
//test to see if first name displays
JLabel firstNameInputTest = new JLabel(firstNameTest);
firstNameInputTest.setBounds(160, 10, 80, 20);
profileInfo.add(firstName);
profileInfo.add(lastName);
profileInfo.add(weightDisplay);
profileInfo.add(height);
profileInfo.add(age);
profileInfo.add(weightGoal);
profileInfo.add(completion);
profileInfo.add(activeLevel);
//part of test to see of first name displays
profileInfo.add(firstNameInputTest);
//blood pressure button
bloodPressureTool.setMaximumSize(new Dimension(90, 80));
bloodPressureTool.setMinimumSize(new Dimension(30, 30));
bloodPressureTool.setFont(new java.awt.Font("Dialog", 1, 10));
bloodPressureTool.setPreferredSize(new Dimension(90, 50));
bloodPressureTool.setBorderPainted(false);
bloodPressureTool.setContentAreaFilled(false);
bloodPressureTool.setVerticalTextPosition(SwingConstants.BOTTOM);
bloodPressureTool.setHorizontalTextPosition(SwingConstants.CENTER);
bloodPressureTool.setText("Blood Pressure");
bloodPressureTool.setOpaque(false);
bloodPressureTool.setMargin(new Insets(0, 0, 0, 0));
bloodPressureTool.setSelected(true);
bloodPressureTool.setIcon(bloodPIcon);
//heart rate button
heartRateTool.setMaximumSize(new Dimension(90, 80));
heartRateTool.setMinimumSize(new Dimension(30, 30));
heartRateTool.setFont(new java.awt.Font("Dialog", 1, 10));
heartRateTool.setPreferredSize(new Dimension(90, 50));
heartRateTool.setBorderPainted(false);
heartRateTool.setContentAreaFilled(false);
heartRateTool.setVerticalTextPosition(SwingConstants.BOTTOM);
heartRateTool.setHorizontalTextPosition(SwingConstants.CENTER);
heartRateTool.setText("Heart Rate");
heartRateTool.setOpaque(false);
heartRateTool.setMargin(new Insets(0, 0, 0, 0));
heartRateTool.setSelected(true);
heartRateTool.setIcon(heartRateIcon);
//weight button
weightTool.setMaximumSize(new Dimension(90, 80));
weightTool.setMinimumSize(new Dimension(30, 30));
weightTool.setFont(new java.awt.Font("Dialog", 1, 10));
weightTool.setPreferredSize(new Dimension(90, 50));
weightTool.setBorderPainted(false);
weightTool.setContentAreaFilled(false);
weightTool.setVerticalTextPosition(SwingConstants.BOTTOM);
weightTool.setHorizontalTextPosition(SwingConstants.CENTER);
weightTool.setText("Weight");
weightTool.setOpaque(false);
weightTool.setMargin(new Insets(0, 0, 0, 0));
weightTool.setSelected(true);
weightTool.setIcon(weightIcon);
//BMI button
bmiTool.setMaximumSize(new Dimension(90, 80));
bmiTool.setMinimumSize(new Dimension(30, 30));
bmiTool.setFont(new java.awt.Font("Dialog", 1, 10));
bmiTool.setPreferredSize(new Dimension(90, 50));
bmiTool.setBorderPainted(false);
bmiTool.setContentAreaFilled(false);
bmiTool.setVerticalTextPosition(SwingConstants.BOTTOM);
bmiTool.setHorizontalTextPosition(SwingConstants.CENTER);
bmiTool.setText("BMI");
bmiTool.setOpaque(false);
bmiTool.setMargin(new Insets(0, 0, 0, 0));
bmiTool.setSelected(true);
bmiTool.setIcon(bmiIcon);
//medication button
medicationTool.setMaximumSize(new Dimension(90, 80));
medicationTool.setMinimumSize(new Dimension(30, 30));
medicationTool.setFont(new java.awt.Font("Dialog", 1, 10));
medicationTool.setPreferredSize(new Dimension(90, 50));
medicationTool.setBorderPainted(false);
medicationTool.setContentAreaFilled(false);
medicationTool.setVerticalTextPosition(SwingConstants.BOTTOM);
medicationTool.setHorizontalTextPosition(SwingConstants.CENTER);
medicationTool.setText("Medication");
medicationTool.setOpaque(false);
medicationTool.setMargin(new Insets(0, 0, 0, 0));
medicationTool.setSelected(true);
medicationTool.setIcon(medicationIcon);
//appointment button
appointmentTool.setMaximumSize(new Dimension(90, 80));
appointmentTool.setMinimumSize(new Dimension(30, 30));
appointmentTool.setFont(new java.awt.Font("Dialog", 1, 10));
appointmentTool.setPreferredSize(new Dimension(90, 50));
appointmentTool.setBorderPainted(false);
appointmentTool.setContentAreaFilled(false);
appointmentTool.setVerticalTextPosition(SwingConstants.BOTTOM);
appointmentTool.setHorizontalTextPosition(SwingConstants.CENTER);
appointmentTool.setText("Appointments");
appointmentTool.setOpaque(false);
appointmentTool.setMargin(new Insets(0, 0, 0, 0));
appointmentTool.setSelected(true);
appointmentTool.setIcon(appointmentIcon);
//note button
noteTool.setMaximumSize(new Dimension(90, 80));
noteTool.setMinimumSize(new Dimension(30, 30));
noteTool.setFont(new java.awt.Font("Dialog", 1, 10));
noteTool.setPreferredSize(new Dimension(90, 50));
noteTool.setBorderPainted(false);
noteTool.setContentAreaFilled(false);
noteTool.setVerticalTextPosition(SwingConstants.BOTTOM);
noteTool.setHorizontalTextPosition(SwingConstants.CENTER);
noteTool.setText("Notes");
noteTool.setOpaque(false);
noteTool.setMargin(new Insets(0, 0, 0, 0));
noteTool.setSelected(true);
noteTool.setIcon(noteIcon);
//profile button
profileTool.setMaximumSize(new Dimension(90, 80));
profileTool.setMinimumSize(new Dimension(30, 30));
profileTool.setFont(new java.awt.Font("Dialog", 1, 10));
profileTool.setPreferredSize(new Dimension(90, 50));
profileTool.setBorderPainted(false);
profileTool.setContentAreaFilled(false);
profileTool.setVerticalTextPosition(SwingConstants.BOTTOM);
profileTool.setHorizontalTextPosition(SwingConstants.CENTER);
profileTool.setText("Profile");
profileTool.setOpaque(false);
profileTool.setMargin(new Insets(0, 0, 0, 0));
profileTool.setSelected(true);
profileTool.setIcon(profileIcon);
//adding buttons to toolBarPanel
toolBarPanel.add(bloodPressureTool);
toolBarPanel.add(heartRateTool);
toolBarPanel.add(weightTool);
toolBarPanel.add(bmiTool);
toolBarPanel.add(medicationTool);
toolBarPanel.add(appointmentTool);
toolBarPanel.add(noteTool);
toolBarPanel.add(profileTool);
//sets up the actual frame
setSize(1200,800);
setResizable(false);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
add(contentPane);
//allows for the program to shut down by using x and then using the dialog
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
exitDialog();
}
});
}//end of appFrame Method
You've got several problems with the above code, but most important, you're using a modeless dialog when you absolutely need to use a modal one. Since it is modeless, program flow in the calling code does not halt when the dialog is made visible, and so you're calling getFirstName() on the dialog immediately after it is opened, before it has been closed, and well before the user has had a chance to input any information whatsoever. A modal dialog on the other hand will freeze program flow in the calling code, and program flow will not resume until the dialog is no longer visible.
Problems and suggestions:
First and foremost, make sure the dialog window is a modal dialog.
But even before this, don't use Dialog, Panel and other AWT component classes, but rather use Swing classes -- JDialog, JPanel, etc.
You can set the JDialog to be modal with either the proper constructor, passing in ModalityType.APPLICATION_MODAL as a parameter within the appropriate constructor (see the API), or you can set it via a method.
Either way, make sure that it's set before setting the dialog visible.
Do this, and when you query the state of the dialog, you can be assured that the user has at least had a chance to interact with the dialog before you try to extract information from it.
Be sure to query the dialog and assign the results after setting it visible.
Edit, I see now that you're calling String firstNameTest = profileInput.getFirstName(); even before setting the dialog visible, as if the firstNameTest String, which is obviously null at this stage, will magically update once the dialog has been visualized and dealt with, but sorry, there's no magic in Java, and fields will not update by themselves. Again, do not set the firstNameTest field at that point, but rather only after the dialog has been displayed and then dealt with.
Next we'll need to talk about null layouts and setBounds. You really don't want to go this route, trust me.
For example:
public class AppFrame extends JFrame {
private static final long serialVersionUID = 1L;
// !! the JLabel needs to be a field so it can be set in the ActionListener
private JLabel firstNameInputTest = new JLabel("");
private ProfileInput profileInput = null; //!! let this start out as null
// !! worthless code, get rid of
// String firstNameTest = profileInput.getFirstName();
public static void main(String[] args) {
// .... etc
And the ActionListener where we create/display the dialog:
newEntry.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//!! create JDialog in a lazy fashion
if (profileInput == null) {
// create dialog, passing in the JFrame
profileInput = new ProfileInput(AppFrame.this);
}
profileInput.setVisible(true); // display the *modal* dialog
// program flow is frozen here until JDialog is no longer visible
// query dialog for its contents
String firstNameTxt = profileInput.getFirstName();
// and use in GUI
firstNameInputTest.setText(firstNameTxt);
}
});
We don't want to declare the JLabel within a method or constructor since in doing so, it will not be visible throughout the class. So...
private AppFrame() { // ??? private ???
// .....
// test to see if first name displays
// !! JLabel firstNameInputTest = new JLabel(firstNameTest); // No!!!
Finally, a very simple example JDialog to demonstrate what I'm discussing:
#SuppressWarnings("serial")
public class ProfileInput extends JDialog {
private JTextField firstNameField = new JTextField(10);
public ProfileInput(JFrame frame) {
// make it modal!
super(frame, "Profile Input", ModalityType.APPLICATION_MODAL);
JPanel panel = new JPanel();
panel.add(new JLabel("Enter First Name:"));
panel.add(firstNameField);
panel.add(new JButton(new SubmitAction("Submit", KeyEvent.VK_S)));
add(panel);
pack();
setLocationRelativeTo(frame);
}
public String getFirstName() {
return firstNameField.getText();
}
private class SubmitAction extends AbstractAction {
public SubmitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
ProfileInput.this.dispose();
}
}
}

Blank Frame for no apperent reason [duplicate]

This question already has answers here:
Java null layout results in a blank screen
(2 answers)
Closed 8 years ago.
Program is Compiling and running but it is not displaying anything on the frame just a blank screen.
i am making main menu for my game using cardLayout, i have made different classes for every panel and then added them in cardlayout in Frame
Kindly some one please pinpoint the mistake i am doing i cant find it..
thankyou
enter code here
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class MainMenu extends JFrame implements ActionListener{
static CardLayout cl2;
static JPanel cardPanel;
Name p1;
MainM p2;
Robot p3;
High p4;
Inst p5;
gamepanel gp;
public static int height;
public static int width;
public static void main(String args[]){
MainMenu cl = new MainMenu();
cl.What();
}
public void What() {
// get the screen size as a java dimension
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(new BorderLayout());
setTitle("EROBOT");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// get height, and width
height = screenSize.height ;
width = screenSize.width ;
// set the jframe height and width
setSize(new Dimension(width, height));
cardPanel = new JPanel();
p1= new Name();
p2= new MainM();
p3= new Robot();
p4= new High();
p5= new Inst();
gp= new gamepanel();
cl2 = new CardLayout();
cardPanel.setLayout(cl2);
cardPanel.add(p1, "name");
cardPanel.add(p2, "menu");
cardPanel.add(p3, "robo");
cardPanel.add(p4, "inst");
cardPanel.add(p5, "high");
cardPanel.add(gp, "start");
getContentPane().add(cardPanel);
//name
Name.done.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "menu" );
}
});
// Main
MainM.newg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "start" );
}
});
MainM.high.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "high" );
}
});
MainM.robo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "robo" );
}
});
MainM.inst.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "inst" );
}
});
/////////////////////
//Robot
Robot.go.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "start" );
}
});
Robot.back1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "menu" );
}
});
//high score
High.back2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "menu" );
}
});
//how to play
Inst.back.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl2.show(cardPanel, "menu" );
}
});
}
public void actionPerformed(ActionEvent e){}
}
class Name extends JPanel{
JLabel enter;
static JButton done;
JTextField name;
JPanel side;
JPanel up;
JLabel title;
Name(){
Color h3= new Color(255,229,204);
side= new JPanel();
up= new JPanel();
setLayout(null);
MainMenu mm= new MainMenu();
setBackground(h3);
title = new JLabel("E-ROBOT");
title.setFont(new Font("Ravie", Font.PLAIN, 40)); //setting the style and the font of JLabel
title.setBounds(520, 100, 300, 50);
enter= new JLabel("ENTER YOUR NAME HERE");
enter.setFont(new Font("Ravie", Font.PLAIN, 20));
enter.setForeground(Color.orange);
enter.setBounds(370, 200, 350, 50);
name = new JTextField();
name.setBounds(390, 250, 150, 25);
done= new JButton("DONE");
done.setFont(new Font("Ravie", Font.PLAIN, 20));
done.setForeground(Color.orange);
done.setBackground(Color.YELLOW);
done.setOpaque(false);
done.setBorder(null);
done.setBounds(400, 280, 150, 30);
side.setBounds(0,40,mm.width,60);
up.setBounds(40,0,40,mm.height);
side.setBackground(Color.ORANGE);
up.setBackground(Color.ORANGE);
side.add(title);
add(enter);
add(name);
add(done);
add(side);
add(up);
}
}
class MainM extends JPanel{
JPanel l1;
JPanel l2;
JPanel l3;
JPanel l4;
JPanel contain;
JPanel side1;
JPanel up1;
static JButton newg;
static JButton high;
static JButton robo;
static JButton inst;
JLabel title;
MainM(){
MainMenu mm= new MainMenu();
Color h3= new Color(255,229,204);
setBackground(h3);
l1= new JPanel();
l2= new JPanel();
l3= new JPanel();
l4= new JPanel();
contain= new JPanel();
side1= new JPanel();
up1= new JPanel();
title = new JLabel("E-ROBOT");
title.setFont(new Font("Ravie", Font.PLAIN, 40));
title.setForeground(Color.WHITE);
title.setBounds(520, 100, 300, 50);
//custom colors
Color b1= new Color(99,230,199);
Color h= new Color(132,234,23);
Color h1= new Color(45,99,120);
Color h2= new Color(0,0,101);
Color h4= new Color(154,0,0);
l1.setBounds(480,200,10,525);
l1.setBackground(h4);
l2.setBounds(465,210,565,10);
l2.setBackground(h4);
l3.setBounds(1000,200,10,525);
l3.setBackground(h4);
l4.setBounds(465,690,565,10);
l4.setBackground(h4);
// settings style amd font of buttons
newg = new JButton("New Game");
newg.setFont(new Font("Ravie", Font.PLAIN, 25));
newg.setBackground(Color.YELLOW);
newg.setOpaque(false);
newg.setBorder(null);
newg.setForeground(h2);
high = new JButton("High Scores");
robo= new JButton("Select your Robot");
inst = new JButton("How to Play");
high.setFont(new Font("Ravie", Font.PLAIN, 25));
high.setBackground(Color.YELLOW);
high.setOpaque(false);
high.setBorder(null);
high.setForeground(h1);
robo.setFont(new Font("Ravie", Font.PLAIN, 25));
robo.setBackground(Color.YELLOW);
robo.setOpaque(false);
robo.setBorder(null);
robo.setForeground(h);
inst.setFont(new Font("Ravie", Font.PLAIN, 25));
inst.setBackground(Color.YELLOW);
inst.setOpaque(false);
inst.setBorder(null);
inst.setForeground(Color.MAGENTA);
contain.setBounds(490,220,490,460);
contain.setLayout(new GridLayout(4,1));
side1.setBounds(0,40,mm.width,60);
up1.setBounds(40,0,40,mm.height);
side1.setBackground(h4);
up1.setBackground(h4);
//adding all the JComponents to the screen
side1.add(title);
contain.add(newg);
contain.add(high);
contain.add(robo);
contain.add(inst);
add(l1);
add(l2);
add(l3);
add(l4);
add(side1);
add(up1);
add(contain);
}
}
class Robot extends JPanel{
ImageIcon a;
ImageIcon b;
ImageIcon c;
JPanel side2;
JPanel up2;
static JButton r1;
static JButton r2;
static JButton r3;
static JButton back1;
static JButton go;
JLabel title1;
Robot(){
Color h= new Color(132,234,23);
MainMenu mm= new MainMenu();
Color h3= new Color(255,229,204);
Color h4= new Color(154,0,0);
side2= new JPanel();
up2= new JPanel();
r1= new JButton();
r2= new JButton();
r3= new JButton();
back1= new JButton("Back");
go= new JButton("LEt's go");
a = new ImageIcon(getClass().getResource("a.gif"));
b = new ImageIcon(getClass().getResource("b.gif"));
c = new ImageIcon(getClass().getResource("c.gif"));
//adding the ImageIcons to the JButtons
r1 = new JButton(a);
r1.setBounds(120,120,300,300);
r1.setBackground(Color.YELLOW);
r1.setOpaque(false);
r1.setBorder(null);
r2 = new JButton(b);
r2.setBounds(460,120,300,300);
r2.setBackground(Color.YELLOW);
r2.setOpaque(false);
r2.setBorder(null);
r3 = new JButton(c);
r3.setBounds(890,120,300,300);
r3.setBackground(Color.YELLOW);
r3.setOpaque(false);
r3.setBorder(null);
back1 = new JButton("Let's Go!");
back1.setBounds(520, 500, 170, 60);
back1.setFont(new Font("Ravie", Font.PLAIN, 25));
back1.setBackground(Color.YELLOW);
back1.setOpaque(false);
back1.setBorder(null);
setLayout(null);
title1 = new JLabel("E-ROBOT");
title1.setFont(new Font("Ravie", Font.PLAIN, 40)); //setting the style and the font of JLabel
// title1.setBounds(520, 100, 300, 50);
side2.setBounds(0,40,mm.width,60);
up2.setBounds(40,0,40,mm.height);
side2.setBackground(h);
up2.setBackground(h);
side2.add(title1);
add(side2);
add(up2);
add(r1);
add(r2);
add(r3);
add(back1);
add(go);
}
}
class High extends JPanel{
JLabel title3;
static JButton back2;
JPanel side4;
JPanel up4;
High()
{
Color h= new Color(132,234,23);
MainMenu mm= new MainMenu();
Color h3= new Color(255,229,204);
side4 = new JPanel();
up4= new JPanel();
Color h1= new Color(45,99,120);
setLayout(null);
title3 = new JLabel("E-ROBOT");
title3.setFont(new Font("Ravie", Font.PLAIN, 40)); //setting the style and the font of JLabel
title3.setBounds(520, 100, 300, 50);
back2= new JButton("Back");
back2.setBounds(500,500,120,30);
back2.setFont(new Font("Ravie", Font.PLAIN, 25));
back2.setBackground(Color.YELLOW);
back2.setOpaque(false);
back2.setBorder(null);
side4.setBounds(0,40,mm.width,60);
up4.setBounds(40,0,40,mm.height);
side4.setBackground(h1);
up4.setBackground(h1);
side4.add(title3);
add(side4);
add(up4);
add(back2);
}
}
class Inst extends JPanel{
JLabel jl1;
JLabel jl2;
JLabel jl3;
JLabel jl4;
JLabel jl5;
JLabel title2;
JPanel side3;
JPanel up3;
static JButton back;
JPanel contain2;
Inst(){
MainMenu mm= new MainMenu();
contain2= new JPanel();
side3= new JPanel();
up3= new JPanel();
Color h= new Color(132,234,23);
Color h3= new Color(255,229,204);
jl1= new JLabel("Welcome aboard\n !");
jl2 = new JLabel("So the game is simple.\n");
jl3 = new JLabel("You have to catch even number only\n.");
jl4 = new JLabel("A life ends if you catch an odd number.\n");
jl5 = new JLabel("Oh and also the game gets more difficult when your lives end!\n");
jl1.setFont(new Font("Ravie", Font.PLAIN, 20));
jl2.setFont(new Font("Ravie", Font.PLAIN, 20));
jl3.setFont(new Font("Ravie", Font.PLAIN, 20));
jl4.setFont(new Font("Ravie", Font.PLAIN, 20));
jl5.setFont(new Font("Ravie", Font.PLAIN, 20));
jl1.setForeground(Color.magenta);
jl2.setForeground(Color.magenta);
jl3.setForeground(Color.magenta);
jl4.setForeground(Color.magenta);
jl5.setForeground(Color.magenta);
title2 = new JLabel("E-ROBOT");
title2.setFont(new Font("Ravie", Font.PLAIN, 40)); //setting the style and the font of JLabel
title2.setBounds(520, 100, 300, 50);
back = new JButton("Back");
back.setFont(new Font("Ravie", Font.PLAIN, 15));
back.setBackground(Color.YELLOW);
back.setOpaque(false);
back.setBorder(null);
setLayout(null);
contain2.setBounds(80,200,800,400);
contain2.setBackground(h3);
side3.setBounds(0,40,mm.width,60);
up3.setBounds(40,0,40,mm.height);
side3.setBackground(Color.MAGENTA);
up3.setBackground(Color.MAGENTA);
side3.add(title2);
contain2.add(jl1);
contain2.add(jl2);
contain2.add(jl3);
contain2.add(jl4);
contain2.add(jl5);
contain2.add(back);
add(contain2);
add(side3);
add(up3);
}
}
I'm not sure whether it helps (sorry but your code is too large and bad formatted, so I cannot understand it), but you can try to revalidate and repaint the root pane or content pane of JFrame each time when you update your GUI.
Something like this
public static void updateRootPane(JComponent aComponent) {
Window w = SwingUtilities.windowForComponent(aComponent);
if (w instanceof JFrame) {
((JFrame) w).getRootPane().revalidate();
((JFrame) w).getRootPane().repaint();
} else if (w instanceof JDialog) {
((JDialog) w).getRootPane().revalidate();
((JDialog) w).getRootPane().repaint();
}
}

why isn't my Jlabels or Jpanels showing?

i've added a title to my Jframe, and now its blocked everything else, what have I done??
public class addressbook
{
public JFrame frame;
public JButton btnadd, btndelete, btnsave, btnprev, btnnext;
public JPanel panel, pTitle;
public JTextField txtname, txtaddress, txthomeno, txtmobno;
public JLabel JlbName , JlbHtn, JlbMtn, JlbAddress, lblTitle;
public addressbook() {
//sets window
frame = new JFrame();
frame.setTitle("Address Book");
frame.setSize(450, 580);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//sets up panel
panel = new JPanel();
panel.setLayout(null);
frame.getContentPane().add(panel);
pTitle = new JPanel();
pTitle.setLayout(new FlowLayout(FlowLayout.CENTER));
lblTitle = new JLabel("Bournemouth University Address Book");
pTitle.add(lblTitle);
frame.add(pTitle);
//Labels
JlbName = new JLabel("Name:");
JlbName.setBounds(10, 50, 100, 20);
panel.add(JlbName);
JlbHtn = new JLabel("Home Number:");
JlbHtn.setBounds(10, 90, 150, 20);
panel.add(JlbHtn);
JlbMtn = new JLabel("Mobile Number:");
JlbMtn.setBounds(10, 130, 200, 20);
panel.add(JlbMtn);
JlbAddress = new JLabel("Address:");
JlbAddress.setBounds(10, 170, 250, 20);
panel.add(JlbAddress);
//Text Fields
txtname = new JTextField("Name");
txtname.setBounds(120, 50, 200, 20);
panel.add(txtname);
txthomeno = new JTextField("Home Number");
txthomeno.setBounds(120, 90, 200, 20);
panel.add(txthomeno);
txtmobno = new JTextField("Mob Number");
txtmobno.setBounds(120, 130, 200, 20);
panel.add(txtmobno);
txtaddress = new JTextField("Address");
txtaddress.setBounds(120, 170, 250, 20);
panel.add(txtaddress);
frame.setVisible(true);
//Buttons && Button Functions
btnadd = new JButton("Add", new ImageIcon("../files/add.png"));
btnadd.setBounds(180, 350, 100, 50);
btnadd.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent event)
{
}});
panel.add(btnadd);
btndelete = new JButton("Delete", new ImageIcon("../files/delete2.png"));
btndelete.setBounds(180, 450, 100, 50);
btndelete.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent event)
{
}});
panel.add(btndelete);
btnsave = new JButton("Save", new ImageIcon("../files/save.png"));
btnsave.setBounds(180, 400, 100, 50);
btnsave.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent event)
{
}});
panel.add(btnsave);
btnprev = new JButton(new ImageIcon("../files/left.png"));
btnprev.setBounds(180, 300, 100, 50);
btnprev.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent event)
{
}});
panel.add(btnprev);
btnnext = new JButton(new ImageIcon("../files/right.png"));
btnnext.setBounds(180, 250, 100, 50);
btnnext.addActionListener(new ActionListener()
{public void actionPerformed(ActionEvent event)
{
}});
panel.add(btnnext);
frame.setVisible(true);
panel.setVisible(true);
}
If you are not using a LayoutManager on purpose (and it looks that way) make sure that you set a location and a size for your component.
pTitle.setLocation(100, 100);
pTitle.setSize(100, 100);
But you should rather remove this line
panel.setLayout(null);
and replace it with something like this:
panel.setLayout(new BorderLayout());
Also, don’t forget to add your pTitle to panel.
Add the label to the panel, don't create a new Panel for it
lblTitle = new JLabel("Bournemouth University Address Book");
lblTitle.setBounds(100, 0, 400, 20);
panel.add(lblTitle);
Try adding your JPanel pTitle to frame.getContentPane() or to the JPanel panel
Edit
Instead of
frame.add(pTitle);
do:
frame.getContentPanel().add(pTitle);
If this very quick fix doesn't help, stick with the answer you've already accepted.
You have to set a LayoutManager for your frame:
frame = new JFrame();
frame.getContentPane().setLayout(FooLayout());

Categories

Resources