JAVA Swing Components won't show up - java

For some reason some of the Swing components don't show up when I run the program and I can't figure out why. Only the multiply label, multiply button, total label, and stop button show up. The rest don't work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BabyCalculatorFinal extends JFrame{
private JLabel AdditionLabel;
private JTextField AdditionField;
private JButton AdditionButton;
private JPanel Multiplication;
private JLabel MultiplicationLabel;
private JTextField MultiplicationField;
private JButton MultiplicationButton;
private JPanel Total;
private JLabel TotalLabel;
private JTextField TotalField;
JButton StopButton;
public BabyCalculatorFinal(){
setDefaultCloseOperation(EXIT_ON_CLOSE);// 1st thing to do
setName("Baby Calculator Final"); // 2nd thing to do
setLayout(new GridLayout(3,0)); //sets grid layout for the entire thing with 3 rows
// Create Action Event
BabyCalculatorListener Listener = new BabyCalculatorListener();
//Addition
//Addition Set Layout
JPanel Addition = new JPanel(new BorderLayout());
//Addition Features
AdditionLabel = new JLabel("Amount to add"); //Create label
AdditionField = new JTextField(10);
AdditionButton = new JButton("Add");
//Organize Addition Panel
Addition.add(AdditionLabel, BorderLayout.WEST);//IMPORTANT FORMAT
Addition.add(AdditionLabel, BorderLayout.CENTER);
Addition.add(AdditionButton, BorderLayout.EAST);
//Add addition Panel to Frame
add(Addition);
AdditionButton.addActionListener(Listener);
//Multiplictation
//Multiplication Set Layout
Multiplication = new JPanel();
Multiplication.setLayout(new BorderLayout());//Trying a different way of setting the layout
//Multiplication Features
MultiplicationLabel = new JLabel("Amount to Multiply"); //Create label
MultiplicationField = new JTextField(10);
MultiplicationButton = new JButton("Multiply");
//Organize Multiplication Panel
Addition.add(MultiplicationLabel, BorderLayout.WEST);
Addition.add(MultiplicationLabel, BorderLayout.CENTER);
Addition.add(MultiplicationButton, BorderLayout.EAST);
//Add Multiplication Panel to Frame
add(Multiplication);
MultiplicationButton.addActionListener(Listener);
//Total
Total = new JPanel(new FlowLayout(10));
TotalLabel = new JLabel("Total");
TotalField = new JTextField();
TotalField.setText("0.0");
TotalField.setVisible(false);
StopButton = new JButton("Stop");
Total.add(TotalLabel);
Total.add(TotalField);
Total.add(StopButton);
//Add Total Panel to Frame
add(Total);
pack();
setVisible(true);
}
public static void main(String[] args){
JFrame myFrame = new BabyCalculatorFinal();
}
public class BabyCalculatorListener implements ActionListener{
public void actionPerformed(ActionEvent e){
String totalText = TotalField.getText();
double total = Double.parseDouble(totalText);
if (e.getSource() == AdditionButton){
String additionText = AdditionField.getText();
double addition = Double.parseDouble(additionText);
total += addition;
}
else{
String multiplicationText = MultiplicationField.getText();
double multiplication = Double.parseDouble(multiplicationText);
total += multiplication;
}
TotalField.setText(total + "");
}
}
}

Your code is full of typos (?), for example you're adding AdditionLabel twice to the JPanel instead of adding AdditionLabel and AdditionField. And you're not using the Multiplication panel after creating it but instead overriding the contents of the Addition panel. The corrected snippet that adds the components should be (I changed the variable names to conform to Java conventions):
additionLabel = new JLabel("Amount to add"); // Create label
additionField = new JTextField(10);
additionButton = new JButton("Add");
// Organize addition Panel
addition.add(additionLabel, BorderLayout.WEST);// IMPORTANT FORMAT
addition.add(additionField, BorderLayout.CENTER); // instead of additionLabel
addition.add(AdditionButton, BorderLayout.EAST);
// Add addition Panel to Frame
add(addition);
AdditionButton.addActionListener(Listener);
// Multiplictation
// Multiplication Set Layout
multiplication = new JPanel();
multiplication.setLayout(new BorderLayout());// Trying a different way
// of setting the layout
// Multiplication Features
multiplicationLabel = new JLabel("Amount to Multiply"); // Create label
multiplicationField = new JTextField(10);
multiplicationButton = new JButton("Multiply");
// Organize Multiplication Panel
multiplication.add(multiplicationLabel, BorderLayout.WEST); // instead of Addition
multiplication.add(multiplicationField, BorderLayout.CENTER);
multiplication.add(multiplicationButton, BorderLayout.EAST);

