Is there any code that I can use to pass value of selected radio button to another frame?
This is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class bookBatman extends JFrame implements ActionListener {
private JLabel jlbName, jlbTime, jlbPic, jlbDate, jlbDescription, jlbAuthor, jlbDateProduce, jlbDirector, jlbActor, jlbRate, jlbNoOfTicket, jlbPrice, jlbTotal;
private JTextField jtfNoOfTicket;
private JRadioButton jr1, jr2, jr3, jr4, jr5, jr6, jr7, jr8, jr9, jr10;
private JButton jTotal, jBook, jCancel;
Font f = new Font("Times",Font.BOLD,30);
public bookBatman () {
setLayout(null); //set LayoutManager
// initialized the label
jlbName = new JLabel ("Batman The Dark Knight");
jlbTime = new JLabel ("Time :");
jlbPrice = new JLabel ("RM 9.00");
jlbPic = new JLabel ();
jlbPic.setIcon(new ImageIcon("C:\\Users\\User\\Desktop\\OOP project\\img\\icon\\Batman.jpg"));
jlbTotal = new JLabel (" Total : RM 9.00");
// add all the label on the frame
add(jlbName);
add(jlbPic);
add(jlbTime);
add(jlbPrice);
add(jlbTotal);
// set all the label positions
jlbName.setBounds(85, 78, 300, 18); //(int x, int y, int width, int height)
jlbPic.setBounds(74, 101, 180, 288);
jlbTime.setBounds(74, 400, 60, 18);
jlbPrice.setBounds (270, 477, 60, 18);
jlbTotal.setBounds (339, 475, 300, 22);
// initialized the textfield
jlbAuthor = new JLabel ("Directed by Christopher Nolan");
jlbDateProduce = new JLabel ("Date : 17 July 2008");
jlbDirector = new JLabel ("Author : Jonathan Nolan, Christopher Nolan");
jlbActor = new JLabel ("Main Actor : Christian Bale");
jlbRate = new JLabel ("Movie Rate : 13 PG (Parental Guidance)");
jlbNoOfTicket = new JLabel ("Number of Ticket :");
// add all the textfield on the frame
add(jlbAuthor);
add(jlbDateProduce);
add(jlbDirector);
add(jlbActor);
add(jlbRate);
add(jlbNoOfTicket);
// set the textfield position
jlbAuthor.setBounds (273, 102, 300, 18);
jlbDateProduce.setBounds (273, 132, 300, 18);
jlbDirector.setBounds (273, 162, 300, 18);
jlbActor.setBounds (273, 192, 300, 18);
jlbRate.setBounds (273, 222, 300, 18);
jlbNoOfTicket.setBounds (77, 478, 150, 18);
// initialize the Radio Button
jr1 = new JRadioButton ("11.40 AM");
jr2 = new JRadioButton ("12.00 PM");
jr3 = new JRadioButton ("1.40 PM");
jr4 = new JRadioButton ("3.40 PM");
jr5 = new JRadioButton ("5.40 PM");
jr6 = new JRadioButton ("7.00 PM");
jr7 = new JRadioButton ("9.00 PM");
jr8 = new JRadioButton ("10.40 PM");
jr9 = new JRadioButton ("11.40 PM");
jr10 = new JRadioButton ("12.40 AM");
// add all the radion button
add(jr1);
add(jr2);
add(jr3);
add(jr4);
add(jr5);
add(jr6);
add(jr7);
add(jr8);
add(jr9);
add(jr10);
// set the radion button positions
jr1.setBounds (75, 423, 100, 24);
jr2.setBounds (172, 423, 100, 24);
jr3.setBounds (269, 423, 100, 24);
jr4.setBounds (366, 423, 100, 24);
jr5.setBounds (463, 423, 100, 24);
jr6.setBounds (75, 447, 100, 24);
jr7.setBounds (172, 447, 100, 24);
jr8.setBounds (269, 447, 100, 24);
jr9.setBounds (366, 447, 100, 24);
jr10.setBounds (463, 447, 100, 24);
// group the button
ButtonGroup group = new ButtonGroup ();
group.add(jr1);
group.add(jr2);
group.add(jr3);
group.add(jr4);
group.add(jr5);
group.add(jr6);
group.add(jr7);
group.add(jr8);
group.add(jr9);
group.add(jr10);
jr1.setActionCommand("radio1"); // for ButtonGroup
String sel = group.getSelection().getActionCommand();
// initialize all the button
jTotal = new JButton ("Total");
jBook = new JButton ("Book Now");
jCancel = new JButton ("Cancel");
// add all the button
add (jTotal);
add (jBook);
add (jCancel);
// set the button positions
jTotal.setBounds (191, 519, 83, 28);
jBook.setBounds (285, 519, 93, 28);
jCancel.setBounds (389, 519, 83, 28);
// add actionlistener
jTotal.addActionListener (this);
jBook.addActionListener (this);
jCancel.addActionListener (this);
// initialize all text field
jtfNoOfTicket = new JTextField (15);
// add all the text field
add (jtfNoOfTicket);
// set the text field positions
jtfNoOfTicket.setBounds (200, 477, 56, 22);
}
public void actionPerformed(ActionEvent e){
if((e.getSource() == jTotal)) {
double price = 12.00;
double number = (Integer.parseInt(jtfNoOfTicket.getText().trim()));
double total = 0.0;
total = price * number;
jlbTotal.setText(" Total : RM" + total +"0");
}
if((e.getSource() == jBook)) {
String name = jlbName.getText ();
String date = jlbDateProduce.getText ();
String time = jr1.getText ();
int number = (Integer.parseInt(jtfNoOfTicket.getText().trim()));
String total = jlbTotal.getText ();
String price = jlbPrice.getText ();
//Passing
ticketReservation frame = new ticketReservation(name, date, time, price, total, String.valueOf(number));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Ticket Reservation"); //set title of the window
frame.setSize(800,600); //size of the window
frame.setVisible(true); //visible the window
frame.setLocationRelativeTo (null); //center the window
}
if((e.getSource() == jCancel)) {
listOfMovies frame = new listOfMovies ();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("List of Movies"); //set title of thewindow
frame.setSize(800,600); //size of the window
frame.setVisible(true); //visible the window
frame.setLocationRelativeTo (null); //center the window
}
}
public static void main (String [] args) {
bookBatman frame = new bookBatman ();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Book Batman : The Dark Knight"); //set title of thewindow
frame.setSize(800,600); //size of the window
frame.setVisible(true); //visible the window
frame.setLocationRelativeTo (null); //center the window
}
}
Don't think of it as passing information from one GUI to another, but rather think of it in its most basic OOP form: as passing object state from one object to another. Often we use public accessor methods (i.e., "getter" methods) for this purpose and this can work here too.
Your ButtonGroup object will hold the ButtonModel of the selected JRadioButton (or null if none are selected) and so you can get the information from the model and return it from your getter method.
As an aside, your code has a lot of redundancies that can be reduced by using arrays and by using appropriate layout managers.
edit 1:
For Example
Say we create a JPanel that holds a bunch of JRadioButtons:
import java.awt.GridLayout;
import javax.swing.*;
class RadioBtnDialogPanel extends JPanel {
private static final String[] BUTTON_TEXTS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private ButtonGroup buttonGroup = new ButtonGroup();
public RadioBtnDialogPanel() {
setLayout(new GridLayout(0, 1)); // give JPanel a decent layout
// create radio buttons, add to button group and to JPanel
for (String buttonText : BUTTON_TEXTS) {
JRadioButton radioBtn = new JRadioButton(buttonText);
radioBtn.setActionCommand(buttonText); // set the actionCommand here
buttonGroup.add(radioBtn);
add(radioBtn);
}
}
// getter or accessor method to get selected JRadioButton's actionCommand text
public String getSelectedButtonText() {
ButtonModel model = buttonGroup.getSelection();
if (model == null) { // no radiobutton selected
return "";
} else {
return model.getActionCommand();
}
}
}
We also give it a public getter method that queries the state of the ButtonGroup to find out which button model has been selected and then return its actionCommand, a String that holds the text that describes the radio button (here it's the same as the text of the radio button).
We can then show this JPanel in a JOptionPane in our main GUI and after the JOptionPane is done, query the object above by calling its getSelectedButtonText() method:
import java.awt.event.*;
import javax.swing.*;
public class RadioButtonInfo extends JPanel {
private RadioBtnDialogPanel radioBtnDlgPanel = new RadioBtnDialogPanel();
private JTextField textfield = new JTextField(10);
public RadioButtonInfo() {
JButton getDayOfWeekBtn = new JButton("Get Day Of Week");
getDayOfWeekBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getDayOfWeekActionPerformed();
}
});
textfield.setFocusable(false);
add(getDayOfWeekBtn);
add(textfield);
}
private void getDayOfWeekActionPerformed() {
// display a JOptionPane that holds the radioBtnDlgPanel
int result = JOptionPane.showConfirmDialog(this, radioBtnDlgPanel, "Select Day Of Week", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) { // if use presses "OK" get the selected radio button text
// here we call the getter method to get the selected button text
String selectedButtonText = radioBtnDlgPanel.getSelectedButtonText();
textfield.setText(selectedButtonText); // and put it into a JTextField
}
}
private static void createAndShowUI() {
JFrame frame = new JFrame("RadioButtonInfo");
frame.getContentPane().add(new RadioButtonInfo());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Related
So I want to store a string value in a variable, the value is given through a JTextField and after a confirm button is clicked, I want it to store what's written in the text field in a string variable.
This is the relevant part of the code:
public class Window {
private JButton confirm;
private JTextField textfield;
private JLabel label;
public void drawWindow() {
JFrame window = new JFrame("CountryQuiz");
ClickChecker click = new ClickChecker();
JPanel panel = new JPanel();
panel.setBounds(40, 80, 200, 200);
panel.setBackground(Color.green);
JTextField t1 = new JTextField("Enter country...");
t1.setBounds(50, 100, 200, 30);
window.add(t1);
JButton confirm = new JButton("Confirm");
confirm.setBounds(50, 50, 95, 30);
confirm.addActionListener(click);
window.add(confirm);
window.setSize(400, 400);
window.setLayout(null);
window.setVisible(true);
window.add(panel);
}
private class ClickChecker implements ActionListener {
public void actionPerformed(ActionEvent e) {
String answer = textfield.getText();
System.out.println(answer);
}
}
}
Results in the following error:
Cannot invoke "javax.swing.JTextField.getText()" because "this.this$0.textfield" is null
Your textfield variable is only declared but never used.
Replace the below
JTextField t1 = new JTextField("Enter country...");
t1.setBounds(50, 100, 200, 30);
window.add(t1);
With
textfield = new JTextField("Enter country...");
textfield.setBounds(50, 100, 200, 30);
window.add(textfield);
Newbie question:
So this code here
public void comboItemItemStateChanged(java.awt.event.ItemEvent evt) {
ArrayList<String> arrayItem = new ArrayList<>();
Iterator<String> iter;
if(comboGroup.getSelectedItem().equals("Betta Fish")){
comboItem.removeAllItems();
arrayItem.add("Plakat");
arrayItem.add("Halfmoon");
arrayItem.add("Crown Tail");
arrayItem.add("Double Tail");
iter = arrayItem.iterator();
while(iter.hasNext()){
comboItem.addItem(iter.next());
}
}
else if(comboGroup.getSelectedItem().equals("Snails")){
comboItem.removeAllItems();
arrayItem.add("Apple Horn");
arrayItem.add("RamsHorn");
arrayItem.add("Pond Snail");
arrayItem.add("Assassin Snail");
iter = arrayItem.iterator();
while(iter.hasNext()){
comboItem.addItem(iter.next());
}
works when I try it on comboBoxes from Design tab in NetBeans. But when I try to apply it to my coded ComboBox, I get a message from evt saying Unused method parameters should be removed. Can I get an explanation why and what is the alternative for hardcoded comboBox?
Purpose of code: a dynamic comboBox so whatever I pick from comboBox1 will have each own set of lists for comboBox2
NOTE: I also tried to change comboItemItemStateChanged to just itemStatChanged.
Source code of my project: https://github.com/kontext66/GuwiPos/blob/main/GuwiPos
Sorry for the confusion everyone, I do have a main class.
public class Main{
public static void main(String[] args){
new GuwiPos();
new HelpWin();
}
}
Main.java, GuwiPos.java
It's quite simple, really.
The message is just NetBeans informing you that the code of method comboItemItemStateChanged does not reference the method parameter evt. It is not an error nor even a warning. You can ignore it. NetBeans displays these "hints" in its editor when you write code whereas NetBeans GUI builder generates code.
Note that method comboItemItemStateChanged will be called each time an item in the JComboBox is selected and also each time an item is de-selected. I'm guessing that you only want the code to run when an item is selected, hence the first line of method comboItemItemStateChanged should be
if (evt.getStateChange() == ItemEvent.SELECTED) {
and then you are referencing the method parameter and the "hint" will go away.
Refer to How to Write an Item Listener
Edit
I think maybe you would benefit from learning about GUI design. I have never seen one like yours. I would like to know how you arrived at that design. In any case, the below code addresses only the functionality whereby the list in comboItem adjusts depending on the selected item in comboGroup.
In my experience, removing and adding items to the JComboBox via methods removeAllItems and addItem, is very slow. It is much more efficient to simply replace the JComboBox model which is what I have done in the below code. For small lists such as yours, the difference will not be noticed but it increases as the lists get larger.
Also, the [JComboBox] selected item is in the evt parameter to method comboItemItemStateChanged.
Your original code did not add an item listener to comboGroup nor did it have a main method. I have added these in the below code. Note that the item listener is added via a method reference.
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import java.awt.Color;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author kahbg
*/
public class GuwiPos extends JFrame implements ActionListener {
public static final Map<String, ComboBoxModel<String>> LISTS;
JButton buttonBasket;
JButton buttonHelp;
JTextField txtGroup;
JTextField txtItem;
JTextField txtQty;
JTextField txtTotal;
JTextField txtPrice;
JComboBox<String> comboGroup;
JComboBox<String> comboItem;
static {
LISTS = new HashMap<>();
Vector<String> v = new Vector<>();
v.add("Plakat");
v.add("Halfmoon");
v.add("Crown Tail");
v.add("Double Tail");
ComboBoxModel<String> model = new DefaultComboBoxModel<>(v);
LISTS.put("Betta Fish", model);
v = new Vector<>();
v.add("Apple Horn");
v.add("RamsHorn");
v.add("Pond Snail");
v.add("Assassin Snail");
model = new DefaultComboBoxModel<>(v);
LISTS.put("Snails", model);
v = new Vector<>();
v.add("Small Fine Net");
v.add("Large Fine Net");
v.add("Flaring Mirror");
v.add("Aquarium Hose");
model = new DefaultComboBoxModel<>(v);
LISTS.put("Supplies", model);
v = new Vector<>();
v.add("Tubifex");
v.add("Daphnia");
v.add("Optimum Pellets");
model = new DefaultComboBoxModel<>(v);
LISTS.put("Food", model);
}
GuwiPos() {
// ComboBox
String[] products = {"Select Item...", "Betta Fish", "Snails", "Supplies", "Food"};
comboGroup = new JComboBox<String>(products);
comboGroup.addItemListener(this::comboItemItemStateChanged);
comboGroup.setBounds(130, 35, 150, 40);
comboItem = new JComboBox<String>();
comboItem.setBounds(130, 85, 150, 40);
// TextFields
txtPrice = new JTextField();
txtPrice.setBounds(130, 135, 150, 40);
txtQty = new JTextField();
txtQty.setBounds(130, 185, 150, 40);
txtTotal = new JTextField();
txtTotal.setBounds(130, 235, 150, 40);
// txtTotalAmt = new JTextField(); to code later on
// txtPaid = new JTextField(); to code later on
// txtChange = new JTextField(); to code later on
// Labels
// Product
JLabel labelProduct = new JLabel();
labelProduct.setText("Item Group");
labelProduct.setBounds(10, 5, 100, 100);
// Item
JLabel labelItem = new JLabel();
labelItem.setText("Item");
labelItem.setBounds(10, 55, 100, 100);
// Price
JLabel labelPrice = new JLabel();
labelPrice.setText("Price");
labelPrice.setBounds(10, 105, 100, 100);
// Qty
JLabel labelQty = new JLabel();
labelQty.setText("Quantity");
labelQty.setBounds(10, 155, 100, 100);
// Total
JLabel labelTotal = new JLabel();
labelTotal.setText("Total");
labelTotal.setBounds(10, 205, 100, 100);
// Buttons
buttonBasket = new JButton();
buttonBasket.setBounds(0, 0, 300, 50);
buttonBasket.setText("Add to Basket");
buttonBasket.setFocusable(false);
buttonBasket.setBorder(BorderFactory.createEtchedBorder());
buttonBasket.addActionListener(this);
JButton buttonPay = new JButton();
buttonPay.setText("PAY");
buttonPay.setBounds(0, 50, 150, 100);
buttonPay.setFocusable(false);
buttonPay.setBorder(BorderFactory.createEtchedBorder());
buttonPay.addActionListener(e -> System.out.println("Payment Success"));
JButton buttonCancel = new JButton();
buttonCancel.setText("CANCEL");
buttonCancel.setBounds(0, 150, 150, 100);
buttonCancel.setFocusable(false);
buttonCancel.setBorder(BorderFactory.createEtchedBorder());
buttonCancel.addActionListener(e -> System.out.println("Transaction Cancelled"));
JButton buttonDiscount = new JButton();
buttonDiscount.setText("Apply Discount?");
buttonDiscount.setBounds(150, 50, 150, 50);
buttonDiscount.setFocusable(false);
buttonDiscount.setBorder(BorderFactory.createEtchedBorder());
buttonDiscount.addActionListener(e -> System.out.println("20% Discount Applied"));
JButton buttonHelp = new JButton();
buttonHelp.setText("HELP");
buttonHelp.setBounds(150, 100, 150, 100);
buttonHelp.setFocusable(false);
buttonHelp.setBorder(BorderFactory.createEtchedBorder());
JButton buttonDelete = new JButton();
buttonDelete.setText("DELETE");
buttonDelete.setBounds(150, 200, 150, 50);
buttonDelete.setFocusable(false);
buttonDelete.setBorder(BorderFactory.createEtchedBorder());
buttonDelete.addActionListener(e -> System.out.println("Item Deleted"));
// Panels
// Left contains item and price
JPanel bluePanel = new JPanel();
bluePanel.setBackground(Color.blue);
bluePanel.setBounds(0, 0, 300, 300); // x,y,width,height
bluePanel.setLayout(null);
// Right contains product basket
JPanel redPanel = new JPanel();
redPanel.setBackground(Color.red);
redPanel.setBounds(300, 0, 600, 300); // x,y,width,length
redPanel.setLayout(null);
// Bottom Left contains buttons pay,change,discount
JPanel greenPanel = new JPanel();
greenPanel.setBackground(Color.green);
greenPanel.setBounds(0, 300, 300, 450);// x,y,width,length
greenPanel.setLayout(null);
// Bottom Right contains total amount
JPanel yellowPanel = new JPanel();
yellowPanel.setBackground(Color.yellow);
yellowPanel.setBounds(0, 300, 900, 450);// x,y,width,length
yellowPanel.setLayout(null);
this.setTitle("Open Betta POS");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.setSize(900, 590);
this.setResizable(false);
this.setVisible(true);
// ADDED AWT
bluePanel.add(txtQty);
bluePanel.add(txtTotal);
bluePanel.add(txtPrice);
bluePanel.add(comboItem);
bluePanel.add(comboGroup);
bluePanel.add(labelProduct);
bluePanel.add(labelItem);
bluePanel.add(labelPrice);
bluePanel.add(labelQty);
bluePanel.add(labelTotal);
greenPanel.add(buttonBasket);
greenPanel.add(buttonPay);
greenPanel.add(buttonCancel);
greenPanel.add(buttonDiscount);
greenPanel.add(buttonHelp);
greenPanel.add(buttonDelete);
this.add(bluePanel);
this.add(redPanel);
this.add(greenPanel);
this.add(yellowPanel);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonBasket) {
System.out.println("Added Item to Basket: " + comboGroup.getSelectedItem() + "\n"
+ comboItem.getSelectedItem());
}
}
// This is not working
public void comboItemItemStateChanged(java.awt.event.ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
Object selection = evt.getItem();
ArrayList<String> arrayItem = new ArrayList<>();
Iterator<String> iter;
if (selection.equals("Betta Fish")) {
comboItem.setModel(LISTS.get("Betta Fish"));
}
else if (selection.equals("Snails")) {
comboItem.setModel(LISTS.get("Snails"));
}
else if (selection.equals("Supplies")) {
comboItem.setModel(LISTS.get("Supplies"));
}
else if (selection.equals("Food")) {
comboItem.setModel(LISTS.get("Food"));
}
else if (selection.equals("Select Item...")) {
comboItem.removeAllItems();
arrayItem.add("Select Item...");
iter = arrayItem.iterator();
while (iter.hasNext()) {
comboItem.addItem(iter.next());
}
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new GuwiPos());
}
}
Your code (improved version - minus one ActionListener)
public class SwingApp {
private static JComboBox<String> comboItem;
private static JComboBox<String> productCombo;
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run () {
createAndShowGUI();
}
});
}
private static void createAndShowGUI () {
JFrame frame = createMainFrame();
JPanel bluePanel = createBluePanel();
JPanel greenPanel = createGreenPanel();
JPanel redPanel = createRedPanel();
JPanel yellowPanel = createYellowPanel();
frame.add(bluePanel);
frame.add(greenPanel);
frame.add(redPanel);
frame.add(yellowPanel);
frame.setVisible(true);
}
private static JFrame createMainFrame () {
JFrame frame = new JFrame("Open Betta POS");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(900, 590);
frame.setResizable(false);
return frame;
}
private static JPanel createBluePanel () {
ComboSelectionListener productComboListener = new ComboSelectionListener();
JPanel panel = new JPanel(null); // Sets layout manager to null which is a bad idea!
String[] products =
{"Select Item...", "Betta Fish", "Snails", "Supplies", "Food"};
productCombo = new JComboBox<>(products);
productCombo.setBounds(130, 35, 150, 40);
productCombo.setActionCommand("selectProduct");
productCombo.addActionListener(productComboListener);
comboItem = new JComboBox<>();
comboItem.setBounds(130, 85, 150, 40);
// TextFields
JTextField txtPrice = new JTextField();
txtPrice.setBounds(130, 135, 150, 40);
JTextField txtQty = new JTextField();
txtQty.setBounds(130, 185, 150, 40);
JTextField txtTotal = new JTextField();
txtTotal.setBounds(130, 235, 150, 40);
JLabel labelProduct = new JLabel();
labelProduct.setText("Item Group");
labelProduct.setBounds(10, 5, 100, 100);
// Item
JLabel labelItem = new JLabel();
labelItem.setText("Item");
labelItem.setBounds(10, 55, 100, 100);
// Price
JLabel labelPrice = new JLabel();
labelPrice.setText("Price");
labelPrice.setBounds(10, 105, 100, 100);
// Qty
JLabel labelQty = new JLabel();
labelQty.setText("Quantity");
labelQty.setBounds(10, 155, 100, 100);
// Total
JLabel labelTotal = new JLabel();
labelTotal.setText("Total");
labelTotal.setBounds(10, 205, 100, 100);
panel.setBackground(Color.blue);
panel.setBounds(0, 0, 300, 300); // x,y,width,height
panel.add(txtQty);
panel.add(txtTotal);
panel.add(txtPrice);
panel.add(comboItem);
panel.add(productCombo);
panel.add(labelProduct);
panel.add(labelItem);
panel.add(labelPrice);
panel.add(labelQty);
panel.add(labelTotal);
return panel;
}
private static JPanel createGreenPanel () {
JPanel panel = new JPanel(null);
panel.setBackground(Color.green);
panel.setBounds(0, 300, 300, 450);// x,y,width,length
JButton buttonBasket = new JButton();
buttonBasket.setBounds(0, 0, 300, 50);
buttonBasket.setText("Add to Basket");
buttonBasket.setFocusable(false);
buttonBasket.setBorder(BorderFactory.createEtchedBorder());
buttonBasket
.addActionListener(e -> System.out.println("Added Item to Basket: "
+ productCombo.getSelectedItem() + "\n" + comboItem.getSelectedItem()));
JButton buttonPay = new JButton();
buttonPay.setText("PAY");
buttonPay.setBounds(0, 50, 150, 100);
buttonPay.setFocusable(false);
buttonPay.setBorder(BorderFactory.createEtchedBorder());
buttonPay.addActionListener(e -> System.out.println("Payment Success"));
JButton buttonCancel = new JButton();
buttonCancel.setText("CANCEL");
buttonCancel.setBounds(0, 150, 150, 100);
buttonCancel.setFocusable(false);
buttonCancel.setBorder(BorderFactory.createEtchedBorder());
buttonCancel
.addActionListener(e -> System.out.println("Transaction Cancelled"));
JButton buttonDiscount = new JButton();
buttonDiscount.setText("Apply Discount?");
buttonDiscount.setBounds(150, 50, 150, 50);
buttonDiscount.setFocusable(false);
buttonDiscount.setBorder(BorderFactory.createEtchedBorder());
buttonDiscount
.addActionListener(e -> System.out.println("20% Discount Applied"));
JButton buttonHelp = new JButton();
buttonHelp.setText("HELP");
buttonHelp.setBounds(150, 100, 150, 100);
buttonHelp.setFocusable(false);
buttonHelp.setBorder(BorderFactory.createEtchedBorder());
JButton buttonDelete = new JButton();
buttonDelete.setText("DELETE");
buttonDelete.setBounds(150, 200, 150, 50);
buttonDelete.setFocusable(false);
buttonDelete.setBorder(BorderFactory.createEtchedBorder());
buttonDelete.addActionListener(e -> System.out.println("Item Deleted"));
panel.add(buttonBasket);
panel.add(buttonPay);
panel.add(buttonCancel);
panel.add(buttonDiscount);
panel.add(buttonHelp);
panel.add(buttonDelete);
return panel;
}
private static JPanel createRedPanel () {
JPanel panel = new JPanel(null);
panel.setBackground(Color.red);
panel.setBounds(300, 0, 600, 300); // x,y,width,length
return panel;
}
private static JPanel createYellowPanel () {
JPanel panel = new JPanel();
panel.setBackground(Color.yellow);
panel.setBounds(0, 300, 900, 450); // x,y,width,length
return panel;
}
private static class ComboSelectionListener implements ActionListener {
#Override
public void actionPerformed (ActionEvent e) {
JComboBox<String> comboGroup = (JComboBox<String>) e.getSource();
ArrayList<String> arrayItem = new ArrayList<>();
Iterator<String> iter;
if (comboGroup.getSelectedItem().equals("Betta Fish")) {
comboItem.removeAllItems();
arrayItem.add("Plakat");
arrayItem.add("Halfmoon");
arrayItem.add("Crown Tail");
arrayItem.add("Double Tail");
iter = arrayItem.iterator();
while (iter.hasNext()) {
comboItem.addItem(iter.next());
}
} else if (comboGroup.getSelectedItem().equals("Snails")) {
comboItem.removeAllItems();
arrayItem.add("Apple Horn");
arrayItem.add("RamsHorn");
arrayItem.add("Pond Snail");
arrayItem.add("Assassin Snail");
iter = arrayItem.iterator();
while (iter.hasNext()) {
comboItem.addItem(iter.next());
}
} else if (comboGroup.getSelectedItem().equals("Supplies")) {
comboItem.removeAllItems();
arrayItem.add("Small Fine Net");
arrayItem.add("Large Fine Net");
arrayItem.add("Flaring Mirror");
arrayItem.add("Aquarium Hose");
iter = arrayItem.iterator();
while (iter.hasNext()) {
comboItem.addItem(iter.next());
}
} else if (comboGroup.getSelectedItem().equals("Food")) {
comboItem.removeAllItems();
arrayItem.add("Tubifex");
arrayItem.add("Daphnia");
arrayItem.add("Optimum Pellets");
iter = arrayItem.iterator();
while (iter.hasNext()) {
comboItem.addItem(iter.next());
}
} else if (comboGroup.getSelectedItem().equals("Select Item...")) {
comboItem.removeAllItems();
arrayItem.add("Select Item...");
iter = arrayItem.iterator();
while (iter.hasNext()) {
comboItem.addItem(iter.next());
}
}
}
}
}
Improvements made (aside from fixing the main issue)
Created a Swing (main) class that is not a Swing component
Main class doesn't implement ActionListener
Used SwingUtilities to launch Swing Application
Created methods to encapsulate the details involving the creation of components
Minimized the scope of variables
When i created my gui in java, i set the background color to blackish and there seems to be a pixel line of white at the right most and bottom most sections of my gui. However when i resize this gui, that like goes away and the gui is completely black. Does anyone know why this is happening? I need my gui to set resizeable to false so resizing the gui to fix this problem will not work.
package JavaQuizGameTut;
import java.awt.ActiveEvent.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class Quiz implements ActionListener{
String[] questions = {
"Which company created Java?",
"What year was Java created?",
"What was java originally called?",
"Who was credited for making java?"
};
String[][] options = {{"Sun Microsystems", "Starbucks", "Microsoft", "Alphabet"},
{"1989", "1996", "1972", "1492"},
{"Apple", "Latte", "Oak", "Koffing"},
{"Steve Jobs", "Bill Gates", "James Gosling", "Mark Zuckerburg"}
};
char[] answers = {'A', 'B', 'C', 'C'};
char guess;
char answer;
int index;
int correct_guesses = 0;
int total_questions = questions.length;
int result;
int seconds;
JFrame frame = new JFrame();
JTextField textfield = new JTextField();
JTextArea textarea = new JTextArea();
JButton buttonA = new JButton();
JButton buttonB = new JButton();
JButton buttonC = new JButton();
JButton buttonD = new JButton();
JLabel answer_labelA = new JLabel();
JLabel answer_labelB = new JLabel();
JLabel answer_labelC = new JLabel();
JLabel answer_labelD = new JLabel();
JLabel time_label = new JLabel();
JLabel seconds_left = new JLabel();
JTextField number_right = new JTextField();
JTextField percentage = new JTextField();
public Quiz() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 650);
frame.getContentPane().setBackground(new Color(50, 50, 50));
frame.setLayout(null);
// frame.setResizable(false);
textfield.setBounds(0, 0, 650, 50);
textfield.setBackground(new Color(25,25, 25));
textfield.setForeground(new Color(25, 255, 0));
textfield.setFont(new Font("Ink Free", Font.PLAIN, 30));
textfield.setBorder(BorderFactory.createBevelBorder(1));
textfield.setHorizontalAlignment(JTextField.CENTER);
textfield.setEditable(false);
frame.add(textfield);
frame.setVisible(true);
}
public void nextQuestion() {
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public void displayAnswer() {
}
public void results() {
}
}
The background color does cover the entire frame only the reason you are seeing a grey bar above it is that you have placed a textfield on top of it and you have set its background colour to be grey.
As in here:
textfield.setBounds(0, 0, 650, 50);
textfield.setBackground(new Color(25,25, 25));
Try changing textfield's color or temporarily commenting it and you'll see whole frame black.
If nothing fixes it then there's something wrong with your system as it is running fine in my system.
You can try running it in another system.
Hi I'm doing a program that firstly opens setting menu like in the picture
enter image description here
first I select the choices of the game I want from the jcombox and jdialog that open window to set the names .
this is the code of it :
public class SettingMenu extends JFrame {
boolean is3players = false, is4players = false;
BufferedImage settingImage;
String[] playersChoises = { "2", "3", "4" };
String[] sizeChoises = { "30", "50", "100" };
JComboBox comboBoxPlayers;
JComboBox comboBoxSizes;
static JButton startGame, writeNames;
public SettingMenu() {
JLabel howManyPlayersText = new JLabel("How many players ?");
comboBoxPlayers = new JComboBox(playersChoises);
if (comboBoxPlayers.getSelectedItem().equals("3")) {
is3players = true;
}
if (comboBoxPlayers.getSelectedItem().equals("4")) {
is3players = true;
is4players = true;
}
JLabel writeNamesText = new JLabel("Set names of playes");
writeNames = new JButton("set names");
JLabel sizeOfBoredText = new JLabel("What the size of the bored ?");
comboBoxSizes = new JComboBox(sizeChoises);
startGame = new JButton("Click to start the game!");
howManyPlayersText.setBounds(177, 200, 270, 100);
comboBoxPlayers.setBounds(230, 270, 100, 30);
writeNamesText.setBounds(230, 210, 380, 250);
writeNames.setBounds(240, 350, 100, 36);
sizeOfBoredText.setBounds(177, 376, 300, 100);
comboBoxSizes.setBounds(230, 450, 100, 30);
startGame.setBounds(200, 500, 200, 44);
add(howManyPlayersText);
add(comboBoxPlayers);
add(writeNamesText);
add(writeNames);
add(sizeOfBoredText);
add(comboBoxSizes);
add(startGame);
setVisible(true);
}
public static void main(String[] args) {
// open this class
new SettingMenu();
// when i click on startgame bottun open the class of the game
startGame.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new LeadersAndSnake_Project201();
}
});
// when i click on writeNames bottun open the class of dialog
writeNames.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new SetNames();
}
});
}
}
and this is Set Names class which open the set names window
enter image description here
class SetNames extends JDialog {
public JTextField setNamePlayer1, setNamePlayer2, setNamePlayer3, setNamePlayer4;
public SetNames() {
this.setSize(280, 151);
this.setLocationRelativeTo(null);
JLabel name1 = new JLabel("Set Player's 1 name : ");
setNamePlayer1 = new JTextField(7);
setNamePlayer1.setText("Player 1");
JLabel name2 = new JLabel("Set Player's 2 name : ");
setNamePlayer2 = new JTextField(7);
setNamePlayer2.setText("Player 2");
JPanel panelOfDialog_1 = new JPanel();
panelOfDialog_1.add(name1);
panelOfDialog_1.add(setNamePlayer1);
JPanel panelOfDialog_2 = new JPanel();
panelOfDialog_2.add(name2);
panelOfDialog_2.add(setNamePlayer2);
JPanel panelOfDialog_3 = new JPanel();
JButton okBotton = new JButton("OK");
add(okBotton);
okBotton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setNamePlayer1 = new JTextField(setNamePlayer1.getText());
setNamePlayer2 = new JTextField(setNamePlayer2.getText());
setVisible(false);
}
});
panelOfDialog_3.add(okBotton);
add(panelOfDialog_1, BorderLayout.NORTH);
add(panelOfDialog_2, BorderLayout.CENTER);
add(panelOfDialog_3, BorderLayout.AFTER_LAST_LINE);
this.setVisible(true);
}
}
and this is the large class for the game but I just put the imprtant thinga here :
class LeadersAndSnake_Project201 extends JFrame implements ActionListener{
// Here I made an object of Setting Menu class for use the varible that it has
SettingMenu obj1 = new SettingMenu();
// Here I made an object of Set Names class to take the name inside the textfiled
SetNames obj2 = new SetNames();
public LeadersAndSnake_Project201() {
// -----------------left panel------------------------------
JPanel leftPanel = new JPanel();
GroupLayout groupLayout = new GroupLayout(leftPanel);
leftPanel.setLayout(groupLayout);
//---------------------------panel 1 for information player 1 -------------------------------------
JPanel panel1 = new JPanel();
ImageIcon imageMan1 = new ImageIcon("man1.png");
JLabel imageMan11 = new JLabel("", imageMan1, JLabel.CENTER);
JLabel player1text = new JLabel(obj2.setNamePlayer1.getText());
panel1.add(imageMan11);
panel1.add(player1text);
//---------------------------panel 2 for information player 2------------------------------------
JPanel panel2 = new JPanel();
ImageIcon imageMan2 = new ImageIcon("man2.png");
JLabel imageMan22 = new JLabel("", imageMan2, JLabel.CENTER);
JLabel player2text = new JLabel(obj2.setNamePlayer2.getText());
panel2.add(imageMan22);
panel2.add(player2text);
//---------------------------panel 3 for information player 3-------------------------------------
JPanel panel3 = new JPanel();
if(obj.is3 == true){
ImageIcon imageMan3 = new ImageIcon("man3.png");
JLabel imageMan33 = new JLabel("", imageMan3, JLabel.CENTER);
JLabel player3text = new JLabel("Player 3");
player2text.setFont(fontText);
panel3.add(imageMan33);
panel3.add(player3text);
}
}
}
Here on left panel are my problems
the jlable of player 1 and player 2 didn't chang even if I try to change them in the textfiled and the second problem is that the panel of player 3 didn't apper even if I select the chois "3" from the combox .
enter image description here
Try to call .pack() on the Frame after altering the elements.
EDIT
You have no code changing the labels. What you need is store the labels in a variable, like you did with other components, and in the ActionListener on on the okButton in SetNames(), instead of doing whatever you do to the TextFields there (which looks wrong), update the Label text.
So, for example
class SetNames extends JDialog {
[...]
public JButton okButton; // save okButton so others can add listeners
}
class LeadersAndSnake_Project201 extends JFrame implements ActionListener{
// Here I made an object of Set Names class to take the name inside the textfiled
SetNames obj2 = new SetNames();
public LeadersAndSnake_Project201() {
[...]
obj2.okButton.addActionListener(new ActionListener(){/*update labels*/});
}}
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();
}
}
}