How to Pass String from one java file to another java file - java

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.

Related

JCheckBox's not showing up when I run my program

I'm new to Java and following an online tutorial to learn swing.
I have just gotten to a part where we are adding in JCheckBox and I can't figure out why they are not showing up when I run the program. I'm running it on Eclipse on a Mac if that makes a difference.
I've tried re-writing everything but that didn't work. I know that they are added but they are just not showing up. The JRadioButtons are showing up just fine.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Userimputcomplex
{
public static void main(String[] args)
{
RadioDemo r = new RadioDemo();
}
}
class RadioDemo extends JFrame
{
JTextField t1; //Input Text
JButton b; //Button
JRadioButton r1,r2; //Check buttons
JLabel l; //Text
JCheckBox c1,c2; //Multiple check buttons
public RadioDemo()
{
t1 = new JTextField(15);
b = new JButton("Ok");
r1 = new JRadioButton("Male");
r2 = new JRadioButton("Female");
l = new JLabel("Greetings");
c1 = new JCheckBox("Dancing");
c2 = new JCheckBox("Singing");
ButtonGroup bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
add(t1);
add(r1);
add(r2);
add(c1);
add(c2);
add(b);
add(l);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String name = t1.getText();
if(r1.isSelected())
{
name = "Mr." + name;
}
else
{
name = "Ms." + name;
}
if(c1.isSelected())
{
name = name + " Dancer";
}
if(c2.isSelected())
{
name = name + " Singer";
}
l.setText(name);
}
});
setLayout(new FlowLayout());
setVisible(true);
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

How do I put label under radio button within a panel with Java Swing/awt

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.

Java - Broken JLabel after proper disposal of different JFrame

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));
}
}

Replacing contents of Jframe with new items returns blank Jframe

I have a start up window that creates a jframe with a drop down box, two text boxes and an OK button. After choosing the drop down menu item and then typing in the two text boxes, another function is called that will replace the contents of the JFrame with other content.
One of the drop down choices is to deposit:
public void deposit(String customerID, String customerPIN) {
Customer customer = validate_info(customerID, customerPIN);
if (!found){
if (pin == null) {
jf.notInDatabase();
} else {
jf.invalidAccount(); // if the customer has not been found but the pin has been set that means the pin was invalid
}
} else {
if (customer != null) {
String result = customer.returnInfo();
jf.depositScreen(result);
After looking around on SO for guidance, this is what I have so far:
public void depositScreen(String phrase) {
getContentPane().removeAll();
JLabel customerInfo = new JLabel(phrase);
customerInfo.setFont(new Font("Futura", Font.PLAIN, 12));
getContentPane().add(customerInfo);
JTextField depositAmount = new JTextField("Please enter the amount you would like to deposit in 00.00 format");
depositAmount.setFont(new Font("Futura", Font.PLAIN, 12));
getContentPane().add(depositAmount);
repaint();
validate();
setVisible(true);
}
So far it's turning up a blank gray box without the labels in it. Where am I going wrong?
Here is an example doing what you want. Notice the order of the validates and invalidates.
import javax.swing.*;
import java.awt.*;
public class SwingSwap{
public static void main(String[] args){
EventQueue.invokeLater(()->buildGui());
}
public static void buildGui(){
JFrame frame = new JFrame("swapping");
final JButton a = new JButton("->B");
final JLabel aLabel = new JLabel("A");
final JButton b = new JButton("->A");
final JLabel bLabel = new JLabel("B");
a.addActionListener(evt->{
EventQueue.invokeLater(()->{
Container cont = frame.getContentPane();
cont.removeAll();
cont.add(b);
cont.add(bLabel);
cont.invalidate();
frame.validate();
frame.repaint();
});
});
b.addActionListener(evt->{
EventQueue.invokeLater(()->{
Container cont = frame.getContentPane();
cont.removeAll();
cont.add(a);
cont.add(aLabel);
cont.invalidate();
frame.validate();
frame.repaint();
});
} );
Container cont = frame.getContentPane();
cont.setLayout(new BoxLayout(cont, BoxLayout.PAGE_AXIS));
cont.add(a);
cont.add(aLabel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

Why do I get this error: java.lang.OutOfMemoryError: can't create offscreen surface

I think my error is my showGreeting() method. Specifically in the try. When the user presses the Get Greeting button I want it show a dialog box what says "Greetings, FirstName + MI + LastName" And when the user leaves a field blank an I created comes error comes up, that works fine, but I do not understand why my normal Greeting does not work.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GreetingApp extends JFrame {
private static final long serialVersionUID = 1L;
private final JTextField firstNameField,middleNameField,lastNameField;
private final JButton greetingButton;
public GreetingApp() {
super("Greetings");
this.firstNameField = new JTextField(8);
this.middleNameField = new JTextField(8);
this.lastNameField = new JTextField(8);
this.greetingButton = new JButton("Get Greeting");
greetingButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent ae){
showGreeting();
}
});
final Container mainPanel = getContentPane();
mainPanel.setLayout(new BorderLayout());
final JPanel inputPanel = new JPanel();
final JPanel buttonPanel = new JPanel();
inputPanel.setLayout(new GridLayout(3,3,2,2));
buttonPanel.setLayout(new BorderLayout());
JSeparator sep = new JSeparator();
inputPanel.add(new JLabel("First Name: "),JLabel.LEFT_ALIGNMENT);
inputPanel.add(firstNameField);
inputPanel.add(new JLabel("MI: "),JLabel.LEFT_ALIGNMENT);
inputPanel.add(middleNameField);
inputPanel.add(new JLabel("Last Name: "),JLabel.LEFT_ALIGNMENT);
inputPanel.add(lastNameField);
mainPanel.add(inputPanel,BorderLayout.PAGE_START);
buttonPanel.add(sep,BorderLayout.PAGE_START);
buttonPanel.add(greetingButton);
mainPanel.add(buttonPanel,BorderLayout.PAGE_END);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private String getFullName() throws IllegalStateException{
if(firstNameField.getText().trim().length() == 0){
throw new IllegalArgumentException("First name cannot be blank");
}
if(middleNameField.getText().trim().length() == 0){
throw new IllegalArgumentException("Middle name cannot be blank");
}
if(lastNameField.getText().trim().length() == 0){
throw new IllegalArgumentException("Last name cannot be blank");
}
return "Greetings, "+this.firstNameField+" "+ this.middleNameField +". "+this.lastNameField+"!";
}
private void showGreeting(){
try{
String message = getFullName();
JOptionPane.showMessageDialog(this, message, "Greetings",JOptionPane.PLAIN_MESSAGE);
}catch(final IllegalArgumentException iae){
JOptionPane.showMessageDialog(this,
iae.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
GreetingApp g = new GreetingApp();
}
}
Edit:
Never mind guys got it I had to add a .getText()
return "Greetings, "+this.firstNameField+" "+ this.middleNameField +". "+this.lastNameField+"!";
after each of fields to actually get the Text from them
Never mind guys got it I had to add a .getText() return "Greetings, "+this.firstNameField+" "+ this.middleNameField +". "+this.lastNameField+"!"; after each of fields to actually get the Text from them

Categories