Related
I create Two Java File, the one is Reg.java and the second is Get.java. in Reg.java I create a JFrame with textfield for name and textfield for age, and a button. all i want is when you enter the name and age in textfields and click button, it will pass the string name and age and show in Get.java.
this is my code for Reg.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Reg extends JFrame implements ActionListener {
private Container con = getContentPane();
FlowLayout fl = new FlowLayout();
JLabel lb1 = new JLabel(": ");
JTextField tf1 = new JTextField(14);
JLabel lb2 = new JLabel("Enter your Age: ");
JTextField tf2 = new JTextField(14);
JButton btnSub = new JButton("Submit");
public Reg(){
setLayout(fl);
setSize(350, 275);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(lb1);
add(tf1);
add(lb2);
add(tf2);
add(btnSub);
lb1.setAlignmentX(LEFT_ALIGNMENT);
lb2.setAlignmentX(LEFT_ALIGNMENT);
lb1.setPreferredSize(new Dimension(120,50));
lb2.setPreferredSize(new Dimension(120,50));
tf1.setAlignmentX(RIGHT_ALIGNMENT);
tf2.setAlignmentX(RIGHT_ALIGNMENT);
btnSub.setHorizontalAlignment(JButton.CENTER);
btnSub.setToolTipText("Click to Submit");
btnSub.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
String name = tf1.getText();
String age = tf2.getText();
}
public static void main(String[] args){
Reg fr = new Reg();
fr.setVisible(true);
}
}
For a more general situation you might provide methods for accessing the user name and password, and a reference from the main class to the login class in order to call those methods.
But this does not require two Java classes, let alone two Java files. It also does not require using two frames, in fact, this is one case where multiple frames makes the task more tricky, in that a frame is non-modal. Use a modal JDialog or a JOptionPane instead of the 'login frame'. That way, the password can be checked as soon it is dismissed.
This is what it might look like: (tip: the valid password for all users is 'guest')
Here's how to go about it:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class LoginRequired {
private JTextField usernameField = new JTextField("Joe Blogs");
private JPasswordField passwordField = new JPasswordField();
char[] password = {'g', 'u', 'e', 's', 't'};
JPanel loginPanel;
LoginRequired() {
JFrame f = new JFrame("Login Required");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JLabel output = new JLabel(
"Login is required to use this application!",
SwingConstants.CENTER);
output.setBorder(new EmptyBorder(50, 100, 50, 100));
f.add(output);
f.pack();
f.setResizable(false);
f.setLocationByPlatform(true);
f.setVisible(true);
boolean loginValid = false;
while (!loginValid) {
showLogin(f);
loginValid = isLoginValid();
}
String user = usernameField.getText();
output.setText("Welcome back, " + user + "!");
f.setTitle("Logged In: " + user);
}
private boolean isLoginValid() {
char[] passwordEntered = passwordField.getPassword();
if (passwordEntered.length != password.length) {
return false;
} else {
for (int ii = 0; ii < password.length; ii++) {
if (password[ii] != passwordEntered[ii]) {
return false;
}
}
return true;
}
}
private void showLogin(JFrame frame) {
if (loginPanel==null) {
loginPanel = new JPanel(new BorderLayout(5, 5));
JPanel labels = new JPanel(new GridLayout(0, 1, 2, 2));
labels.add(new JLabel("User Name", SwingConstants.RIGHT));
labels.add(new JLabel("Password", SwingConstants.RIGHT));
loginPanel.add(labels, BorderLayout.WEST);
JPanel controls = new JPanel(new GridLayout(0, 1, 2, 2));
usernameField = new JTextField("Joe Blogs");
controls.add(usernameField);
passwordField = new JPasswordField();
controls.add(passwordField);
loginPanel.add(controls, BorderLayout.CENTER);
}
passwordField.setText("");
JOptionPane.showMessageDialog(
frame, loginPanel, "Log In", JOptionPane.QUESTION_MESSAGE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new LoginRequired();
}
});
}
}
public class Reg extends JFrame implements ActionListener {
.....
'''''
Get get;
public Reg(){
.....
.....
get = new Get();
}
#Override
public void actionPerformed(ActionEvent e){
String name = tf1.getText();
String age = tf2.getText();
get.print(name);
get.print(age);
}
}
class Get{
public void print(String txt) {
System.out.println(txt);
}
}
Use BuferedReader with get.java and use BufferedWriter with reg.java.
Use BufferedWriter in reg.java to write the Name and age in two lines and then use BufferedReader to read these values in Get.java.
There is 3 panels which I created as seen in the image. The first panel is the "From" panel, second is "To" panel, and third is the buttons panel. So the question is, how can I put a new line for the "Enter Temperature: [ ]" so that it will be under neath the radio buttons? I am very new to Java swing/awt please bear with me.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class TemperatureConversion extends JFrame{
// component
JTextField txtFromTemp, txtToTemp;
JLabel lblFromTemp, lblToTemp;
JRadioButton radFromCelsius, radFromFahrenheit, radFromKelvin;
JRadioButton radToCelsius, radToFahrenheit, radToKelvin;
JPanel pnlFromRadioButton, pnlToRadioButton, pnlFromTemp, pnlButton;
ButtonGroup bgFrom, bgTo;
JButton btnConvert, btnExit;
// constructor
public TemperatureConversion(){
super("Temperature");
// assign objects
radFromCelsius = new JRadioButton("Celsius", true);
radFromFahrenheit = new JRadioButton("Fahrenheit");
radFromKelvin = new JRadioButton("Kelvin");
lblFromTemp = new JLabel("Enter Temperature: ");
pnlFromTemp = new JPanel();
btnConvert = new JButton("Convert");
btnExit = new JButton("Exit");
pnlButton = new JPanel();
txtFromTemp = new JTextField(3);
lblToTemp = new JLabel("Comparable Temperature: ");
txtToTemp = new JTextField(3);
// register the button to a listener
btnExit.addActionListener(new MyButtonListener());
btnConvert.addActionListener(new MyButtonListener());
// make the multiple choice exclusive but not a container
bgFrom = new ButtonGroup();
bgFrom.add(radFromCelsius);
bgFrom.add(radFromFahrenheit);
bgFrom.add(radFromKelvin);
// radio buttons
radToCelsius = new JRadioButton("Celsius");
radToFahrenheit = new JRadioButton("Fahrenheit", true);
radToKelvin = new JRadioButton("Kelvin");
// make the multiple choice exclusive
bgTo = new ButtonGroup();
bgTo.add(radToCelsius);
bgTo.add(radToFahrenheit);
bgTo.add(radToKelvin);
pnlFromRadioButton = new JPanel();
pnlToRadioButton = new JPanel();
// decorate the panel
pnlFromRadioButton.setBorder(BorderFactory.createTitledBorder("From"));
pnlToRadioButton.setBorder(BorderFactory.createTitledBorder("To"));
// add radiobutton to panel
pnlFromRadioButton.add(radFromCelsius);
pnlFromRadioButton.add(radFromFahrenheit);
pnlFromRadioButton.add(radFromKelvin);
pnlToRadioButton.add(radToCelsius);
pnlToRadioButton.add(radToFahrenheit);
pnlToRadioButton.add(radToKelvin);
// add button to panel
pnlButton.add(btnConvert);
pnlButton.add(btnExit);
// add label and txt field to panel
pnlFromRadioButton.add(lblFromTemp);
pnlFromRadioButton.add(txtFromTemp);
pnlToRadioButton.add(lblToTemp);
txtToTemp.setEditable(false);
pnlToRadioButton.add(txtToTemp);
// add panels to the frame
add(pnlFromRadioButton, BorderLayout.NORTH);
add(pnlToRadioButton, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
// private inner class to handle button event
private class MyButtonListener implements ActionListener {
// must override actionPerformed method
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnConvert) {
if (radFromCelsius.isSelected())
System.out.print("exit");
} else if (e.getSource() == btnExit) {
System.exit(0);
}
}
}
public static void main(String[] args) {
new TemperatureConversion();
}
}
Nest more JPanels and use layout managers
For instance, in the JPanel where you want two lines, give it a BoxLayout oriented along the BoxLayout.PAGE_AXIS, and then add two more JPanels to this BoxLayout-using, a top JPanel with the radio buttons and bottom JPanel with the JLabel and JTextField (or whatever else you want in it).
Side note: this would be a great place to use an enum one called TempScale that had three values: CELSIUS, FAHRENHEIT, KELVIN. You could even give the enum the formulas for conversion to and from Kelvin.
For example:
import java.awt.Component;
import java.awt.event.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class TempConversion2 extends JPanel {
private ToFromPanel fromPanel = new ToFromPanel("From", true);
private ToFromPanel toPanel = new ToFromPanel("To", false);
private ButtonPanel buttonPanel = new ButtonPanel(fromPanel, toPanel);
public TempConversion2() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(fromPanel);
add(toPanel);
add(buttonPanel);
}
private static void createAndShowGui() {
TempConversion2 mainPanel = new TempConversion2();
JFrame frame = new JFrame("Temp Convert");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class ButtonPanel extends JPanel {
public ButtonPanel(ToFromPanel fromPanel, ToFromPanel toPanel) {
add(new JButton(new ConvertAction("Convert", fromPanel, toPanel)));
add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
}
}
#SuppressWarnings("serial")
class ConvertAction extends AbstractAction {
private ToFromPanel fromPanel;
private ToFromPanel toPanel;
public ConvertAction(String name, ToFromPanel fromPanel, ToFromPanel toPanel) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
this.fromPanel = fromPanel;
this.toPanel = toPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
String text = fromPanel.getText();
try {
double fromTemp = Double.parseDouble(text.trim());
TempScale fromScale = fromPanel.getTempScalesPanel().getSelectedTempScale();
double kelvinValue = fromScale.convertToKelvin(fromTemp);
TempScale toScale = toPanel.getTempScalesPanel().getSelectedTempScale();
double toValue = toScale.convertFromKelvin(kelvinValue);
String toValueString = String.format("%.2f", toValue);
toPanel.setText(toValueString);
} catch (NumberFormatException e1) {
Component parentComponent = fromPanel;
String message = "Text must be a valid number: " + text;
String title = "Invalid Text Entered";
int messageType = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(parentComponent, message, title, messageType);
fromPanel.setText("");
}
}
}
#SuppressWarnings("serial")
class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
#SuppressWarnings("serial")
class ToFromPanel extends JPanel {
private String title;
private TempScalesPanel tempScalesPanel = new TempScalesPanel();
private JTextField tempTextField = new JTextField(3);
public ToFromPanel(String title, boolean textFieldEnabled) {
this.title = title;
tempTextField.setFocusable(textFieldEnabled);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
bottomPanel.add(new JLabel("Temperature:"));
bottomPanel.add(Box.createHorizontalStrut(8));
bottomPanel.add(tempTextField);
setBorder(BorderFactory.createTitledBorder(title));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(tempScalesPanel);
add(bottomPanel);
}
public String getTitle() {
return title;
}
public TempScalesPanel getTempScalesPanel() {
return tempScalesPanel;
}
public String getText() {
return tempTextField.getText();
}
public void setText(String text) {
tempTextField.setText(text);
}
}
#SuppressWarnings("serial")
class TempScalesPanel extends JPanel {
private ButtonGroup buttonGroup = new ButtonGroup();
private Map<ButtonModel, TempScale> buttonTempMap = new HashMap<>();
public TempScalesPanel() {
for (TempScale tempScale : TempScale.values()) {
JRadioButton radioButton = new JRadioButton(tempScale.getName());
add(radioButton);
buttonGroup.add(radioButton);
buttonTempMap.put(radioButton.getModel(), tempScale);
// set first button as selected by default
if (buttonGroup.getSelection() == null) {
buttonGroup.setSelected(radioButton.getModel(), true);
}
}
}
public TempScale getSelectedTempScale() {
ButtonModel model = buttonGroup.getSelection();
return buttonTempMap.get(model);
}
}
This is the enum that I was talking about. Note that if you change the enum, and for instance add another temperature scale element, the program will automatically include it in the GUI and in the calculations. God I love Java and OOP.
public enum TempScale {
CELSIUS("Celsius", 1.0, -273.15),
FAHRENHEIT("Fahrenheit", 5.0 / 9.0, -459.67),
KELVIN("Kelvin", 1.0, 0.0);
private TempScale(String name, double ratioToKelvin, double absZero) {
this.name = name;
this.ratioToKelvin = ratioToKelvin;
this.absZero = absZero;
}
private String name;
private double ratioToKelvin;
private double absZero;
public String getName() {
return name;
}
public double getRatioToKelvin() {
return ratioToKelvin;
}
public double getAbsZero() {
return absZero;
}
public double convertToKelvin(double value) {
return (value - absZero) * ratioToKelvin;
}
public double convertFromKelvin(double kelvinValue) {
return (kelvinValue / ratioToKelvin) + absZero;
}
}
Always consider posting an MCVE.
For example you layout can be simplified and demonstrated with :
import java.awt.BorderLayout;
import java.awt.Label;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TemperatureConversion extends JFrame{
JPanel pnlFromRadioButton, pnlToRadioButton, pnlFromTemp, pnlButton;
// constructor
public TemperatureConversion(){
pnlFromRadioButton = new JPanel();
pnlFromRadioButton.add(new Label("From Panel"));
pnlToRadioButton = new JPanel();
pnlToRadioButton.add(new Label("To Panel"));
pnlButton = new JPanel();
pnlButton.add(new Label("Buttons Panel"));
// add panels to the frame
add(pnlFromRadioButton, BorderLayout.NORTH);
add(pnlToRadioButton, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TemperatureConversion();
}
}
Suppose you want to an "Enter Temperature: [ ]" label to show in a different "line" under From buttons, your constructor will change to :
public TemperatureConversion(){
//set a layout manger. You could use grid layout
//GridLayout gridLayout = new GridLayout(4, 1);
//Or BoxLayout
BoxLayout boxLayout = new BoxLayout(getContentPane(), BoxLayout.Y_AXIS); // top to bottom
setLayout(boxLayout);
pnlFromRadioButton = new JPanel();
pnlFromRadioButton.add(new Label("From Panel"));
//create a panel to hold the desired label
pnlFromTemp = new JPanel();
pnlFromTemp.add(new JLabel("Enter Temperature: [ ]"));//add label
pnlToRadioButton = new JPanel();
pnlToRadioButton.add(new Label("To Panel"));
pnlButton = new JPanel();
pnlButton.add(new Label("Buttons Panel"));
// add panels to the frame
//the panel will show in the order added
add(pnlFromRadioButton);
add(pnlFromTemp);
add(pnlToRadioButton);
add(pnlButton);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Sorry I am new to forums and am not familiar with posting etiquette for codes #c0der. But using GridLayout solved my problem and I want to show you what I did, it is a big mess but here it is. Here is my bizarre code but don't know how to reduce it any further. This is how it is suppose to look as I wanted and because now I understand what you mean by "Nest more JPanels and use layout managers" #Hovercraft Full of Eels:
my temperature program
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.*;
public class TemperatureConversion extends JFrame {
// component
JTextField txtFromTemp, txtToTemp;
JLabel lblFromTemp, lblToTemp, lblToTempbox;
JRadioButton radFromCelsius, radFromFahrenheit, radFromKelvin;
JRadioButton radToCelsius, radToFahrenheit, radToKelvin;
JPanel pnlFromRadioButton, pnlToRadioButton, pnlFrom, pnlTo, pnlButton;
JPanel pnlEnterTemp, pnlComparableTemp;
ButtonGroup bgFrom, bgTo;
JButton btnConvert, btnExit;
// constructor
public TemperatureConversion() {
super("Temperature");
// assign objects
radFromCelsius = new JRadioButton("Celsius", true);
radFromFahrenheit = new JRadioButton("Fahrenheit");
radFromKelvin = new JRadioButton("Kelvin");
lblFromTemp = new JLabel("Enter Temperature: ");
pnlFrom = new JPanel();
btnConvert = new JButton("Convert");
btnExit = new JButton("Exit");
pnlButton = new JPanel();
txtFromTemp = new JTextField(3);
lblToTemp = new JLabel("Comparable Temperature: ");
txtToTemp = new JTextField(3);
pnlTo = new JPanel();
pnlEnterTemp = new JPanel();
pnlComparableTemp = new JPanel();
pnlFromRadioButton = new JPanel();
pnlToRadioButton = new JPanel();
// register the button to a listener
btnExit.addActionListener(new MyButtonListener());
btnConvert.addActionListener(new MyButtonListener());
// make the multiple choice exclusive but not a container
bgFrom = new ButtonGroup();
bgFrom.add(radFromCelsius);
bgFrom.add(radFromFahrenheit);
bgFrom.add(radFromKelvin);
// radio buttons
radToCelsius = new JRadioButton("Celsius");
radToFahrenheit = new JRadioButton("Fahrenheit", true);
radToKelvin = new JRadioButton("Kelvin");
// make the multiple choice exclusive
bgTo = new ButtonGroup();
bgTo.add(radToCelsius);
bgTo.add(radToFahrenheit);
bgTo.add(radToKelvin);
pnlFrom.setLayout(new GridLayout(2, 1));
pnlFrom.add(pnlFromRadioButton);
pnlFrom.add(pnlEnterTemp);
pnlTo.setLayout(new GridLayout(2, 1));
pnlTo.add(pnlToRadioButton);
pnlTo.add(pnlComparableTemp);
// decorate the panel
pnlFrom.setBorder(BorderFactory.createTitledBorder("From"));
pnlTo.setBorder(BorderFactory.createTitledBorder("To"));
// add radiobutton to panel
pnlFromRadioButton.add(radFromCelsius);
pnlFromRadioButton.add(radFromFahrenheit);
pnlFromRadioButton.add(radFromKelvin);
pnlToRadioButton.add(radToCelsius);
pnlToRadioButton.add(radToFahrenheit);
pnlToRadioButton.add(radToKelvin);
// add button to panel
pnlButton.add(btnConvert);
pnlButton.add(btnExit);
// add label and txt field to panel
pnlEnterTemp.add(lblFromTemp);
pnlEnterTemp.add(txtFromTemp);
pnlComparableTemp.add(lblToTemp);
txtToTemp.setEditable(false);
pnlComparableTemp.add(txtToTemp);
// add panels to the frame
add(pnlFrom, BorderLayout.NORTH);
add(pnlTo, BorderLayout.CENTER);
add(pnlButton, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
// private inner class to handle button event
private class MyButtonListener implements ActionListener {
// must override actionPerformed method
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnConvert) {
if (radFromCelsius.isSelected() && radToFahrenheit.isSelected()) {
int strInput = Integer.parseInt(txtFromTemp.getText());
int celsius = strInput * 9 / 5 + 32;
txtToTemp.setText(Integer.toString(celsius));
} else if (radFromCelsius.isSelected() && radToCelsius.isSelected() ||
radFromFahrenheit.isSelected() && radToFahrenheit.isSelected() ||
radFromKelvin.isSelected() && radToKelvin.isSelected()) {
txtToTemp.setText(txtFromTemp.getText());
} else if (radToCelsius.isSelected() && radFromFahrenheit.isSelected()) {
int strInput = Integer.parseInt(txtFromTemp.getText());
int fahrenheit = (strInput - 32) * 5 / 9;
txtToTemp.setText(Integer.toString(fahrenheit));
} else if (radFromKelvin.isSelected() && radToCelsius.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double celsius = strInput - 273.15;
txtToTemp.setText(Double.toString(celsius));
} else if (radFromKelvin.isSelected() && radToFahrenheit.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double fahrenheit = strInput - 459.67;
txtToTemp.setText(Double.toString(fahrenheit));
} else if (radFromCelsius.isSelected() && radToKelvin.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double celsius = strInput + 273.15;
txtToTemp.setText(Double.toString(celsius));
} else if (radFromFahrenheit.isSelected() && radToKelvin.isSelected()) {
double strInput = Integer.parseInt(txtFromTemp.getText());
double fahrenheit = strInput + 255.37;
txtToTemp.setText(Double.toString(fahrenheit));
}
} else if (e.getSource() == btnExit) {
System.exit(0);
}
}
}
public static void main(String[] args) {
new TemperatureConversion();
}
}
By the way #Hovercraft Full Of Eels, your solution is way more efficient and advanced than my level of thinking. I am newbie to programming in general so bear with me on my messy code and organization lol. I have barely dipped my feet into OOP. I do have a sense of how you used enum for TempScale and I thank you for your suggestion. I will keep these in my notes as references.
I'm currently making our project and I'm having problem reseting JLabel back to "0". Here's the code
main code snippet (check note 1 for frame disposal method used):
import javax.swing.*; //import library
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class draft_main //class name
{
public static void main(String[] args)
{ //method name
JFrame f0 = new JFrame("POS"); //frame
JPanel p0 = new JPanel(); //panel inside the frame
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
JPanel p5 = new JPanel();
JPanel p6 = new JPanel();
JPanel p7 = new JPanel();
JLabel l0 = new JLabel("Amount:"); //label inside the panel
JLabel l1 = new JLabel("0");
JLabel l2 = new JLabel("Menu Code: ");
JLabel l3 = new JLabel("--Menu--");
JTextField tf0 = new JTextField("", 12); //user input for menu code
JButton b0 = new JButton("Checkout"); //buttons
JButton b1 = new JButton("Cancel");
JButton b2 = new JButton("Exit");
JButton b4 = new JButton("Accept");
JButton b7 = new JButton("Remove");
JOptionPane jop = new JOptionPane(); //JOptionPane
JTextField tf1 = new JTextField("1. Hot Pockets Pizza", 20); //list of menu
JTextField tf2 = new JTextField("2. Burger with Fries", 20);
JTextField tf3 = new JTextField("3. Sticky Rice (Bico)", 20);
ArrayList<String> ar = new ArrayList<String>(); //list of array
try{
b4.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) //what the accept button does
{
String order = tf0.getText(), tots="", temp="";
int o = Integer.parseInt(order);
int tot=0;
switch(o) //menu choice
{
case 1 : temp = l1.getText(); tot=Integer.parseInt(temp); tot=tot+250; tots = Integer.toString(tot); l1.setText(tots); ar.add("Hot Pockets Pizza"); break;
case 2 : temp = l1.getText(); tot=Integer.parseInt(temp); tot=tot+65; tots = Integer.toString(tot); l1.setText(tots); ar.add("Burger with Fries"); break;
case 3 : temp = l1.getText(); tot=Integer.parseInt(temp); tot=tot+12; tots = Integer.toString(tot); l1.setText(tots); ar.add("Sticky Rice (Bico)"); break;
default : jop.showMessageDialog(null, "Menu code not listed in menu", "Error", jop.INFORMATION_MESSAGE); break;
}
}
});
b0.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) //what the checkout button does
{
JFrame f1 = new JFrame("Checkout");
JFrame f2 = new JFrame("Order");
JPanel p8 = new JPanel();
JPanel p9 = new JPanel();
JPanel p10 = new JPanel();
JPanel p11 = new JPanel();
JPanel p12 = new JPanel();
JPanel p13 = new JPanel();
JPanel p14 = new JPanel();
JLabel l5 = new JLabel("Order list");
JLabel l6 = new JLabel(/*convert ArrayList to String then put here*/);
JLabel l4 = new JLabel("Cash");
JTextField tf4 = new JTextField("", 14);
JButton b5 = new JButton("Accept");
JButton b6 = new JButton("Cancel");
JButton b7 = new JButton("Ok");
b5.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String cas = l1.getText(), in = tf4.getText();
int cash = Integer.parseInt(cas), inp = Integer.parseInt(in), cahs=0;
if(cash>inp)
{
jop.showMessageDialog(null, "Insufficient funds", "Lacking cash? Work for it.", jop.INFORMATION_MESSAGE);
}
else if(cash<inp)
{
cahs = inp - cash;
jop.showMessageDialog(null, "Change: " +cahs+". Thank you");
f1.dispatchEvent(new WindowEvent(f1, WindowEvent.WINDOW_CLOSING));
}
else if(cash==inp)
{
jop.showMessageDialog(null, "Thank you.", "Thank you.", jop.INFORMATION_MESSAGE);
f1.dispatchEvent(new WindowEvent(f1, WindowEvent.WINDOW_CLOSING));
}
}
});
b6.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
f1.dispatchEvent(new WindowEvent(f1, WindowEvent.WINDOW_CLOSING));
}
});
b7.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
f2.dispatchEvent(new WindowEvent(f2, WindowEvent.WINDOW_CLOSING));
}
});
p9.add(l0);
p9.add(l1);
p10.add(l4);
p10.add(tf4);
p11.add(b5);
p11.add(b6);
p12.add(l5);
p12.add(l6);
p13.add(b7);
p14.add(p12);
p14.add(p13);
p8.add(p10);
p8.add(p11);
p8.add(p9);
f1.add(p8);
f1.pack();
f1.setSize(240,170);
f1.setLocationRelativeTo(null);
f1.setResizable(false);
f1.setDefaultCloseOperation(f1.DISPOSE_ON_CLOSE);
f1.setVisible(true);
f2.add(p14);
f2.pack();
f2.setSize(270,100);
f2.setResizable(false);
f2.setLocationRelativeTo(null);
f2.setDefaultCloseOperation(f2.DISPOSE_ON_CLOSE);
f2.setVisible(true);
}
});
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
l1.setText("0");
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
f0.dispose();
}
});
}
catch(Exception e)
{
jop.showMessageDialog(null, "Error");
}
tf1.setEditable(false);
tf2.setEditable(false);
tf3.setEditable(false);
p4.add(tf1);
p5.add(tf2);
p6.add(tf3);
p7.add(l3);
p3.add(l2);
p3.add(tf0);
p3.add(b4);
p1.add(l0);
p1.add(l1);
p2.add(b0);
p2.add(b1);
p2.add(b2);
p0.add(p3);
p0.add(p1);
p0.add(p2);
p0.add(p7);
p0.add(p4);
p0.add(p5);
p0.add(p6);
f0.add(p0);
f0.pack();
f0.setSize(303,280);
f0.setLocationRelativeTo(null);
f0.setResizable(false);
f0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f0.setVisible(true);
}
}
what happens is when the main window opens it asks for which from the menu did a guy order then it displays the price. During checkout the user will be asked to input amount of cash given and gives change if there's any. After then the checkout frame is then "properly" disposed (so as I think so), exposing the main frame. However the JLabel does not seem to update when I place another order or clear the current order and it bothers me since the main frame is supposed to be fully interactive until the main frame is closed.
note #1: I have used different methods on how to dispose the 2nd and 3rd frame which pops up since I thought it may have been because of the dispose(); does not really destroys the frame but let's it run in the background.
note #2: yes the program is not finished yet, but those don't matter for now for those will just be some minor features of the application.
You've several problems with this code, but the major ones that I see (and I haven't gone through all of it yet, so there may be more)
First and foremost, those JFrame sub-windows shouldn't be JFrames at all, but rather should be modal JDialogs. The reason for this is this gives you complete control over program flow when these dialogs are used, since you'll then know that the main program flow will be put on hold while the modal dialog is visible, and then the flow will resume as soon as the dialog is no longer visible. This way you can query the state of the dialog after it has been dealt with, and then use this information to update your GUI.
Your amount is shown in the l1 variable, and this will never change unless you specifically call setText(...) on this variable. You don't seem to be doing it when the order has been processed. Again modal dialogs will help you with this.
Your variable naming is bad. Instead of using meaningless letters and numbers for names, use names that make sense and that make your code self-commenting. So for instance, instead of l1, use amountLabel or something similar.
Your code is one huge god class with everything stuffed into the static main method, and this makes for a debugging nightmare. Java is an object-oriented language, and if used properly OOP techniques can help you reduce program complexity making your code easier for yourself and for us to understand. Start OOP-ifying your program and you'll see immediate dividends.
And I found your bug -- you're adding the l1 JLabel to another container, and so it is effectively being removed from the original JFrame. If you minimize your original GUI and then restore it, you'll see the amount l1 JLabel disappear.
Here's some sample code not yet done, but to give you an idea about adding OOP to the program:
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class Draft2 extends JPanel {
private List<MyItem> selectedItems = new ArrayList<>();
private NumberFormat formatter = NumberFormat.getCurrencyInstance();
private double total;
private JLabel totalAmountLabel = new JLabel(formatter.format(total));
private DefaultComboBoxModel<MyItem> comboModel = new DefaultComboBoxModel<>();
private JComboBox<MyItem> menuCombo = new JComboBox<>(comboModel);
public Draft2() {
// monospaced to make names and price line up
menuCombo.setFont(new Font(Font.MONOSPACED, Font.BOLD, 12));
// fill the JComboBox with items
comboModel.addElement(new MyItem("Baseball", 21.5));
comboModel.addElement(new MyItem("Bat", 50.8));
comboModel.addElement(new MyItem("Football", 22.26));
// create a JPanel to hold selection components and add components
JPanel selectionPanel = new JPanel();
selectionPanel.add(new JLabel("Menu:"));
selectionPanel.add(menuCombo);
selectionPanel.add(new JButton(new AcceptAction("Accept", KeyEvent.VK_A)));
// create a JPanel to hold the total amount information
JPanel totalAmountPanel = new JPanel();
totalAmountPanel.add(new JLabel("Total Amount:"));
totalAmountPanel.add(totalAmountLabel);
// create a JPanel to hold buttons, uses grid layout with a single row
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
btnPanel.add(new JButton(new CheckOutAction("Check Out", KeyEvent.VK_C)));
btnPanel.add(new JButton(new CancelAction("Cancel", KeyEvent.VK_N)));
btnPanel.add(new JButton(new ExitAction("Exit", KeyEvent.VK_X)));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(selectionPanel);
add(Box.createVerticalStrut(5)); // so don't crowd things
add(totalAmountPanel);
add(Box.createVerticalStrut(5));
add(btnPanel);
}
public void setTotalAmount(double total) {
totalAmountLabel.setText(formatter.format(total));
}
private class AcceptAction extends AbstractAction {
public AcceptAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
MyItem myMenuItem = (MyItem) menuCombo.getSelectedItem();
if (myMenuItem == null) {
return; // nothing selected, get out
}
selectedItems.add(myMenuItem);
double total = 0.0;
for (MyItem myItem : selectedItems) {
total += myItem.getCost();
}
setTotalAmount(total);
}
}
private class CheckOutAction extends AbstractAction {
public CheckOutAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Finish....
// open JDialog or JOptionPane
}
}
private class CancelAction extends AbstractAction {
public CancelAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Finish...
}
}
private class ExitAction extends AbstractAction {
public ExitAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("My GUI Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Draft2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
class MyItem {
private NumberFormat formatter = NumberFormat.getCurrencyInstance();
private String name;
private double cost;
public MyItem(String name, double cost) {
this.name = name;
this.cost = cost;
}
public String getName() {
return name;
}
public double getCost() {
return cost;
}
#Override
public String toString() {
return String.format("%-10s %s", name, formatter.format(cost));
}
}
I have a class here that when I try to run gives me the error:
The type GUI must implement the inherited abstract method ActionListener.actionPerformed(actionEvent)
void is an invalid type for the variable actionPerformed
Syntax error on token "(", ; expected
Syntax error on token ")", ; expected
I don't understand what I'm doing wrong at this point. I have my GUI class implementing ActionListener. Any help would be greatly appreciated. Thanks!
GUI Class:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Enumeration;
public class GUI extends JFrame implements ActionListener {
// RadioButtons & ButtonGroup
private JRadioButton jrbStudent = new JRadioButton("Student");
private JRadioButton jrbGraduate = new JRadioButton("Graduate Student");
private ButtonGroup group = new ButtonGroup();
// JTextFields
private JTextField name = new JTextField(20);
private JTextField address = new JTextField(20);
private JTextField balance = new JTextField(20);
private JTextField major = new JTextField(20);
// Submit Button
private JButton jbtSubmit = new JButton("Submit");
// echoStudent output area
private JTextArea echoStudent = new JTextArea();
// Specific Buttons
private JButton printStudentNames = new JButton("Print Student's Names");
private JButton printGradStudentNames = new JButton(
"Print Graduate Student's Names");
private JButton calcBalance = new JButton(
"Calculate Average Balance of All Students");
private JButton compSciMajor = new JButton(
"Displays Computer Science Major Students");
// ScrollPane
private JScrollPane scrollPane = new JScrollPane(echoStudent);
private Manager m1 = new Manager();
public GUI () {
super("College Admission Information Interface");
// Creates panel P1 and adds the components
JPanel p1 = new JPanel(new GridLayout(9, 1, 10, 10));
p1.add(new JLabel("Name: "));
p1.add(name);
p1.add(new JLabel("Address: "));
p1.add(address);
p1.add(new JLabel("Balance: "));
p1.add(balance);
p1.add(new JLabel("Major: "));
p1.add(major);
p1.add(jrbStudent);
p1.add(jrbGraduate);
p1.add(new JLabel("Submit Button: "));
p1.add(jbtSubmit);
p1.add(printStudentNames);
p1.add(printGradStudentNames);
p1.add(calcBalance);
p1.add(compSciMajor);
p1.add(new JLabel("Submitted Text: "));
// Creates a radio-button group to group both buttons
group.add(jrbStudent);
group.add(jrbGraduate);
// Registers listeners
jrbStudent.addActionListener(this);
jrbGraduate.addActionListener(this);
jbtSubmit.addActionListener(this);
printStudentNames.addActionListener(this);
printGradStudentNames.addActionListener(this);
calcBalance.addActionListener(this);
compSciMajor.addActionListener(this);
// GUI settings
setTitle("Information Interface");
setSize(1200, 900);
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
// Adds the panel and text area to the frame
add(p1);
p1.add(echoStudent);
echoStudent.setEditable(false);
public void actionPerformed(ActionEvent event) {
if(event.getSource() == jbtSubmit) {
if(jrbStudent.isSelected()) {
Student s1 = Manager.instance().createStudent(name.getText(),
address.getText(), major.getText(),
Double.parseDouble(balance.getText()));
echoStudent.append("\n\nCreated Student: " + s1.toString());
}
else if(jrbGraduate.isSelected()) {
GradStudent g1 = Manager.instance().createGradStudent(name.getText(),
address.getText(), major.getText(),
Double.parseDouble(balance.getText()));
echoStudent.append("\n\nCreated Graduate Student: " + g1.toString());
}
}
else if(event.getSource() == printStudentNames) {
echoStudent.append(Manager.instance().listStudents());
}
else if(event.getSource() == printGradStudentNames) {
echoStudent.append(Manager.instance().listGrads());
}
else if(event.getSource() == calcBalance) {
echoStudent.append(Manager.instance().aveBalance());
}
else if(event.getSource() == compSciMajor) {
echoStudent.append(Manager.instance().listCsci());
}
}
}
public static void main(String[] args) {
new GUI();
}
}
You need to move your actionPerformed declaration outside of your constructor.
Currently you have this:
public class GUI extends JFrame implements ActionListener {
...
public GUI() {
...
public void actionPerformed(ActionEvent event) {
...
}
}
}
It needs to be like:
public class GUI extends JFrame implements ActionListener {
...
public GUI() {
...
}
public void actionPerformed(ActionEvent event) {
...
}
}
I have not tested your code but that is the first obvious problem.
I keep receiving the error:
Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Container.java:483)
at java.awt.Container.addImpl(Container.java:1084)
at java.awt.Container.add(Container.java:966)
at Lab2.EmployeeGUI.main(EmployeeGUI.java:28)
Can someone please help me and tell me what I'm doing wrong?
I am beginner programmer.
package Lab2;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
*
* #author Jim Doyle
*/
public class EmployeeGUI extends JFrame implements ActionListener {
JTextField fName, mName, lName, phone, sal, years;
JComboBox boxTitle, boxDept;
DefaultListModel lstdefault;
JList project;
DbWork dbw = new DbWork("Lab2");
DbWork Title = new DbWork("Lab2");
DbWork Dept = new DbWork("Lab2");
DbWork Prjs = new DbWork("Lab2");
DbWork PrjList = new DbWork("Lab2");
public static void main(String[] args) {
EmployeeGUI app = new EmployeeGUI();
JFrame frame = new JFrame("Employee Interface by Jim Doyle");
frame.getContentPane().add(app, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public EmployeeGUI() {
JPanel labels = new JPanel();
labels.setLayout(new GridLayout(8,1));
labels.add(new JLabel("First Name"));
labels.add(new JLabel("MI"));
labels.add(new JLabel("Last Name"));
labels.add(new JLabel("Title"));
labels.add(new JLabel("Telephone"));
labels.add(new JLabel("Salary"));
labels.add(new JLabel("Department"));
labels.add(new JLabel("Years in Service"));
getContentPane().add(labels, BorderLayout.WEST);
JPanel fields = new JPanel();
fields.setLayout(new GridLayout(8,1));
fName = new JTextField(15);
mName = new JTextField(15);
lName = new JTextField(15);
phone = new JTextField(15);
sal = new JTextField(15);
years = new JTextField(15);
boxTitle = new JComboBox();
boxDept = new JComboBox();
fields.add(fName);
fields.add(mName);
fields.add(lName);
fields.add(boxTitle);
fields.add(phone);
fields.add(sal);
fields.add(years);
getContentPane().add(fields, BorderLayout.CENTER);
JPanel prjinfo = new JPanel();
prjinfo.setLayout(new GridLayout(1,2));
prjinfo.add(new JLabel("Project Description"));
project = new JList();
lstdefault = new DefaultListModel();
// add items to title combo box
while(Title.nextRecord()) {
String txtTit = Title.getField(1);
if(txtTit!=null) {
boxTitle.addItem(Title.getField(1));
}
}
// add items to department combo box
while(Dept.nextRecord()) {
String txtDept = Dept.getField(2);
if(txtDept!=null) {
boxDept.addItem(Dept.getField(2));
}
}
while(PrjList.nextRecord()) {
lstdefault.addElement(PrjList.getField(1));
}
project = new JList(lstdefault);
project.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
prjinfo.add(project);
getContentPane().add(prjinfo, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
String button = e.getActionCommand();
if(button == "First") {
if(dbw.firstRecord()) {
Execute();
}
}
else if(button == "Next") {
if(dbw.nextRecord()) {
Execute();
}
}
else if(button == "Save") {
String sql = "UPDATE FirstName, MiddleName, LastName, WorkPhone, Salary, YearsInService FROM Employee;";
dbw.processQuery(sql);
}
}
private void action() {
boxTitle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox b = (JComboBox)e.getSource();
String ntitle = (String)b.getSelectedItem();
updateTitle(ntitle);
}
});
}
private void Execute() {
fName.setText(dbw.getField(1));
mName.setText(dbw.getField(2));
lName.setText(dbw.getField(3));
phone.setText(dbw.getField(5));
sal.setText(dbw.getField(6));
years.setText(dbw.getField(8));
String ftext = dbw.getField(4);
int dx = TitleList(ftext);
boxTitle.setSelectedIndex(dx);
String dtext = dbw.getField(7);
int dx2 = DeptList(dtext);
boxDept.setSelectedIndex(dx2);
action();
}
int TitleList(String title) {
int dx = 0;
for(int z=0; z<boxTitle.getItemCount(); z++) {
if(title.equals(boxTitle.getItemAt(z))) {
dx = z;
}
}
return dx;
}
int DeptList(String dept) {
int dx = 0;
for(int z=0; z<boxDept.getItemCount(); z++) {
if(dept.equals(boxDept.getItemAt(z))) {
dx = z;
}
}
return dx;
}
private void updateTitle(String title) {
}
}
EmployeeGUI extends from JFrame, but in your main method, you are creating a new JFrame and are trying to add an instance of EmployeeGUI to it.
Change EmployeeGUI so it extends from JPanel instead
Here:
frame.getContentPane().add(app, BorderLayout.CENTER);
you're trying to add a JFrame to a JFrame which makes no sense.
Why not instead just try to display app rather than add it to a JFrame. Or even better, not have EmployeeGUI extend JFrame.
You can't add a JFrame to another JFrame.
But you can add a JPanel to a JFrame, in other words change EmployeeGUI to make it extends JPanel.