Related

Java Swing: Action Listener Not Working Correctly

For some reason my action listener isn't working correctly. When I add the first number to it it works fine, but when I continue to add numbers it stops working correctly. Any ideas on why this happens would be appreciated!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BabyCalculatorFinal extends JFrame{
private JLabel additionLabel;
private JTextField additionField;
private JButton additionButton;
private JPanel multiplication;
private JLabel multiplicationLabel;
private JTextField multiplicationField;
private JButton multiplicationButton;
private JPanel total;
private JLabel totalLabel;
private JTextField totalField;
private JButton stopButton;
public BabyCalculatorFinal(){
setDefaultCloseOperation(EXIT_ON_CLOSE);// 1st thing to do
setName("Baby Calculator Final"); // 2nd thing to do
setLayout(new GridLayout(3,0)); //sets grid layout for the entire thing with 3 rows
// Create Action Event
BabyCalculatorListener listener = new BabyCalculatorListener();
//Addition
//Addition Set Layout
JPanel addition = new JPanel(new BorderLayout());
//Addition Features
additionLabel = new JLabel("Amount to add"); //Create label
additionField = new JTextField(10);
additionButton = new JButton("Add");
//Organize Addition Panel
addition.add(additionLabel, BorderLayout.WEST);//IMPORTANT FORMAT
addition.add(additionField, BorderLayout.CENTER);
addition.add(additionButton, BorderLayout.EAST);
//Add addition Panel to Frame
add(addition);
additionButton.addActionListener(listener);
//Multiplictation
//Multiplication Set Layout
multiplication = new JPanel();
multiplication.setLayout(new BorderLayout());//Trying a different way of setting the layout
//Multiplication Features
multiplicationLabel = new JLabel("Amount to Multiply"); //Create label
multiplicationField = new JTextField(10);
multiplicationButton = new JButton("Multiply");
//Organize Multiplication Panel
multiplication.add(multiplicationLabel, BorderLayout.WEST);
multiplication.add(multiplicationField, BorderLayout.CENTER);
multiplication.add(multiplicationButton, BorderLayout.EAST);
//Add Multiplication Panel to Frame
add(multiplication);
multiplicationButton.addActionListener(listener);
//Total
total = new JPanel(new FlowLayout());
totalLabel = new JLabel("Total");
totalField = new JTextField();
totalField.setText("0.0");
totalField.setEditable(false);
stopButton = new JButton("Stop");
total.add(totalLabel);
total.add(totalField);
total.add(stopButton);
//Add Total Panel to Frame
add(total);
pack();
setVisible(true);
}
public static void main(String[] args){
JFrame myFrame = new BabyCalculatorFinal();
}
public class BabyCalculatorListener implements ActionListener{
public void actionPerformed(ActionEvent e){
String totalText = totalField.getText();
double totalAmount = Double.parseDouble(totalText);
if (e.getSource() == additionButton){
String additionText = additionField.getText();
double addAmount = Double.parseDouble(additionText);
totalAmount += addAmount;
}
else{
String multiplicationText = multiplicationField.getText();
double multiplicationAmount = Double.parseDouble(multiplicationText);
totalAmount *= multiplicationAmount;
}
totalField.setText(totalAmount + "");
}
}
}
Your code works fine for me. It could be a repaint issue that you're experiencing. Try resizing the frame when you stop seeing the "total" change. If that works, you could try a repaint() after setting the totalField text.

Formatting of components in Swing

