I am very new to Java and I'm trying to put together a simple time calculator.
How come the add() method only throws up the last thing I added? When I run the program it only shows "Days" instead of the textboxes and the years label.
import javax.swing.*;
public class TimeCalculator extends JFrame
{
public static void main(String[] args)
{
JOptionPaneMultiInput window = new JOptionPaneMultiInput();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(300,500);
window.setVisible(true);
}
public TimeCalculator()
{
super("Time Calculator");
JTextField yearsField = new JTextField(5);
JTextField daysField = new JTextField(5);
JTextField hoursField = new JTextField(5);
JTextField minutesField = new JTextField(5);
JTextField secondsField = new JTextField(5);
JLabel yearsLabel = new JLabel();
JLabel daysLabel = new JLabel();
JLabel hoursLabel = new JLabel();
JLabel minutesLabel = new JLabel();
JLabel secondsLabel = new JLabel();
JCheckBox yearsCheckbox = new JCheckBox();
JCheckBox daysCheckbox = new JCheckBox();
JCheckBox hoursCheckbox = new JCheckBox();
JCheckBox minutesCheckbox = new JCheckBox();
JCheckBox secondsCheckbox = new JCheckBox();
JLabel yearsCLabel = new JLabel();
JLabel daysCLabel = new JLabel();
JLabel hoursCLabel = new JLabel();
JLabel minutesCLabel = new JLabel();
JLabel secondsCLabel = new JLabel();
JButton convertButton = new JButton();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
yearsLabel.setText("Years");
daysLabel.setText("Days");
hoursLabel.setText("Hours");
minutesLabel.setText("Minutes");
secondsLabel.setText("Seconds");
yearsCLabel.setText("Yr");
daysCLabel.setText("D");
hoursCLabel.setText("Hr");
minutesCLabel.setText("Min");
secondsCLabel.setText("Sec");
convertButton.setText("Convert");
convertButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
//doConvert(evt); this will be added later once i figure everything out
}
});
add(yearsField);
add(yearsLabel);
add(daysField);
add(daysLabel);
}
}
JOptionPaneMultiInput mentioned in main() is not part of the posted source code. Consider posting an SSCCE.
The answer to:
When I run the program it only shows "Days" instead of the textboxes
and the years label.
TimeCalculator that appears in the question extends JFrame. By default JFrame uses BorderLayout layout. When BorderLayout is used, add() method without constraints argument results in BorderLayout.CENTER constraint to add components. So you add your objects to the center of BorderLayout. Every subsequent add() replaces the previous component that was added. At the end, only daysLabel remains.
See How to Use BorderLayout for more details. Also see A Visual Guide to Layout Managers for other layout managers as you have many controls in your frame and it would be hard to lay it out without additional nesting panels.
Related
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class GUI extends JFrame implements ActionListener
{
GUI()
{
JFrame frame = new JFrame();
JLabel L_Name = new JLabel("Name");
JLabel L_Roll = new JLabel("Roll no");
JLabel L_Year = new JLabel("Year");
JLabel L_Branch = new JLabel("Branch");
JLabel L_Marks = new JLabel("Aggr Marks");
JTextField T_Name = new JTextField(15);
JTextField T_Roll = new JTextField(15);
JTextField T_Year = new JTextField(15);
JTextField T_Branch = new JTextField(15);
JTextField T_Marks = new JTextField(15);
JLabel R_Name = new JLabel("");
JLabel R_Roll = new JLabel("");
JLabel R_Year = new JLabel("");
JLabel R_Branch = new JLabel("");
JLabel R_Marks = new JLabel("");
JLabel R_aggr = new JLabel("");
JButton submit = new JButton("Submit");
JPanel p1 = new JPanel(new GridLayout(6,3,7,7));
p1.add(L_Name);
p1.add(T_Name);
p1.add(R_Name);
p1.add(L_Roll);
p1.add(T_Roll);
p1.add(R_Roll);
p1.add(L_Year);
p1.add(T_Year);
p1.add(R_Year);
p1.add(L_Branch);
p1.add(T_Branch);
p1.add(R_Branch);
p1.add(L_Marks);
p1.add(T_Marks);
p1.add(R_Marks);
p1.add(R_aggr);
submit.addActionListener(this);
p1.add(submit);
frame.add(p1);
frame.setLayout(null);
frame.setLocationRelativeTo(null);
frame.setSize(300,330);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
}
public static void main(String args[])
{
GUI g = new GUI();
}
}
I've added the JPanel to the JFrame, it is still not visible.
I am not getting any errors
This is what I am trying to do:
Create a GUI to enter the details of a student on the left side of the window. The following details are required: Name, Roll number, Branch (use radio button), Year (drop down list) and Aggregate marks. On clicking a submit button the consolidated details along with the total marks should be printed on the right side of the GUI (Use Swing and frame).
You're shooting yourself in the foot with this line:
frame.setLayout(null);
When you do this, you the programmer are completely responsible for specifying all the sizes and positions of components added to the container. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
So don't do this but instead use the layout managers and let them do the work for you.
Also as a side recommendation, I recommend that you try to improve the formatting of your code that you post in here and your code in general. Good formatting including using an indentation style that is uniform and consistent will help others (us!) to better understand your code, and more importantly, it will help you to better understand your code and thus fix your own bugs. Also it shows that you're willing to put in extra effort to make it easier for the volunteers here to help you, and that effort is much appreciated.
e.g., your code should look like this:
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class GUI extends JFrame implements ActionListener {
GUI() {
JFrame frame = new JFrame();
JLabel L_Name = new JLabel("Name");
JLabel L_Roll = new JLabel("Roll no");
JLabel L_Year = new JLabel("Year");
JLabel L_Branch = new JLabel("Branch");
JLabel L_Marks = new JLabel("Aggr Marks");
JTextField T_Name = new JTextField(15);
JTextField T_Roll = new JTextField(15);
JTextField T_Year = new JTextField(15);
JTextField T_Branch = new JTextField(15);
JTextField T_Marks = new JTextField(15);
JLabel R_Name = new JLabel("");
JLabel R_Roll = new JLabel("");
JLabel R_Year = new JLabel("");
JLabel R_Branch = new JLabel("");
JLabel R_Marks = new JLabel("");
JLabel R_aggr = new JLabel("");
JButton submit = new JButton("Submit");
JPanel p1 = new JPanel(new GridLayout(6, 3, 7, 7));
p1.add(L_Name);
p1.add(T_Name);
p1.add(R_Name);
p1.add(L_Roll);
p1.add(T_Roll);
p1.add(R_Roll);
p1.add(L_Year);
p1.add(T_Year);
p1.add(R_Year);
p1.add(L_Branch);
p1.add(T_Branch);
p1.add(R_Branch);
p1.add(L_Marks);
p1.add(T_Marks);
p1.add(R_Marks);
p1.add(R_aggr);
submit.addActionListener(this);
p1.add(submit);
frame.add(p1);
// frame.setLayout(null); // *** Get rid of
frame.setLocationRelativeTo(null);
// frame.setSize(300, 330); // *** Get rid of
frame.pack(); // **** add
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
}
public static void main(String args[]) {
GUI g = new GUI();
}
}
Yes, i googled for about 30min. Yes there are 2 different Posts about that topic in stackoverflow, but those do not give me any solution to my problem.
I am using quite a few Panels with BoxLayout to position some stuff. When i try to add the final thing to my main Panel i get "BoxLayout can't be shared".
Code:
private void open(int i) {
JLabel titelLabel = new JLabel("Aufgabenblatttitel: ");
JTextField titelTextField = new JTextField();
JLabel dozentLabel = new JLabel("Dozent: ");
JTextField dozentTextField = new JTextField();
JLabel beschreibungLabel = new JLabel("Aufgabenblattbeschreibung: ");
JTextField beschreibungTextField = new JTextField();
JLabel studiengangLabel = new JLabel("Studiengang: ");
JTextField studiengangTextField = new JTextField();
JLabel dateLabel = new JLabel("Erstellt am: ");
for(Aufgabe aufgabe : data.get(i).getAufgaben()) {
JPanel aufgabenPanel = new JPanel();
JLabel aufgabeTitelLabel = new JLabel("Titel: ");
JTextField aufgabeTitelTextField = new JTextField();
aufgabeTitelTextField.setText(aufgabe.getTitel());
JPanel aufgabeTitelPanel = new JPanel();
aufgabeTitelPanel.add(aufgabeTitelLabel);
aufgabeTitelPanel.add(aufgabeTitelTextField);
aufgabeTitelPanel.setLayout(new BoxLayout(aufgabeTitelPanel, BoxLayout.LINE_AXIS));
JLabel aufgabeBeschreibungLabel = new JLabel("Beschreibung: ");
JTextField aufgabeBeschreibungTextField = new JTextField();
aufgabeBeschreibungTextField.setText(aufgabe.getBeschreibung());
JPanel aufgabeBeschreibungPanel = new JPanel();
aufgabeBeschreibungPanel.add(aufgabeBeschreibungLabel);
aufgabeBeschreibungPanel.add(aufgabeBeschreibungTextField);
aufgabeBeschreibungPanel.setLayout(new BoxLayout(aufgabeBeschreibungLabel, BoxLayout.LINE_AXIS));
JLabel aufgabeLoesungLabel = new JLabel("Lösung: ");
JTextField aufgabeLoesungTextField = new JTextField();
aufgabeLoesungTextField.setText(aufgabe.getLoesung());
JPanel aufgabeLoesungPanel = new JPanel();
aufgabeLoesungPanel.add(aufgabeLoesungLabel);
aufgabeLoesungPanel.add(aufgabeLoesungTextField);
aufgabeLoesungPanel.setLayout(new BoxLayout(aufgabeLoesungPanel, BoxLayout.LINE_AXIS));
aufgabenPanel.add(aufgabeTitelPanel);
aufgabenPanel.add(aufgabeBeschreibungPanel);
aufgabenPanel.add(aufgabeLoesungPanel);
aufgabenPanel.setLayout(new BoxLayout(aufgabenPanel, BoxLayout.PAGE_AXIS));
this.add(aufgabenPanel);
}
}
Which is Part of the class "AufgabeEditieren", which is defined as:
public class AufgabeEditieren extends JPanel { ... }
So: The AufgabeEditieren constructor calls open() after the class has been initialized. The it tries to create some panels and objects and wants to add them to the class itself via "this.add(aufgabenPanel);". this is refererring to the class AufgabeEditieren (it's object). So why does it not work? Its a panel and should be able to get those items? Thanks...
Ok, it took me a while because I am really not familiar with your mother tongue (it would be much simpler for everyone if you posted your code with english names for variables), but the problem comes from here:
aufgabeBeschreibungPanel.setLayout(new BoxLayout(aufgabeBeschreibungLabel, BoxLayout.LINE_AXIS));
Your setting a BoxLayout on aufgabeBeschreibungPanel but you provide aufgabeBeschreibungLabel as a parameter of BoxLayout. You should instead write:
aufgabeBeschreibungPanel.setLayout(new BoxLayout(aufgabeBeschreibungPanel, BoxLayout.LINE_AXIS));
When seeing this issue, the most common cause of this is that you wrote:
y.setLayout(new BoxLayout(x, BoxLayout.XXX));
where y and x are different.
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.
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
I'm trying to create (hand-coded) a GUI similair to the GUI shown below, however, only an empty frame shows.
Mock GUI:
I've used various layouts and SWING/AWT components to create the GUI and 4 JPanels which contain:
mainPanel: Contains all the panels in it.
listPanel: Contains the JTables, JLabels and the two JButtons
infoPanel: Contains the JLabels, JCheckBox and JTextBoxes.
addPanel: Contains the JLists and JButton
This is what I coded so far:
import java.awt.*;
import javax.swing.*;
import javax.swing.JTable;
public class GUI extends JFrame {
public void buildGui() {
JFrame frame = new JFrame("Hotel TV Scheduler");
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel listPanel = new JPanel();
listPanel.setLayout(new GridLayout(3,3));
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new GridLayout(2,2));
JPanel addPanel = new JPanel();
addPanel.setLayout(new FlowLayout());
mainPanel.add(listPanel, BorderLayout.LINE_START);
mainPanel.add(infoPanel, BorderLayout.LINE_END);
mainPanel.add(addPanel, BorderLayout.PAGE_END);
JTable chOneTable = new JTable();
JTable chTwoTable = new JTable();
JTable listTable = new JTable();
JLabel ch1Label = new JLabel("Channel 1");
JLabel ch2Label = new JLabel("Channel 2");
JLabel listLabel = new JLabel("List");
JButton rmvChOneButton = new JButton("Remove Channel");
JButton rmvChTwoButton = new JButton("Remove Channel");
listPanel.add(ch1Label);
listPanel.add(ch2Label);
listPanel.add(listLabel);
listPanel.add(chOneTable);
listPanel.add(chTwoTable);
listPanel.add(listTable);
listPanel.add(rmvChOneButton);
listPanel.add(rmvChTwoButton);
JLabel titleLabel = new JLabel("Title");
JLabel genreLabel = new JLabel("Genre");
JLabel durationLabel = new JLabel("Duration");
JLabel actorLabel = new JLabel("Actor");
JLabel directorLabel = new JLabel("Director");
JLabel rentableLabel = new JLabel("Rentable");
JLabel synLabel = new JLabel("Synopsis");
JTextField txtTitle = new JTextField();
JTextField txtGenre = new JTextField();
JTextField txtDuration = new JTextField();
JTextField txtActor = new JTextField();
JTextField txtDirector = new JTextField();
JTextField txtSynopsis = new JTextField();
JCheckBox rentCB = new JCheckBox();
infoPanel.add(titleLabel);
infoPanel.add(txtTitle);
infoPanel.add(genreLabel);
infoPanel.add(txtGenre);
infoPanel.add(durationLabel);
infoPanel.add(txtDuration);
infoPanel.add(actorLabel);
infoPanel.add(txtActor);
infoPanel.add(directorLabel);
infoPanel.add(txtDirector);
infoPanel.add(rentableLabel);
infoPanel.add(rentCB);
infoPanel.add(synLabel);
infoPanel.add(txtSynopsis);
JButton btnAddProg = new JButton("Add Program");
JList channelList = new JList();
JList timeList = new JList();
addPanel.add(btnAddProg);
addPanel.add(channelList);
addPanel.add(timeList);
frame.setVisible(true);
}
}
Anyone can tell me why only an empty frame is showing up ?
Thanks and Regards,
Brian
Yep just checked, you'll see something if you actually add the mainPanel to the frame, (looks nothing like the mock though!)
frame.setContentPane(mainPanel);
frame.pack();
You've not added mainPanel to the frame