I have just started programming in Swing. I am making a Fitness application using Swing. I have 2 questions:
Whenever I click 'Calculate Scales' it should display the results only once, but it is displaying as many times as I click. How can I solve this?
How can I set limit of JTextField up to 3 digits in my code?
Here is my code. Correct me if I am going wrong somewhere. Suggest me where I can make improvements.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;//since obsolete
class H1 extends JFrame implements ActionListener
{
JLabel l1,l2,l3,l4,l5;
JTextField t1,t2,t3;
JRadioButton r1,r2;
ButtonGroup bg1;
JLabel bmr;
JLabel bmi;
int click=0;
JButton b1,b2;Container c1;
public static void main(String args[])
{
H1 j1 =new H1();
j1.setTitle("Personal Scales ");
j1.setSize(1000,1000);
j1.setVisible(true);
j1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j1.pack();
}
H1()
{
c1=this.getContentPane();
setLayout(new BoxLayout(c1,BoxLayout.Y_AXIS));
JPanel j1 = new JPanel();
j1.setLayout(new FlowLayout());
t1 = new JTextField(10);
l1=new JLabel("Height");
j1.add(l1);
j1.add(t1);
c1.add(j1);
JPanel j2 = new JPanel();
j2.setLayout(new FlowLayout());
l2=new JLabel("Weight");
t2 = new JTextField(10);
j2.add(l2);
j2.add(t2);
c1.add(j2);
JPanel j3 = new JPanel();
j3.setLayout(new FlowLayout());
l3=new JLabel("Age");
t3 = new JTextField(10);
j3.add(l3);
j3.add(t3);
c1.add(j3);
JPanel j4 = new JPanel();
j4.setLayout(new FlowLayout());
l4=new JLabel("Sex");
bg1=new ButtonGroup();
r1=new JRadioButton("M");
r2=new JRadioButton("F");
bg1.add(r1);//button grouping is done to avoid multiple selection of radio button
bg1.add(r2);
j4.add(l4);
j4.add(r1);
j4.add(r2);
c1.add(j4);
JPanel j5 = new JPanel();
j5.setLayout(new FlowLayout());
b1=new JButton("Calculate Scales");//creating instance of JButton
j5.add(b1);
c1.add(j5);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
click +=1;
//JLabel bmr;
//JLabel bmi;
long ht=Long.parseLong(t1.getText());
long wt=Long.parseLong(t2.getText());
long age=Long.parseLong(t3.getText());
//JPanel j6 = new JPanel();
//j6.setLayout(new FlowLayout());
double bmi1 = wt/Math.pow((ht * 0.01),2);
String bmi2 = Double.toString(bmi1);//since double cant be added to container
bmi=new JLabel("BMI "+bmi2);
//c1.add(j6);
// JPanel j7 = new JPanel();
//j7.setLayout(new FlowLayout());
double bmr1;String bmr2;
if(r1.isSelected())
bmr1 = 66.47 +(13.75 * wt) + (5.003 * ht) - (6.775 * age);
else
bmr1 = 655.1 +(9.563 * wt) + (1.85 * ht) - (4.676 * age);
bmr2=Double.toString(bmr1);
bmr=new JLabel("BMR "+bmr2);
if(click>1)
{
c1.remove(bmi);
c1.remove(bmr);
}
/*j6.add(bmi);
j6.add(bmr);*/
c1.add(bmi);
c1.add(bmr);
}
}
I'm also newer to java, so correct me if I'm wrong and cause of that, I can't write you a comment and have to write an answer ;)
As I can see it, you make a new JLabel each time you click the Button.
Try to use eg. bmi.setText("BMI here" + bmi2); for your result description through setText() you only change the Text in this label. And also as variable declaration use JLabel bmi = null;
Maybe you also can add a JPanel to display your result to get the JLabel a fixed position and initializing it.
I hope that I can help you ;)
Zorian

JButton opening new JFrame?

I have been looking for multiple ways to open a JFrame with a button. One of the ways I found was to establish the JFrame with a method and call upon that method with the button. That however does not seem to be working with my program. Could someone please tell me what I am doing wrong? I am pretty new to Java and am trying to learn on my own and seem to be doing a pretty terrible job of it. I am trying to create a Catalog and at the bottom of it have a button called "Make a New Purchase" which will open a new JFrame that will allow someone to enter their information. Much of the code in the program is unnecessary and I will edit it later, such as the multiple JPanels. All I need to do is get the new JFrame to come up with the button click. The showNewFrame() method is what I am trying to have activated by the button press.
public class Catalog extends JFrame
{
//Construct a panel for each row
JPanel firstRow = new JPanel();
JPanel secondRow = new JPanel();
JPanel thirdRow = new JPanel();
JPanel fourthRow = new JPanel();
JPanel fifthRow = new JPanel();
JPanel sixthRow = new JPanel();
JPanel seventhRow = new JPanel();
JPanel eighthRow = new JPanel();
JPanel ninthRow = new JPanel();
JPanel tenthRow = new JPanel();
JPanel eleventhRow = new JPanel();
JPanel twelvethRow = new JPanel();
JPanel thirteenthRow = new JPanel();
JPanel fourteenthRow = new JPanel();
JPanel fifteenthRow = new JPanel();
JPanel sixteenthRow = new JPanel();
JPanel seventeenthRow = new JPanel();
JPanel eighteenthRow = new JPanel();
JPanel nineteenthRow = new JPanel();
JPanel twentiethRow = new JPanel();
JPanel twentyfirstRow = new JPanel();
JPanel twentysecondRow = new JPanel();
JPanel twentythirdRow = new JPanel();
JPanel twentyfourthRow = new JPanel();
//Construct a panel for the fields and buttons
JPanel fieldPanel = new JPanel();
JPanel buttonPanel = new JPanel();
//Construct labels and text boxes
JLabel coatOneLabel = new JLabel("Coat One");
ImageIcon pictureOne = new ImageIcon("C:\\Users\\p6\\Desktop\\prodImage.jpeg");
JLabel picLabelOne = new JLabel(pictureOne);
JLabel priceOneLabel = new JLabel("Price:");
JLabel coatTwoLabel = new JLabel("Coat Two");
ImageIcon pictureTwo = new ImageIcon("snow.png");
JLabel picLabelTwo = new JLabel(pictureTwo);
JLabel priceTwoLabel = new JLabel("Price:");
JLabel coatThreeLabel = new JLabel("Coat Three");
ImageIcon pictureThree = new ImageIcon("snow.png");
JLabel picLabelThree = new JLabel(pictureThree);
JLabel priceThreeLabel = new JLabel("Price:");
JLabel coatFourLabel = new JLabel("Coat Four");
ImageIcon pictureFour = new ImageIcon("snow.png");
JLabel picLabelFour = new JLabel(pictureFour);
JLabel priceFourLabel = new JLabel("Price:");
JLabel coatFiveLabel = new JLabel("Coat Five");
ImageIcon pictureFive = new ImageIcon("snow.png");
JLabel picLabelFive = new JLabel(pictureFive);
JLabel priceFiveLabel = new JLabel("Price:");
JLabel coatSixLabel = new JLabel("Coat Six");
ImageIcon pictureSix = new ImageIcon("snow.png");
JLabel picLabelSix = new JLabel(pictureSix);
JLabel priceSixLabel = new JLabel("Price:");
JLabel coatSevenLabel = new JLabel("Coat Seven");
ImageIcon pictureSeven = new ImageIcon("snow.png");
JLabel picLabelSeven = new JLabel(pictureSeven);
JLabel priceSevenLabel = new JLabel("Price:");
JLabel coatEightLabel = new JLabel("Coat Eight");
ImageIcon pictureEight = new ImageIcon("snow.png");
JLabel picLabelEight = new JLabel(pictureEight);
JLabel priceEightLabel = new JLabel("Price:");
//Construct buttons
JButton submitButton = new JButton("Make A Purchase");
JButton exitButton = new JButton("Not Right Now");
public static void main(String[] args)
{
//set the look and feel of the interface
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"The UIManager could not set the Look and Feel for this application.","Error",JOptionPane.INFORMATION_MESSAGE);
}
Catalog f = new Catalog();
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setSize(800,600);
f.setTitle("Coat Catalog");
f.setResizable(false);
f.setLocation(200,200);
f.setVisible(true);
}
public Catalog()
{
Container c = getContentPane();
c.setLayout((new BorderLayout()));
fieldPanel.setLayout(new GridLayout(20,10));
FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT,5,3);
firstRow.setLayout(rowSetup);
secondRow.setLayout(rowSetup);
thirdRow.setLayout(rowSetup);
fourthRow.setLayout(rowSetup);
fifthRow.setLayout(rowSetup);
sixthRow.setLayout(rowSetup);
seventhRow.setLayout(rowSetup);
eighthRow.setLayout(rowSetup);
ninthRow.setLayout(rowSetup);
tenthRow.setLayout(rowSetup);
eleventhRow.setLayout(rowSetup);
twelvethRow.setLayout(rowSetup);
thirteenthRow.setLayout(rowSetup);
fourteenthRow.setLayout(rowSetup);
fifteenthRow.setLayout(rowSetup);
sixteenthRow.setLayout(rowSetup);
seventeenthRow.setLayout(rowSetup);
eighteenthRow.setLayout(rowSetup);
nineteenthRow.setLayout(rowSetup);
twentiethRow.setLayout(rowSetup);
twentyfirstRow.setLayout(rowSetup);
twentysecondRow.setLayout(rowSetup);
twentythirdRow.setLayout(rowSetup);
twentyfourthRow.setLayout(rowSetup);
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
//Add fields to rows
firstRow.add(coatOneLabel);
firstRow.add(coatTwoLabel);
secondRow.add(picLabelOne);
secondRow.add(picLabelTwo);
thirdRow.add(priceOneLabel);
thirdRow.add(priceTwoLabel);
fourthRow.add(coatThreeLabel);
fourthRow.add(coatFourLabel);
fifthRow.add(picLabelThree);
fifthRow.add(picLabelFour);
sixthRow.add(priceThreeLabel);
sixthRow.add(priceFourLabel);
seventhRow.add(coatFiveLabel);
seventhRow.add(coatSixLabel);
eighthRow.add(picLabelFive);
eighthRow.add(picLabelSix);
ninthRow.add(priceFiveLabel);
ninthRow.add(priceSixLabel);
tenthRow.add(coatSevenLabel);
tenthRow.add(coatEightLabel);
eleventhRow.add(picLabelSeven);
eleventhRow.add(picLabelEight);
twelvethRow.add(priceSevenLabel);
twelvethRow.add(priceEightLabel);
//Add rows to panel
fieldPanel.add(firstRow);
fieldPanel.add(secondRow);
fieldPanel.add(thirdRow);
fieldPanel.add(fourthRow);
fieldPanel.add(fifthRow);
fieldPanel.add(sixthRow);
fieldPanel.add(seventhRow);
fieldPanel.add(eighthRow);
fieldPanel.add(ninthRow);
fieldPanel.add(tenthRow);
fieldPanel.add(eleventhRow);
fieldPanel.add(twelvethRow);
fieldPanel.add(thirteenthRow);
fieldPanel.add(fourteenthRow);
fieldPanel.add(fifteenthRow);
fieldPanel.add(sixteenthRow);
fieldPanel.add(seventeenthRow);
fieldPanel.add(eighteenthRow);
fieldPanel.add(nineteenthRow);
fieldPanel.add(twentiethRow);
fieldPanel.add(twentyfirstRow);
fieldPanel.add(twentysecondRow);
fieldPanel.add(twentythirdRow);
fieldPanel.add(twentyfourthRow);
//Add button to panel
buttonPanel.add(submitButton);
buttonPanel.add(exitButton);
//Add panels to frame
c.add(fieldPanel, BorderLayout.CENTER);
c.add(buttonPanel, BorderLayout.SOUTH);
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent h)
{
if (h.getSource() == exitButton)
{
System.exit(0);
}
}
});
//Add functionality to buttons
submitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent d)
{
if (d.getSource() == submitButton)
{
showNewFrame();
}
}
});
}
private void showNewFrame()
{
JFrame BillPayer = new JFrame("BillPayer");
BillPayer.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
BillPayer.pack();
BillPayer.setVisible(true);
class BillPayer extends JFrame implements ActionListener
{
//Declare output stream
DataOutputStream output;
//Construct a panel for each row
JPanel firstRow = new JPanel();
JPanel secondRow = new JPanel();
JPanel thirdRow = new JPanel();
JPanel fourthRow = new JPanel();
JPanel fifthRow = new JPanel();
JPanel sixthRow = new JPanel();
JPanel seventhRow = new JPanel();
JPanel eighthRow = new JPanel();
//Construct a panel for the fields and buttons
JPanel fieldPanel = new JPanel();
JPanel buttonPanel = new JPanel();
//Construct labels and text boxes
JLabel acctNumLabel = new JLabel("Account Number: ");
JTextField acctNum = new JTextField(15);
JLabel pmtLabel = new JLabel("Payment Amount:");
JTextField pmt = new JTextField(10);
JLabel firstNameLabel = new JLabel("First Name: ");
JTextField firstName = new JTextField(10);
JLabel lastNameLabel = new JLabel("Last Name:");
JTextField lastName = new JTextField(20);
JLabel addressLabel = new JLabel("Address:");
JTextField address = new JTextField(35);
JLabel cityLabel = new JLabel("City: ");
JTextField city = new JTextField(10);
JLabel stateLabel = new JLabel("State:");
JTextField state = new JTextField(2);
JLabel zipLabel = new JLabel("Zip:");
JTextField zip = new JTextField(9);
//Construct button
JButton submitButton = new JButton("Submit");
public void main(String[] args)
{
//set the look and feel of the interface
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"The UIManager could not set the Look and Feel for this application.","Error",JOptionPane.INFORMATION_MESSAGE);
}
BillPayer f = new BillPayer();
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setSize(450,300);
f.setTitle("Crandall Power and Light Customer Payments");
f.setResizable(false);
f.setLocation(200,200);
f.setVisible(true);
}
public BillPayer()
{
Container c = getContentPane();
c.setLayout((new BorderLayout()));
fieldPanel.setLayout(new GridLayout(8,1));
FlowLayout rowSetup = new FlowLayout(FlowLayout.LEFT,5,3);
firstRow.setLayout(rowSetup);
secondRow.setLayout(rowSetup);
thirdRow.setLayout(rowSetup);
fourthRow.setLayout(rowSetup);
fifthRow.setLayout(rowSetup);
sixthRow.setLayout(rowSetup);
seventhRow.setLayout(rowSetup);
eighthRow.setLayout(rowSetup);
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
//Add fields to rows
firstRow.add(acctNumLabel);
firstRow.add(pmtLabel);
secondRow.add(acctNum);
secondRow.add(pmt);
thirdRow.add(firstNameLabel);
thirdRow.add(lastNameLabel);
fourthRow.add(firstName);
fourthRow.add(lastName);
fifthRow.add(addressLabel);
sixthRow.add(address);
seventhRow.add(cityLabel);
seventhRow.add(stateLabel);
seventhRow.add(zipLabel);
eighthRow.add(city);
eighthRow.add(state);
eighthRow.add(zip);
//Add rows to panel
fieldPanel.add(firstRow);
fieldPanel.add(secondRow);
fieldPanel.add(thirdRow);
fieldPanel.add(fourthRow);
fieldPanel.add(fifthRow);
fieldPanel.add(sixthRow);
fieldPanel.add(seventhRow);
fieldPanel.add(eighthRow);
//Add button to panel
buttonPanel.add(submitButton);
//Add panels to frame
c.add(fieldPanel, BorderLayout.CENTER);
c.add(buttonPanel, BorderLayout.SOUTH);
//Add functionality to buttons
submitButton.addActionListener(this);
//Get the current date and open the file
Date today = new Date();
SimpleDateFormat myFormat = new SimpleDateFormat("MMddyyyy");
String filename = "payments" + myFormat.format(today);
try
{
output = new DataOutputStream(new FileOutputStream(filename));
}
catch(IOException io)
{
JOptionPane.showMessageDialog(null,"The program could not create a storage location. Please check the disk drive and then run the program again.","Error",JOptionPane.INFORMATION_MESSAGE);
System.exit(1);
}
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent f)
{
int answer = JOptionPane.showConfirmDialog(null,"Are you sure you want to exit and submit the file?", "File Submission",JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION)
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent f)
{
String arg = f.getActionCommand();
if(checkFields())
{
try
{
output.writeUTF(acctNum.getText());
output.writeUTF(pmt.getText());
output.writeUTF(firstName.getText());
output.writeUTF(lastName.getText());
output.writeUTF(address.getText());
output.writeUTF(city.getText());
output.writeUTF(state.getText());
output.writeUTF(zip.getText());
JOptionPane.showMessageDialog(null,"The payment information has been saved.","Submission successful",JOptionPane.INFORMATION_MESSAGE);
}
catch(IOException c)
{
System.exit(1);
}
clearFields();
}
}
public boolean checkFields()
{
if ((acctNum.getText().compareTo("")<1) ||
(pmt.getText().compareTo("")<1) ||
(firstName.getText().compareTo("")<1) ||
(lastName.getText().compareTo("")<1) ||
(address.getText().compareTo("")<1) ||
(city.getText().compareTo("")<1) ||
(state.getText().compareTo("")<1) ||
(zip.getText().compareTo("")<1))
{
JOptionPane.showMessageDialog(null,"You must complete all fields.","Data Entry Error",JOptionPane.WARNING_MESSAGE);
return false;
}
else
{
return true;
}
}
public void clearFields()
{
//Clear fields and reset the focus
acctNum.setText("");
pmt.setText("");
firstName.setText("");
lastName.setText("");
address.setText("");
city.setText("");
state.setText("");
zip.setText("");
acctNum.requestFocus();
}
}
}
}
I tried to make quite a few changes to the program. The issue is that now the button does bring up a new window but the window doesn't include the data I need it to have. It has the title "Coat Payment", so I believe it is getting to everything but the inner class I have in the BillPayer method (the inner class is PaymentScreen). Once again I believe that my ignorance is leading me astray.
//Add functionality to buttons
submitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent d)
{
if (d.getSource() == submitButton)
{
BillPayer();
}
}
});
}
private void BillPayer()
{
JDialog PaymentScreen = new JDialog();
PaymentScreen.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
PaymentScreen.setSize(900,600);
PaymentScreen.setTitle("Coat Payment");
PaymentScreen.setResizable(false);
PaymentScreen.setLocation(200,200);
PaymentScreen.setVisible(true);
class PaymentScreen extends JDialog implements ActionListener
{
Sorry, but that's some schizophrenic code. Maybe I'm reading it wrong, but I see:
You create a JFrame variable called BillPayer, and set it visible. It is a small empty JFrame and nothing else.
You then declare a separate BillPayer class, and don't display it,
Except for in code within its (???) main method, a main method that is within a private inner class, which is (appropriately) never called.
Recommendations:
First and foremost, you probably really don't want to display another JFrame. Most applications should have only one main window, a JFrame.
If you need another window being displayed from a main window, then use a dialog such as a JDialog. This is fairly easy to do, and just like a JFrame involves creating a JPanel filled with your GUI, and then placing that JPanel into the JDialog and setting it visible.
If you use a JDialog, you can choose whether it is modal or not, whether it will freeze the underlying calling window when it is displayed or not.
To display another window from a button press, be it a JFrame or a JDialog, you would call setVisible(true) on the window from within the button press's ActionListener actionPerformed method. It looks like you're doing this. Is anything showing at all? Have you debugged the code to see if code you think is being reached is not being called?
Or if you want to display another view inside of the main window, use a CardLayout.
Don't give your variables the exact same name, spelling and capitalization as your classes.
Learn and follow Java naming conventions: class names begin with an upper case letter and variable and method names with lower-case letters.
Don't confuse your code by burying a main method inside of an inner private class. This makes little sense.
Study up on use of arrays and collections such as ArrayLists which can help you make programs that are much more compact, more readable, and easier to debug and extend. A lot of your code's redundancy can be reduced by doing this.
If you have code for another GUI view that is distinct from the main view, perhaps this code should be in its own top-level class, and not an inner class.
Edit
On review of your code some more, I suggest:
Yes, use a JDialog for the data entry window.
The data would probably be best displayed in a JTable held in a JScrollPane in the main GUI. This would be in place of the rows of JPanels that your current code uses.
This is going to sound rough, but it's more time efficient.
Select project > hit delete
Download Netbeans or Eclipse (or both) and program in these programs. They will help filter out mistakes you've made and provide a help with layout, so that it looks more comprehensible.
Once that's done, follow these tutorials:
http://docs.oracle.com/javase/tutorial/uiswing/start/index.html
The answer above already gave a lot of valuable tips, but your problem is that you simply do not know anything yet on how to properly build a program.
My tip: decide for yourself what would be awesome to make. Something you think is useful for yourself or others, then go through the tutorial and try to build it. This forces you to not only implement what you learn as you go along, but also run into the real issue with any programmming language: learn how to solve problems.

JPanels in Jframe not shown

I am making a simple layout for a calculator, actually i am new to java and learning the basics. My problem is that when i run this code, only a JFrame opens and the other panels n its buttons are not shown. PLz help , where my i going wrong.
import java.awt.*;
import javax.swing.*;
public class Layouts extends JFrame{
public Layouts(){
super("Calculator");
setLookAndFeel();
setSize(350,350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout border = new BorderLayout();
setLayout(border);
GridLayout numbers = new GridLayout(2,2);
row2.setLayout(numbers);
row2.add(one);
row2.add(two);
row2.add(three);
row2.add(four);
GridLayout operators = new GridLayout(2,2);
row3.setLayout(operators);
row3.add(plus);
row3.add(subtract);
row3.add(multiply);
row3.add(equals);
setVisible(true);
}
private void setLookAndFeel()
{
try
{
IManager.setLookAndFeel("com.sun.java.lang.plaf.nimbus.NimbusLookAndFeel");
}
catch(Exception exc)
{
}
}
//row 1
JPanel row1 = new JPanel();
JTextField text = new JTextField(20);
//row 2
JPanel row2 = new JPanel();
JButton one = new JButton("1");
JButton two = new JButton("2");
JButton three = new JButton("3");
JButton four = new JButton("4");
//row3
JPanel row3 = new JPanel();
JButton plus = new JButton("+");
JButton subtract = new JButton("-");
JButton multiply = new JButton("*");
JButton equals = new JButton("=");
public static void main(String[] args)
{
Layouts l1 = new Layouts();
}
}
Remember to add all of the components (i.e row2, row3 etc..)
Example:
add(row2,BorderLayout.CENTER)
add(row3,BorderLayout.SOUTH)
BorderLayout border = new BorderLayout();
setLayout(border);
But you aren't adding anything to border ! Add the numbers and operators.
You need to add the JPanels and JButtons to JFrame. The JFrame in this case is your Layouts class. So do something like :
row1.add(text);
this.add(row1);
row2.add(one);
row2.add(two);
row2.add(three);
row2.add(four);
this.add(row2);
...
check this tutorial is is a very useful one JButton, JPanel & JFrame examples

BorderLayout.CENTER "disappears"

I'm coding a prototype, but got problems with the GUI.
I want the JPanel pCustomer to be centered, but doing so it disappears completely. If I put it for example in the SOUTH, everything is fine.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JPanel implements ActionListener {
private JPanel pTop = new JPanel();
private JPanel pMenue = new JPanel();
private JPanel pContent = new JPanel();
private JPanel pCustomer = new JPanel();
private JPanel pEnq = new JPanel();
private JPanel pCustomerMenue = new JPanel();
private JTextField tf1 = new JTextField();
private JButton bCustomer = new JButton("Customer");
private JButton bEnq = new JButton("Product");
private JButton bCNew = new JButton("New Customer");
private JLabel lCustomer = new JLabel("Customer");
String[] customerString = {"--- SELECT -- ", "New Customer", "Edit Customer", "Delete Customer"};
private JComboBox cb1 = new JComboBox(customerString);
private JLabel lRes = new JLabel();
String[] productString = {"--- SELECT -- ", "Sell Product", "Enquire Product", "Complain Product"};
private JLabel lWelcome = new JLabel("Welcome to our System!");
private JLabel lNo = new JLabel("Customer Number: ");
private JLabel lEnq = new JLabel("Enquiry");
public Test() {
this.setLayout(new BorderLayout());
// pTop
this.add(pTop, BorderLayout.NORTH);
pTop.setLayout(new BorderLayout());
pTop.add(lNo, BorderLayout.WEST);
pTop.add(tf1, BorderLayout.CENTER);
// pMenue
this.add(pMenue, BorderLayout.WEST);
pMenue.setLayout(new GridLayout(5, 1));
pMenue.add(bCustomer);
pMenue.add(bEnq);
// pContent
this.add(pContent, BorderLayout.CENTER);
pContent.add(lWelcome);
pContent.setLayout(new BorderLayout());
pContent.setBackground(Color.GREEN);
// pCustomer
pContent.add(pCustomer, BorderLayout.CENTER); // EAST, SOUTH, WEST works, but I want it to be centered.
pCustomer.add(cb1);
pCustomer.add(lRes);
pCustomer.setVisible(false);
pCustomer.setBackground(Color.blue);
// pCustomerMenue
pContent.add(pCustomerMenue, BorderLayout.NORTH);
pCustomerMenue.add(bCNew);
pCustomerMenue.setVisible(false);
pCustomerMenue.setBackground(Color.red);
// pEnq
pContent.add(pEnq, BorderLayout.CENTER);
pEnq.add(lEnq);
pEnq.setVisible(false);
// ---
bCustomer.addActionListener(this);
bEnq.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
lWelcome.setVisible(false);
if (source == bCustomer) {
init();
pCustomer.setVisible(true);
pCustomerMenue.setVisible(true);
bCustomer.setEnabled(false);
}
if (source == bEnq) {
init();
pEnq.setVisible(true);
bEnq.setEnabled(false);
}
}
public void init() {
pCustomer.setVisible(false);
pCustomerMenue.setVisible(false);
pEnq.setVisible(false);
bCustomer.setEnabled(true);
bEnq.setEnabled(true);
}
}
If I remove these 3 lines:
pContent.add(pEnq, BorderLayout.CENTER);
pEnq.add(lEnq);
pEnq.setVisible(false);
I can even put it in the Centre and it works.
Read up about border layout. Basically you have 5 positions (NORTH, EAST, SOUTH, WEST, CENTER) and whenever you put a component into one of those positions any component already in that position is replaced.
Thus pContent.add(pEnq, BorderLayout.CENTER); will replace pCustomer with pEnq.
If you want both panels in the center you either need to put an intermediate panel into the center and then add the other panels to that one or use another layout manager, e.g. MiGLayout.
With MiGLayout your pContent layout might look like this:
pContent.setLayout(new MiGLayout());
pContent.add(pCustomerMenue, "pushx, wrap"); //fill the available width, new line after this component
pContent.add(pCustomer, "pushx, wrap"); //fill the available width, new line after this component
pContent.add(pEnq, "pushx"); //fill the available width
You try to add two different Panels to the Center of the BorderLayout.
First you add
pContent.add(pCustomer, BorderLayout.CENTER); // EAST, SOUTH, WEST works, but I want it to be centered.
And a few Lines later you do:
pContent.add(pEnq, BorderLayout.CENTER);
So pEnq lays over pCustomer!

Categories

Resources