JLabel text in narrow column instead of spread out - java

I am trying to have a frame that has a JLabel on it. I have succeeded in adding it to the frame but the text shows up in a narrow column instead of taking up more space in the window. How do I fix this? I tried using the html with no luck.
EDIT: The intro panel is the one I am having trouble with.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Window implements ActionListener{
JFrame frame = new JFrame("Loan Program");
JFrame intro = new JFrame("Welcome To The Loan Program!");
JPanel panel = new JPanel(new GridBagLayout());
JPanel panel2 = new JPanel(new GridBagLayout());
JPanel panel3 = new JPanel(new GridBagLayout());
JPanel descriptionPanel = new JPanel(new GridBagLayout());
JPanel descriptionPanel1 = new JPanel(new GridBagLayout());
GridBagConstraints g = new GridBagConstraints();
JButton calculate;
JButton cancel;
JButton reset;
JButton introOk;
JLabel loanAmount;
JLabel loanInterest;
JLabel loanPeriod;
JLabel monthlyRepayment;
JLabel introLabel;
JTextField laField;
JTextField liField;
JTextField lpField;
JTextField mrField;
DecimalFormat df = new DecimalFormat("#.##");
public Window() {
g.insets = new Insets(10, 10, 20, 10); //For the spacing between elements
//Initalizing components
introLabel = new JLabel();
introOk = new JButton("Ok");
//Setting up text for intro panel
String text = "<html><h1 align='center'>Loan Program 1.0</h1>";
text = text + "This program lets you calculate the various aspects of loans <br />";
text = text + "If you are leaving a field empty then use 0 for its place <br />";
text = text + "<h1 align='center'>Text Fields To Enter</h1>";
text = text + "Monthly Payment: Enter values for: Loan Period, Loan Amount, and Loan Interest. Enter 0 for Monthly Payment. <br />";
text = text + "Loan Period: Enter Values for: Loan Amount, Loan Interest, and Monthly Payment. Enter 0 for Loan Period. <br />";
//Setting text to the label
introLabel.setText(text);
//Positioning introLabel
descriptionPanel.add(introLabel, g);
//Positioning button
descriptionPanel1.add(introOk, g);
//Actionlistener for buttont to dipose current frame.
introOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
intro.dispose();
}
});
intro.add(descriptionPanel);
intro.add(descriptionPanel1, BorderLayout.SOUTH);
//Initializing buttons here and adding them to panel
calculate = new JButton("Calculate");
reset = new JButton("Reset");
cancel = new JButton("Cancel");
panel.add(calculate, g);
panel.add(reset, g);
panel.add(cancel, g);
//Adding the Actionlistener for buttons
calculate.addActionListener(this);
reset.addActionListener(this);
cancel.addActionListener(this);
//Initializing the labels
loanAmount = new JLabel("Loan Amount:");
loanInterest = new JLabel("Loan Interest:");
loanPeriod = new JLabel("Loan Period:");
monthlyRepayment = new JLabel("Monthly Payment:");
//Positioning loanAmount label
g.gridx = 0;
g.gridy = 0;
panel2.add(loanAmount, g);
//Positioning loanInterest label
g.gridx = 0;
g.gridy = 2;
panel2.add(loanInterest, g);
//Positioning loanPeriod label
g.gridx = 0;
g.gridy = 3;
panel2.add(loanPeriod, g);
//Positioning monthlyRepayment label
g.gridx = 0;
g.gridy = 4;
panel2.add(monthlyRepayment, g);
//Initializing the text fields
laField = new JTextField("", 20);
liField = new JTextField("", 20);
lpField = new JTextField("", 20);
mrField = new JTextField("", 20);
//Positioning laField
g.gridx = 1;
g.gridy = 0;
panel2.add(laField, g);
//Positioning liField
g.gridx = 1;
g.gridy = 2;
panel2.add(liField, g);
//Positioning lpField
g.gridx = 1;
g.gridy = 3;
panel2.add(lpField, g);
//Positioning mrField
g.gridx = 1;
g.gridy = 4;
panel2.add(mrField, g);
//Adding panels to the frame using boarderlayout
frame.add(panel, BorderLayout.SOUTH);
frame.add(panel2, BorderLayout.WEST);
// Creating the window
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//popup window for intro
intro.setSize(500, 500);
intro.setVisible(true);
intro.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if(o == cancel) {
//Initializing components for the window
JFrame frame1 = new JFrame("Are you sure?");
JPanel panel = new JPanel(new GridBagLayout());
JPanel panel2 = new JPanel(new GridBagLayout());
JLabel label = new JLabel("Are you sure you want to exit?");
JButton yes = new JButton("Yes");
JButton no = new JButton("No");
//Positioning Label
g.gridx = 0;
g.gridy = 0;
panel.add(label, g);
//Positioning yes button
g.gridx = 0;
g.gridy = 0;
g.gridwidth = 1;
panel2.add(yes, g);
//Positioning no button
g.gridx = 1;
g.gridy = 0;
panel2.add(no, g);
//Action to close program when yes is clicked
yes.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//Action to close current window if no is clicked
no.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame1.dispose();
}
});
//Adding the panels to frame with borderlayout
frame1.add(panel, BorderLayout.NORTH);
frame1.add(panel2, BorderLayout.SOUTH);
//Setting up frame
frame1.setSize(300, 300);
frame1.setVisible(true);;
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Adding actionListener once again for second level of menu
//No to close the current window
Object b = e.getSource();
if(b == no) {
System.out.println("heres");
frame1.dispose();
}
//Yes to close the program completely
if(b == yes) {
System.exit(0);
}
}
//New instance of window to reset it
if(o == reset) {
frame.dispose();
new Window();
}
//Calculate buttons actions
if(o == calculate) {
//Test values to see if they are being passed
System.out.println(laField.getText() + "\n" + liField.getText() + "/n" + lpField.getText() + "\n" + mrField.getText());
//If statement for monthly payment with the correct fields filled out
if(laField.getText() != null && liField.getText() != null && lpField.getText() != null && mrField.getText() == "0") {
//Strings and double and ints to convert from text field number.
String sRate, sMonths, sPrincipal;
sRate = liField.getText();
sMonths = lpField.getText();
sPrincipal = laField.getText();
double rate = Double.parseDouble(sRate);
int months = Integer.parseInt(sMonths);
double principal = Double.parseDouble(sPrincipal);
//Setting up components for new window
JFrame frame = new JFrame("Monthly Payment");
JPanel panel = new JPanel(new GridBagLayout());
JPanel panel2 = new JPanel(new GridBagLayout());
JLabel label = new JLabel("The monthly payment is: " + df.format(calculateMonthlyRepayment(rate, months, principal)));
JButton button = new JButton("Ok");
//Action listener for okay button to just close current frame.
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
//Padding for element
g.insets = new Insets(5, 5, 5, 5);
//Adding components to panel
panel.add(label, g);
panel2.add(button, g);
//Adding panels to frame
frame.add(panel, BorderLayout.CENTER);
frame.add(panel2, BorderLayout.SOUTH);
//Intializing frame
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//If statement for period calculation checks to see proper fields filled
if(mrField.getText() != null && liField.getText() != null && laField.getText() != null && lpField.getText() == "0"); {
//String and doubles to convert to numbers from text box
String sMonthlyPayment, sloanAmount, sinterestRate;
sMonthlyPayment = mrField.getText();
sloanAmount = laField.getText();
sinterestRate = liField.getText();
double monthlyPayment = Double.parseDouble(sMonthlyPayment);
double loanAmount = Double.parseDouble(sloanAmount);
double interestRate = Double.parseDouble(sinterestRate);
//Initializing the components
JFrame frame = new JFrame("Total Loan Period");
JPanel panel = new JPanel(new GridBagLayout());
JPanel panel2 = new JPanel(new GridBagLayout());
JLabel label = new JLabel("Total number of periods is : " + calculatePeriod(monthlyPayment, interestRate, loanAmount));
JButton button = new JButton("Ok");
//Button listener to close current frame
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
//Padding for the components
g.insets = new Insets(5, 5, 5, 5);
//Adding componeents to panel with gridbag
panel.add(label, g);
panel2.add(button, g);
//Adding panels to frame
frame.add(panel, BorderLayout.CENTER);
frame.add(panel2, BorderLayout.SOUTH);
//Initializing the frame
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
}
public double calculateMonthlyRepayment(double rate, int months, double principal) {
String input = mrField.getText();
double totalMr = Double.parseDouble(input);
double mrpayment = (rate + ((rate)/((Math.pow(1 + rate, months) - 1)))) * principal;
return mrpayment;
}
double calculatePeriod(double monthlyPayment, double interestRate, double loanAmount) {
return (Math.log(monthlyPayment) - Math.log(monthlyPayment - (loanAmount * interestRate))) / Math.log(1 + interestRate);
}
}

First, a recommendation, please try using a gui designer like window builder or matisse. they really ease your daily work and limit the badness of code on defining layout constraints.
if you experience troubles with the layout and non appearing or misaligned components, it´s usually a sign of wrong usage of your desired layout manager. There are excellent posts about it throughout stackoverflow.
Your most significant error in the code is reusing the GridBagConstraints, which is a bad idea because
As you might have guessed from the above example, it is possible to reuse the same GridBagConstraints instance for multiple components, even if the components have different constraints. However, it is recommended that you do not reuse GridBagConstraints, as this can very easily lead to you introducing subtle bugs if you forget to reset the fields for each new instance.
so try to share your constraints only if they are the same for each component, e.g. constraints for the labels and another one for the textfield columns.
There also lies your error on narrow columns. if you also want to specify a desired width for all labels, set the gridwidth on the label contstraint. this applies to the textfield constraint, too.
Check out the GridBagLayout Example again, for better understanding of its usage.
Some more advises:
Naming your class Window maybe mislead others because they could assume they are using java.awt.window, which is totally different from your class and can be overseen as you see it only on the import statement.
Any gui element must be called from the EDT, so invoke your class using the SwingUtilities, like
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Window();
}
});
dont forget to call pack() to let the layout manager do its work based on your constraints.
Try also to avoid using tons of frames, instead use dialogs. Frames should only be used if its needed to have them in a separate context, like they would be totally indepedent from each other.
An example for you to start with:
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GridExample extends JFrame{
public GridExample() {
initComponents();
pack();
setTitle("GridExample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null); //Center, could also be setLocationByPlatform(true);
}
#Override
public Dimension preferredSize() {
return new Dimension(500,300);
}
private void initComponents() {
getContentPane().setLayout(new BorderLayout(0, 0));
JPanel mainPanel = new JPanel();
getContentPane().add(mainPanel, BorderLayout.CENTER);
GridBagLayout gbl_mainPanel = new GridBagLayout();
gbl_mainPanel.columnWidths = new int[]{0, 0, 0, 0};
gbl_mainPanel.rowHeights = new int[]{0, 0, 0, 0, 0, 0};
gbl_mainPanel.columnWeights = new double[]{0.0, 1.0, 0.0, Double.MIN_VALUE};
gbl_mainPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
mainPanel.setLayout(gbl_mainPanel);
JLabel lblLoanAmount = new JLabel("Loan Amount:");
GridBagConstraints gbc_lblLoanAmount = new GridBagConstraints();
gbc_lblLoanAmount.fill = GridBagConstraints.HORIZONTAL;
gbc_lblLoanAmount.insets = new Insets(0, 0, 5, 5);
gbc_lblLoanAmount.gridx = 0;
gbc_lblLoanAmount.gridy = 0;
mainPanel.add(lblLoanAmount, gbc_lblLoanAmount);
txtLoanAmount = new JTextField();
GridBagConstraints gbc_txtLoanAmount = new GridBagConstraints();
gbc_txtLoanAmount.gridwidth = 2;
gbc_txtLoanAmount.insets = new Insets(0, 0, 5, 0);
gbc_txtLoanAmount.fill = GridBagConstraints.HORIZONTAL;
gbc_txtLoanAmount.gridx = 1;
gbc_txtLoanAmount.gridy = 0;
mainPanel.add(txtLoanAmount, gbc_txtLoanAmount);
txtLoanAmount.setColumns(10);
JLabel lblLoanInterest = new JLabel("Loan Interest:");
GridBagConstraints gbc_lblLoanInterest = new GridBagConstraints();
gbc_lblLoanInterest.insets = new Insets(0, 0, 5, 5);
gbc_lblLoanInterest.fill = GridBagConstraints.BOTH;
gbc_lblLoanInterest.gridx = 0;
gbc_lblLoanInterest.gridy = 1;
mainPanel.add(lblLoanInterest, gbc_lblLoanInterest);
txtLoanInterest = new JTextField();
GridBagConstraints gbc_txtLoanInterest = new GridBagConstraints();
gbc_txtLoanInterest.gridwidth = 2;
gbc_txtLoanInterest.anchor = GridBagConstraints.NORTH;
gbc_txtLoanInterest.insets = new Insets(0, 0, 5, 0);
gbc_txtLoanInterest.fill = GridBagConstraints.HORIZONTAL;
gbc_txtLoanInterest.gridx = 1;
gbc_txtLoanInterest.gridy = 1;
mainPanel.add(txtLoanInterest, gbc_txtLoanInterest);
txtLoanInterest.setColumns(10);
JLabel lblLoanPeriod = new JLabel("Loan Period:");
GridBagConstraints gbc_lblLoanPeriod = new GridBagConstraints();
gbc_lblLoanPeriod.fill = GridBagConstraints.HORIZONTAL;
gbc_lblLoanPeriod.insets = new Insets(0, 0, 5, 5);
gbc_lblLoanPeriod.gridx = 0;
gbc_lblLoanPeriod.gridy = 2;
mainPanel.add(lblLoanPeriod, gbc_lblLoanPeriod);
txtLoanPeriod = new JTextField();
GridBagConstraints gbc_txtLoanPeriod = new GridBagConstraints();
gbc_txtLoanPeriod.gridwidth = 2;
gbc_txtLoanPeriod.anchor = GridBagConstraints.NORTH;
gbc_txtLoanPeriod.insets = new Insets(0, 0, 5, 0);
gbc_txtLoanPeriod.fill = GridBagConstraints.HORIZONTAL;
gbc_txtLoanPeriod.gridx = 1;
gbc_txtLoanPeriod.gridy = 2;
mainPanel.add(txtLoanPeriod, gbc_txtLoanPeriod);
txtLoanPeriod.setColumns(10);
JLabel lblMonthlyPayment = new JLabel("Monthly Payment:");
GridBagConstraints gbc_lblMonthlyPayment = new GridBagConstraints();
gbc_lblMonthlyPayment.fill = GridBagConstraints.HORIZONTAL;
gbc_lblMonthlyPayment.insets = new Insets(0, 0, 5, 5);
gbc_lblMonthlyPayment.gridx = 0;
gbc_lblMonthlyPayment.gridy = 3;
mainPanel.add(lblMonthlyPayment, gbc_lblMonthlyPayment);
txtMonthlyPament = new JTextField();
GridBagConstraints gbc_txtMonthlyPament = new GridBagConstraints();
gbc_txtMonthlyPament.gridwidth = 2;
gbc_txtMonthlyPament.insets = new Insets(0, 0, 5, 0);
gbc_txtMonthlyPament.anchor = GridBagConstraints.NORTH;
gbc_txtMonthlyPament.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMonthlyPament.gridx = 1;
gbc_txtMonthlyPament.gridy = 3;
mainPanel.add(txtMonthlyPament, gbc_txtMonthlyPament);
txtMonthlyPament.setColumns(10);
JButton btnCalculate = new JButton("Calculate");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculate();
}
private void calculate() {
//do the math here
txtResult.setText("Calculate pressed!");
}
});
JLabel lblResult = new JLabel("Result:");
GridBagConstraints gbc_lblResult = new GridBagConstraints();
gbc_lblResult.fill = GridBagConstraints.HORIZONTAL;
gbc_lblResult.insets = new Insets(0, 0, 0, 5);
gbc_lblResult.gridx = 0;
gbc_lblResult.gridy = 4;
mainPanel.add(lblResult, gbc_lblResult);
txtResult = new JTextField();
GridBagConstraints gbc_txtResult = new GridBagConstraints();
gbc_txtResult.insets = new Insets(0, 0, 0, 5);
gbc_txtResult.fill = GridBagConstraints.HORIZONTAL;
gbc_txtResult.gridx = 1;
gbc_txtResult.gridy = 4;
mainPanel.add(txtResult, gbc_txtResult);
txtResult.setColumns(10);
GridBagConstraints gbc_btnCalculate = new GridBagConstraints();
gbc_btnCalculate.gridx = 2;
gbc_btnCalculate.gridy = 4;
mainPanel.add(btnCalculate, gbc_btnCalculate);
}
private static final long serialVersionUID = 1L;
private JTextField txtLoanAmount;
private JTextField txtLoanInterest;
private JTextField txtLoanPeriod;
private JTextField txtMonthlyPament;
private JTextField txtResult;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GridExample g = new GridExample();
String text = "<html><h1 align='center'>Loan Program 1.0</h1>";
text = text + "This program lets you calculate the various aspects of loans <br />";
text = text + "If you are leaving a field empty then use 0 for its place <br />";
text = text + "<h1 align='center'>Text Fields To Enter</h1>";
text = text + "Monthly Payment: Enter values for: Loan Period, Loan Amount, and Loan Interest. Enter 0 for Monthly Payment. <br />";
text = text + "Loan Period: Enter Values for: Loan Amount, Loan Interest, and Monthly Payment. Enter 0 for Loan Period. <br />";
g.setVisible(true);
JOptionPane.showMessageDialog(g, new JLabel(text));
}
});
}
}

Related

I want my button not in the same row as my choose buttons in my gui? How will I do that?

How do I add a break to put my "Make pokemon" buttons and textarea not in the same row as my "Pokemon choice." I'm trying to put an empty JLabel, but I don't think it works.
public class PokemonPanel extends JPanel {
private JLabel lTitle = new JLabel("Pokemon");
private JLabel lMsg = new JLabel(" ");
private JButton bDone = new JButton(" Make Pokemon ");
private JButton bClear = new JButton(" Clear ");
private JPanel topSubPanel = new JPanel();
private JPanel centerSubPanel = new JPanel();
private JPanel bottomSubPanel = new JPanel();
private GUIListener listener = new GUIListener();
private Choice chSpe = new Choice();
private JLabel lEmp = new JLabel(" ");
private PokemonGUILizylf st;
private final int capacity = 10;
private PokemonGUILizylf[ ] stArr = new PokemonGUILizylf[capacity];
private int count = 0;
private String sOut = new String("");
private JTextArea textArea = new JTextArea(400, 500);
private JTextArea textArea2 = new JTextArea(400, 500);
private JScrollPane scroll = new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
public PokemonPanel() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(400, 500));
topSubPanel.setBackground(Color.cyan);
centerSubPanel.setBackground(Color.white);
bottomSubPanel.setBackground(Color.white);
topSubPanel.add(lTitle);
this.add("North", topSubPanel);
JLabel lSpe = new JLabel("Pokemon Available: ");
JLabel lEmp = new JLabel(" ");
JLabel lNew = new JLabel("New Pokemon: ");
//add choices to the choice dropdown list
chSpe.add("Choose");
chSpe.add("Bulbasaur");
chSpe.add("Venusaur");
chSpe.add("Ivysaur");
chSpe.add("Squirtle");
chSpe.add("Wartortle");
chSpe.add("Blastoise");
chSpe.add("Charmander");
chSpe.add("Charmeleon");
chSpe.add("Charizard");
centerSubPanel.add(lSpe);
centerSubPanel.add(chSpe);
centerSubPanel.add(lEmp);
centerSubPanel.add(bDone);
centerSubPanel.add(lNew);
textArea.setPreferredSize(new Dimension(500, 200));
textArea.setEditable(false);
textArea2.setPreferredSize(new Dimension(500, 200));
textArea2.setEditable(false);
textArea.setBackground(Color.white);
textArea.setEditable(false);
scroll.setBorder(null);
centerSubPanel.add(scroll); //add scrollPane to panel, textArea inside.
scroll.getVerticalScrollBar().setPreferredSize(new Dimension(10, 0));
add("Center", centerSubPanel);
bottomSubPanel.add(lMsg);
bDone.addActionListener(listener); //add listener to button
bottomSubPanel.add(bClear);
bClear.addActionListener(listener); //add listener to button
//add bottomSubPanel sub-panel to South area of main panel
add("South", bottomSubPanel);
}
This is what my GUI looks like:
enter image description here
But it should show like this:
enter image description here
Can someone explain to me how I can do that?
Use a different layout manager (other then default FlowLayout which JPanel uses)
See Laying Out Components Within a Container for more details.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new PokemonPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PokemonPanel extends JPanel {
private JLabel lTitle = new JLabel("Pokemon");
// private JLabel lMsg = new JLabel(" ");
private JButton bDone = new JButton("Make Pokemon ");
private JButton bClear = new JButton("Clear");
private JPanel topSubPanel = new JPanel();
private JPanel centerSubPanel = new JPanel(new GridBagLayout());
private JPanel bottomSubPanel = new JPanel();
// private GUIListener listener = new GUIListener();
private JComboBox<String> chSpe = new JComboBox<>();
private JLabel lEmp = new JLabel(" ");
// private PokemonGUILizylf st;
private final int capacity = 10;
// private PokemonGUILizylf[] stArr = new PokemonGUILizylf[capacity];
// private int count = 0;
// private String sOut = new String("");
// private JTextArea textArea = new JTextArea(400, 500);
// private JTextArea textArea2 = new JTextArea(400, 500);
//
// private JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
// JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
public PokemonPanel() {
this.setLayout(new BorderLayout());
// this.setPreferredSize(new Dimension(400, 500));
topSubPanel.setBackground(Color.cyan);
centerSubPanel.setBackground(Color.white);
bottomSubPanel.setBackground(Color.white);
topSubPanel.add(lTitle);
this.add("North", topSubPanel);
JLabel lSpe = new JLabel("Pokemon Available: ");
JLabel lNew = new JLabel("New Pokemon: ");
//add choices to the choice dropdown list
DefaultComboBoxModel<String> chSpeModel= new DefaultComboBoxModel<>();
chSpeModel.addElement("Choose");
chSpeModel.addElement("Bulbasaur");
chSpeModel.addElement("Venusaur");
chSpeModel.addElement("Ivysaur");
chSpeModel.addElement("Squirtle");
chSpeModel.addElement("Wartortle");
chSpeModel.addElement("Blastoise");
chSpeModel.addElement("Charmander");
chSpeModel.addElement("Charmeleon");
chSpeModel.addElement("Charizard");
chSpe.setModel(chSpeModel);
centerSubPanel.setBorder(new EmptyBorder(4, 4, 4, 4));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.LINE_END;
centerSubPanel.add(lSpe, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
centerSubPanel.add(chSpe);
gbc.anchor = GridBagConstraints.NORTH;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy++;
centerSubPanel.add(bDone, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
centerSubPanel.add(lNew, gbc);
gbc.gridx++;
gbc.gridheight = gbc.REMAINDER;
centerSubPanel.add(new JScrollPane(new JTextArea(10, 10)), gbc);
// textArea.setEditable(false);
// textArea2.setEditable(false);
//
// textArea.setBackground(Color.white);
// textArea.setEditable(false);
// scroll.setBorder(null);
// centerSubPanel.add(scroll); //add scrollPane to panel, textArea inside.
// scroll.getVerticalScrollBar().setPreferredSize(new Dimension(10, 0));
add("Center", centerSubPanel);
// bottomSubPanel.add(lMsg);
// bDone.addActionListener(listener); //add listener to button
bottomSubPanel.add(bClear);
// bClear.addActionListener(listener); //add listener to button
//add bottomSubPanel sub-panel to South area of main panel
add("South", bottomSubPanel);
}
}
}
Also, avoid using setPreferredSize, let the layout managers do their job. In the example I'm used insets (from GridBagConstraints) and an EmptyBorder to add some additional space around the components
Also, be careful of using AWT components (ie Choice), they don't always play nicely with Swing. In this case, you should be using JComboBox

What layout should I use to make this work for Java?

Here's what I want the end result to look like...
I am trying to use a GridBagLayout for this but not sure if its the right choice because it's coming out all over the place. I know I shouldn't write all my code in a single constructor but here's what I have so far...
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.Font;
import java.awt.event.*;
import static java.lang.Math.*;
public class HomeStylePizza extends JFrame{
private static final int WIDTH = 500;
private static final int HEIGHT = 400;
//GUI components
private JLabel lblEachTopping, lblPizzaSize, lblPizzaType, lblWelcome, lblYourOrder;
private JButton btnProcessSelection;
private JCheckBox cbPepproni, cbSausage, cbMushrooms, cbPineapple, cbOnion, cbBellPepper;
private JRadioButton rbSmall, rbMedium, rbLarge, rbThinCrust, rbMediumCrust, rbPan;
private ButtonGroup grp1, grp2;
private JTextArea textArea;
private CalculateButtonHandler cbHandler;
public HomeStylePizza()
{
//Create new labels
lblEachTopping = new JLabel("Each Topping: $1.50");
lblPizzaSize = new JLabel("Pizza Size");
lblPizzaType = new JLabel("Pizza Type");
lblWelcome = new JLabel("Welcome to Home Style Pizza Shop");
lblYourOrder = new JLabel("Your order:");
//Create new buttons
btnProcessSelection = new JButton("Process Selection");
cbHandler = new CalculateButtonHandler();
btnProcessSelection.addActionListener(cbHandler);
//Create new JCheckBoxes
cbPepproni = new JCheckBox("Pepproni");
cbSausage = new JCheckBox("Sausage");
cbMushrooms = new JCheckBox("Mushrooms");
cbPineapple = new JCheckBox("Pineapple");
cbOnion = new JCheckBox("Onion");
cbBellPepper = new JCheckBox("Bell Pepper");
//Create radio buttons
rbSmall = new JRadioButton("Small: $6.50");
rbMedium = new JRadioButton("Medium: $8.50");
rbLarge = new JRadioButton("Large: $10.00");
rbThinCrust = new JRadioButton("Thin Crust");
rbMediumCrust = new JRadioButton("Medium Crust");
rbPan = new JRadioButton("Pan");
//Create new TextArea
textArea = new JTextArea(6, 10);
//Set title
setTitle("Pizza Shop");
//Create new font layout
Font font = new Font("New Times Roman", Font.BOLD, 18);
//get the container
Container pane = getContentPane();
JPanel thePanel = new JPanel();
thePanel.setLayout(new GridBagLayout());
//set the layout
pane.setLayout(new GridBagLayout());
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
gridConstraints.gridwidth = 1;
gridConstraints.gridheight = 1;
gridConstraints.weightx = 50;
gridConstraints.weighty = 100;
gridConstraints.insets = new Insets(5,5,5,5);
gridConstraints.anchor = GridBagConstraints.CENTER;
gridConstraints.fill = GridBagConstraints.BOTH;
//Place components in the pane
thePanel.add(lblWelcome, gridConstraints);
gridConstraints.anchor = GridBagConstraints.FIRST_LINE_START;
gridConstraints.gridwidth = 20;
gridConstraints.gridx = 15;
lblWelcome.setFont(new Font("New Times Roman", Font.BOLD, 18));
lblWelcome.setForeground(Color.RED);
//Create new vertical box and place a titled border around it
Box optionBox1 = Box.createVerticalBox();
optionBox1.setBorder(BorderFactory.createTitledBorder(null, "Toppings", 0, 0, new Font("times new roman", Font.PLAIN, 14), Color.RED));
//add components to optionBox1
optionBox1.add(lblEachTopping);
lblEachTopping.setForeground(Color.RED);
optionBox1.add(cbPepproni);
optionBox1.add(cbSausage);
optionBox1.add(cbMushrooms);
optionBox1.add(cbPineapple);
optionBox1.add(cbOnion);
optionBox1.add(cbBellPepper);
//add optionBox1 to WEST quadrant
thePanel.add(optionBox1, gridConstraints);
gridConstraints.anchor = GridBagConstraints.LINE_START;
gridConstraints.gridwidth = 1;
gridConstraints.gridx = 1;
gridConstraints.gridy = 10;
//Create new vertical box and place a titled border around it
Box optionBox2 = Box.createVerticalBox();
optionBox2.setBorder(BorderFactory.createTitledBorder(null, "Pizza Size", 0, 0, new Font("times new roman", Font.PLAIN, 14), Color.RED));
//Create new ButtonGroup
grp1 = new ButtonGroup();
//add components to optionBox2 and grp1
grp1.add(rbSmall);
grp1.add(rbMedium);
grp1.add(rbLarge);
optionBox2.add(rbSmall);
optionBox2.add(rbMedium);
optionBox2.add(rbLarge);
//add optionBox2 to CENTER
thePanel.add(optionBox2, gridConstraints);
gridConstraints.anchor = GridBagConstraints.CENTER;
gridConstraints.gridx = 3;
gridConstraints.gridy = 10;
Box btnBox = Box.createHorizontalBox();
btnBox.setBorder(BorderFactory.createEmptyBorder());
btnBox.add(btnProcessSelection);
thePanel.add(btnBox);
gridConstraints.anchor = GridBagConstraints.LAST_LINE_END;
gridConstraints.gridwidth = 5;
gridConstraints.gridx = 3;
gridConstraints.gridy = 12;
//Create new vertical box and place a titled border around it
Box optionBox3 = Box.createVerticalBox();
optionBox3.setBorder(BorderFactory.createTitledBorder(null, "Pizza Type", 0, 0, new Font("times new roman", Font.PLAIN, 14), Color.RED));
//Create new ButtonGroup
grp2 = new ButtonGroup();
//add components to optionBox2 and grp1
grp2.add(rbThinCrust);
grp2.add(rbMediumCrust);
grp2.add(rbPan);
optionBox3.add(rbThinCrust);
optionBox3.add(rbMediumCrust);
optionBox3.add(rbPan);
//add optionBox3 to EAST
thePanel.add(optionBox3, gridConstraints);
gridConstraints.anchor = GridBagConstraints.LINE_END;
gridConstraints.gridwidth = 1;
gridConstraints.gridx = 5;
gridConstraints.gridy = 10;
//Create box for lblYourOrder and textArea and
//add them to pane in SOUTH quadrant
Box orderBox = Box.createVerticalBox();
orderBox.setBorder(null);
orderBox.add(lblYourOrder);
orderBox.add(textArea);
thePanel.add(orderBox, gridConstraints);
gridConstraints.anchor = GridBagConstraints.LAST_LINE_START;
gridConstraints.gridwidth = 30;
gridConstraints.gridx = 1;
gridConstraints.gridy = 13;
pane.add(thePanel);
//set window size and display it
setSize(WIDTH, HEIGHT);
setVisible(true);
//Center frame
this.setLocationRelativeTo(null);
this.pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}//End of constructor
public static void main(String[] args)
{
HomeStylePizza menuTest = new HomeStylePizza();
}//End of main
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
}
}
}//End of class
Its a bit ugly and you can ignore most of my comments I've been changing things around trying to fix it. I was using a different layout.
Edited: I went ahead and created the Pizza Shop GUI.
I used a combination of BorderLayouts and GridBagLayouts.
I grouped together the code to make it easier to follow. Grouping the code does not mean putting all of the JCheckBox initializations together. Grouping the code means that all of the elements that make up a JPanel are there, right next to each other. This way, you don't have to jump all over the code looking for the lines that define the JRadioButton rbMedium.
I used a separate GridBagConstraints for each Swing component to make it easier for me to debug the GUI.
I've left the action listener for you to code.
Here's the GUI code:
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
public class HomeStylePizza implements Runnable {
private static final Insets bottomInsets = new Insets(10, 10, 10, 10);
private static final Insets normalInsets = new Insets(10, 10, 0, 10);
// GUI components
private JCheckBox cbPepproni, cbSausage, cbMushrooms, cbPineapple, cbOnion,
cbBellPepper;
private JRadioButton rbSmall, rbMedium, rbLarge, rbThinCrust,
rbMediumCrust, rbPan;
private JTextArea textArea;
public static void main(String[] args) {
SwingUtilities.invokeLater(new HomeStylePizza());
} // End of main
#Override
public void run() {
JFrame frame = new JFrame("Pizza Shop");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
int gridy = 0;
addComponent(mainPanel, createTitlePanel(), 0, gridy++, 2, 1,
normalInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
addComponent(mainPanel, createToppingPanel(), 0, gridy, 1, 1,
normalInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
JPanel eastPanel = new JPanel();
eastPanel.setLayout(new BorderLayout());
eastPanel.add(createSizePanel(), BorderLayout.WEST);
eastPanel.add(new JLabel(" "), BorderLayout.CENTER);
eastPanel.add(createTypePanel(), BorderLayout.EAST);
eastPanel.add(createButtonPanel(), BorderLayout.SOUTH);
addComponent(mainPanel, eastPanel, 1, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
addComponent(mainPanel, createTextAreaPanel(), 0, gridy++, 2, 1,
bottomInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel();
JLabel lblWelcome = new JLabel("Welcome to Home Style Pizza Shop");
Font titleFont = lblWelcome.getFont().deriveFont(20F);
lblWelcome.setFont(titleFont);
lblWelcome.setForeground(Color.RED);
panel.add(lblWelcome);
return panel;
}
private JPanel createToppingPanel() {
Border redBorder = BorderFactory.createLineBorder(Color.RED, 2);
Border emptyBorder = BorderFactory.createEmptyBorder(4, 10, 4, 10);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createCompoundBorder(redBorder,
emptyBorder));
panel.setLayout(new GridLayout(0, 1));
JLabel lblEachTopping = new JLabel("Each Topping: $1.50");
lblEachTopping.setForeground(Color.RED);
panel.add(lblEachTopping);
cbPepproni = new JCheckBox("Pepperoni");
cbSausage = new JCheckBox("Sausage");
cbMushrooms = new JCheckBox("Mushrooms");
cbPineapple = new JCheckBox("Pineapple");
cbOnion = new JCheckBox("Onion");
cbBellPepper = new JCheckBox("Bell Pepper");
// add components to optionBox1
panel.add(cbPepproni);
panel.add(cbSausage);
panel.add(cbMushrooms);
panel.add(cbPineapple);
panel.add(cbOnion);
panel.add(cbBellPepper);
return panel;
}
private JPanel createSizePanel() {
Border redBorder = BorderFactory.createLineBorder(Color.RED, 2);
Border emptyBorder = BorderFactory.createEmptyBorder(4, 10, 4, 10);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createCompoundBorder(redBorder,
emptyBorder));
panel.setLayout(new GridLayout(0, 1));
JLabel lblPizzaSize = new JLabel("Pizza Size");
lblPizzaSize.setForeground(Color.RED);
panel.add(lblPizzaSize);
rbSmall = new JRadioButton("Small: $6.50");
rbMedium = new JRadioButton("Medium: $8.50");
rbLarge = new JRadioButton("Large: $10.00");
// Create new ButtonGroup
ButtonGroup group = new ButtonGroup();
group.add(rbSmall);
group.add(rbMedium);
group.add(rbLarge);
panel.add(rbSmall);
panel.add(rbMedium);
panel.add(rbLarge);
return panel;
}
private JPanel createTypePanel() {
Border redBorder = BorderFactory.createLineBorder(Color.RED, 2);
Border emptyBorder = BorderFactory.createEmptyBorder(4, 10, 4, 10);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createCompoundBorder(redBorder,
emptyBorder));
panel.setLayout(new GridLayout(0, 1));
JLabel lblPizzaType = new JLabel("Pizza Type");
lblPizzaType.setForeground(Color.RED);
panel.add(lblPizzaType);
rbThinCrust = new JRadioButton("Thin Crust");
rbMediumCrust = new JRadioButton("Medium Crust");
rbPan = new JRadioButton("Pan");
// Create new ButtonGroup
ButtonGroup group = new ButtonGroup();
// add components to optionBox2 and grp1
group.add(rbThinCrust);
group.add(rbMediumCrust);
group.add(rbPan);
panel.add(rbThinCrust);
panel.add(rbMediumCrust);
panel.add(rbPan);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
JButton btnProcessSelection = new JButton("Process Selection");
btnProcessSelection.addActionListener(new CalculateButtonHandler());
panel.add(btnProcessSelection);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JLabel lblYourOrder = new JLabel("Your order:");
panel.add(lblYourOrder, BorderLayout.NORTH);
textArea = new JTextArea(6, 12);
JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight, Insets insets,
int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
private class CalculateButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
} // End of HomeStylePizza class
Use GridBagLayout, or use netbeans it will make it easy for you, other option use GridLayout(2,1)
in it 2 panel
panel 1 will have grid layout of 1,2 in it you first list and other pnael has grid layout of 2,1 first row is your second list and the second row will be the button finally put the order info in the second row of your base layout.

JTextField Everything looks ok in Eclipse but won't compile

Can someone please tell me what's wrong with this code?
I need it to pop up a frame and fill the frame with certain field a namer field and an intake field and also display a button at the bottom of the grid.
Any help would be welcomed, Thanks!!
import java.awt.*;
import javax.swing.*;
public class FrameDemo
//To create the gui and show it.
{
public static void createAndShowGUI()
{
//create and set up the window.
JFrame frame = new JFrame("RungeKutta");
GridLayout first = new GridLayout(1,14);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create, name and Populate TextField
JTextField PL = new JTextField("Pendulum Length", 20);
//Set TextField to Uneditable. Each will have Empty Field Below For Variables
PL.setEditable(false);
//Set Textfield for user entered dat
JTextField PLv = new JTextField();
//Allow handler for user input on Empty Textfield?
JTextField AD = new JTextField("Angular Displacement", 20);
AD.setEditable(false);
JTextField ADv = new JTextField();
JTextField AV = new JTextField("Angular Velocity", 20);
AV.setEditable(false);
JTextField Avv = new JTextField();
JTextField TS= new JTextField("Time Steps", 20);
TS.setEditable(false);
JTextField TSv = new JTextField();
JTextField MT = new JTextField("Max Time", 20);
MT.setEditable(false);
JTextField MTv = new JTextField();
JTextField V = new JTextField("Viscosity (0-1)", 20);
V.setEditable(false);
JTextField Vv = new JTextField();
//Create Button to Restart
JButton BNewGraph = new JButton("Draw New Graph"); //Button to restart entire drawing process
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600,500));
frame.getContentPane().add(PL, first);
frame.getContentPane().add(PLv, first);
frame.getContentPane().add(AD, first);
frame.getContentPane().add(ADv, first);
frame.getContentPane().add(AV, first);
frame.getContentPane().add(Avv, first);
frame.getContentPane().add(TS, first);
frame.getContentPane().add(TSv, first);
frame.getContentPane().add(MT, first);
frame.getContentPane().add(MTv, first);
frame.getContentPane().add(V, first);
frame.getContentPane().add(Vv, first);
frame.getContentPane().add(BNewGraph, first);
//display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
//add job to event scheduler
//create and show GUI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
This is not how you use GridLayout:
frame.getContentPane().add(PL, first);
Instead you'd set the container's layout using the layout manager:
frame.getContentPane().setLayout(first);
and then add components to the container:
frame.getContentPane().add(PL);
frame.getContentPane().add(PLv);
frame.getContentPane().add(AD);
frame.getContentPane().add(ADv);
frame.getContentPane().add(AV);
frame.getContentPane().add(Avv);
frame.getContentPane().add(TS);
frame.getContentPane().add(TSv);
frame.getContentPane().add(MT);
frame.getContentPane().add(MTv);
// and so on for all the components.
You will want to read the tutorial on how to use GridLayout which you can find here: GridLayout Tutorial.
As an aside, note that this:
frame.getContentPane().add(PL);
can be shortened to this:
frame.add(PL);
Also you will want to study and learn Java naming conventions: class names begin with an upper case letter and all method and variables with lower case letters. Also avoid variable names like pl or plv, or ad or adv, and instead use names that are a little bit longer and have meaning, names that make your code self-commenting. So instead of AD, consider angularDisplacementField for the JTextfield's name.
Myself, I'd use a GridBagLayout and do something like:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.*;
public class GuiDemo extends JPanel {
// or better -- use an enum for this
public static final String[] FIELD_LABELS = {
"Pendulum Length", "Angular Displacement", "Angular Velocity",
"Time Steps", "Max Time", "Viscocity (0-1)"
};
private static final int TEXT_FIELD_COLUMNS = 10;
private static final int GAP = 3;
private static final Insets RIGHT_GAP_INSETS = new Insets(GAP, GAP, GAP, 3 * GAP);
private static final Insets BALANCED_INSETS = new Insets(GAP, GAP, GAP, GAP);
private Map<String, JTextField> labelFieldMap = new HashMap<>();
public GuiDemo() {
JPanel labelFieldPanel = new JPanel(new GridBagLayout());
int row = 0;
// to make sure that no focusAccelerator is re-used
Set<Character> focusAccelSet = new HashSet<>();
for (String fieldLabelLText : FIELD_LABELS) {
JLabel fieldLabel = new JLabel(fieldLabelLText);
JTextField textField = new JTextField(TEXT_FIELD_COLUMNS);
labelFieldPanel.add(fieldLabel, getGbc(row, 0));
labelFieldPanel.add(textField, getGbc(row, 1));
labelFieldMap.put(fieldLabelLText, textField);
for (char c : fieldLabelLText.toCharArray()) {
if (!focusAccelSet.contains(c)) {
textField.setFocusAccelerator(c);
fieldLabel.setDisplayedMnemonic(c);
focusAccelSet.add(c);
break;
}
}
row++;
}
JButton button = new JButton(new DrawGraphAction("Draw New Graph"));
labelFieldPanel.add(button, getGbc(row, 0, 2, 1));
setLayout(new BorderLayout(GAP, GAP));
add(labelFieldPanel, BorderLayout.CENTER);
}
private class DrawGraphAction extends AbstractAction {
public DrawGraphAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO calculation method
}
}
public static GridBagConstraints getGbc(int row, int column) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = column;
gbc.gridy = row;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
if (column == 0) {
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = RIGHT_GAP_INSETS;
} else {
gbc.anchor = GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = BALANCED_INSETS;
}
return gbc;
}
public static GridBagConstraints getGbc(int row, int column, int width, int height) {
GridBagConstraints gbc = getGbc(row, column);
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.insets = BALANCED_INSETS;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Gui Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GuiDemo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Need help making button relay information

Okay, so I have made a GUI with some input boxes and a combo box. I am wondering how I would go about having a listener know when the button is pressed then relay all the information in the imput boxes and combo box into different parts of the script...
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class dogedice extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JComboBox combo;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
dogedice frame = new dogedice();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public dogedice() {
setTitle("DogeDice Bot");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.WEST);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0};
gbl_panel.rowHeights = new int[]{0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0};
gbl_panel.rowWeights = new double[]{0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
//Every new Label however needs every part that says "user" or on the Password: "pass" changed to something unique.
JLabel userTag = new JLabel("Username:");
GridBagConstraints gbc_userTag = new GridBagConstraints();
gbc_userTag.insets = new Insets(0, 0, 0, 5);
gbc_userTag.anchor = GridBagConstraints.EAST;
gbc_userTag.gridx = 0;//Here are your x + y coords
gbc_userTag.gridy = 0;//Adding to x moves left, adding to y moves down
panel.add(userTag, gbc_userTag);
//Every new textfield needs only the * part to change for it to be valid. (gbc_* =)
textField = new JTextField();
GridBagConstraints gbc_Username = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel startTag = new JLabel("Starting Bid:");
GridBagConstraints gbc_startTag = new GridBagConstraints();
gbc_startTag.insets = new Insets(0, 0, 0, 5);
gbc_startTag.anchor = GridBagConstraints.EAST;
gbc_startTag.gridx = 0;
gbc_startTag.gridy = 2;
panel.add(startTag, gbc_startTag);
textField = new JTextField();
GridBagConstraints gbc_StartBid = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 2;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel multTag = new JLabel("Multiplier:");
GridBagConstraints gbc_multTag = new GridBagConstraints();
gbc_multTag.insets = new Insets(0, 0, 0, 5);
gbc_multTag.anchor = GridBagConstraints.EAST;
gbc_multTag.gridx = 0;
gbc_multTag.gridy = 3;
panel.add(multTag, gbc_multTag);
textField = new JTextField();
GridBagConstraints gbc_Multiplier = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 3;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel minTag = new JLabel("Min Remaining:");
GridBagConstraints gbc_minTag = new GridBagConstraints();
gbc_minTag.insets = new Insets(0, 0, 0, 5);
gbc_minTag.anchor = GridBagConstraints.EAST;
gbc_minTag.gridx = 0;
gbc_minTag.gridy = 4;
panel.add(minTag, gbc_minTag);
textField = new JTextField();
GridBagConstraints gbc_MinRemaining = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 4;
panel.add(textField, gbc_textField);
textField.setColumns(10);
textField = new JTextField();
GridBagConstraints gbc_Password = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 1;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel passTag = new JLabel("Password:");
GridBagConstraints gbc_passTag = new GridBagConstraints();
gbc_passTag.insets = new Insets(0, 0, 0, 5);
gbc_passTag.anchor = GridBagConstraints.EAST;
gbc_passTag.gridx = 0;
gbc_passTag.gridy = 1;
panel.add(passTag, gbc_passTag);
textField = new JTextField();
GridBagConstraints gbc_Odds = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 5;
panel.add(textField, gbc_textField);
textField.setColumns(10);
JLabel oddsTag = new JLabel("Odds %:");
GridBagConstraints gbc_oddsTag = new GridBagConstraints();
gbc_oddsTag.insets = new Insets(0, 0, 0, 5);
gbc_oddsTag.anchor = GridBagConstraints.EAST;
gbc_oddsTag.gridx = 0;
gbc_oddsTag.gridy = 5;
panel.add(oddsTag, gbc_oddsTag);
textField = new JTextField();
GridBagConstraints gbc_ComboBox = new GridBagConstraints();
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 6;
panel.add(textField, gbc_textField);
textField.setColumns(10);
//This is the Combo Box
combo = new JComboBox<String>(new String[]{"BTC","LTC","PPC","NMC","XPM","FTC","ANC","DOGE","NXT"});
combo.addActionListener(this);
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.fill = GridBagConstraints.HORIZONTAL;
gbc_list.gridx = 1;
gbc_list.gridy = 7;
panel.add(combo, gbc_list);
JLabel maxTag = new JLabel("MaxBet:");
GridBagConstraints gbc_maxTag = new GridBagConstraints();
gbc_maxTag.insets = new Insets(0, 0, 0, 5);
gbc_maxTag.anchor = GridBagConstraints.EAST;
gbc_maxTag.gridx = 0;
gbc_maxTag.gridy = 6;
panel.add(maxTag, gbc_maxTag);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.SOUTH);
panel_1.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
JButton btnConfirm = new JButton("Turn Up");
panel_1.add(btnConfirm);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea("Current Balance");
textArea.setColumns(1);
scrollPane.setViewportView(textArea);
JScrollPane scrollPanel = new JScrollPane();//This will hold the information the bot sends over such as win/loose or error
contentPane.add(scrollPane, BorderLayout.CENTER);
JTextArea textAreal = new JTextArea("Input bot information here...");
textArea.setColumns(20);
scrollPane.setViewportView(textArea);
pack();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == combo) {
System.out.println(combo.getSelectedIndex()+1);
}
}
}
It's quite straightforward to add an ActionListener to a JButton.
// ...
btnConfirm = new JButton("Turn Up");
btnConfirm.addActionListener(this);
panel_1.add(btnConfirm);
// ...
Because you'll want to know when the button is triggering the callback, like so:
private JButton btnConfirm;
This way, you'll be able to tell when it's that button that triggered the actionListener() method:
if (event.getSource() == btnConfirm) {
// Handle "Turn Up" button press here
}
Start by taking a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener
Essentially you need to register an ActionListener with your button...
There are a number of ways you might be able to achieve this...
You Could
Use the more traditional, purpose class...
public class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent evt) {
if ("Turn Up".evt.getActionCommand()) {
// Handle Turn Up...
}
}
}
In this context, you'll be required to provide a reference to the component you want to modify so that the ActionHandler can interact with it, personally, this is best done via an interface, but that's just me...
public class ActionHandler implements ActionListener {
private dogedice dice;
public ActionHandler(dogedice dice) {
this.dice = dice;
}
public void actionPerformed(ActionEvent evt) {
//...
}
}
The benefit of this is you can plug an play the action handler, changing what the action does depending on your needs. If you use an interface instead of an implementation reference, you further decouple the action from the program
You Could
Use use an anonymous class
btnConfirm = new JButton("Turn Up");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// handle turn up action...
}
});
The benefit to this is, you don't end up with "another" class, the ActionListener can reference all the internal fields of the parent class and, because you've attached it directly, you can assume that the only thing that is going to generate the ActionEvent is the btnConfirm button.
The downside is you lose the flexibility to change how the action is handled without physically modifying the code
You Could
Take advantage of the Actions API, this is a little like the first option, in that you (should normally) create another class specifically designed to handle the "Turn Up" event, but these are self contained entities. That is, they carry all the information required to configure the UI element and perform the required action when triggered.
This is really good where the action may be repeated in the UI via menus, buttons or key strokes

Debugging code I have with 2 classes and a JFrame that holds 4 JPanels

I am looking for help to debug this program that I have written there are, no errors but the goal is to create a frame with three panels inside of it each of which has a titled border. I am having difficulty because my prompt requires of me to make 2 constructors and 2 classes so when I call the DailySales class in main I feel it doesn't include the other class.
So basically how can I make the panels show up while still keeping two classes and two constructors and how would I add titled borders to each of the JPanels, sorry but I'm having difficulty with the Oracle tutorial.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class DailySales extends JPanel {
final int lPizzaPrice = 12;
final int mPizzaPrice = 9;
final int sPizzaPrice = 6;
final int bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza;
String mPizza;
String sPizza;
String bSticks;
int largePizza;
int mediumPizza;
int smallPizza;
int breadSticks;
int totalLargePizza;
int totalMediumPizza;
int totalSmallPizza;
int totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
private FlowLayout dailyFlow;
private Container container;
JLabel lPizzaLabel = new JLabel("Large Pizza");//creating labels
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");//Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(dailyFlow);
subPanel1.add(lPizzaLabel, largeField);
subPanel1.add(mPizzaLabel, mediumField);
subPanel1.add(sPizzaLabel, smallField);
subPanel1.add(bSticksLabel, breadField);
subPanel1.setSize(100, 100);
subPanel2.setLayout(dailyFlow);
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel3.setLayout(dailyFlow);
subPanel3.add(totalSalesLabel, totalSalesField);
subPanel3.add(totalTaxLabel, totalTaxField);
subPanel3.add(netSalesLabel, netSalesField);
subPanel3.add(dailyCostLabel, dailyCostField);
subPanel3.add(profitLabel, profitField);
top.setBackground(Color.red);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
totalSalesField.setEditable(false);//making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() //creating a constructor
{
/**
* The constructor with all the layout informations and operators
*
*
* Also adding all labels, textfields, and buttons to frame. making the
* total field uneditable
*/
JFrame frame = new JFrame();
frame.add(subPanel1);
frame.add(subPanel2);
frame.add(subPanel3);
frame.add(top);
frame.setSize(600, 450);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {//initial button removes all entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {//update button calculates all the inputs and displays everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice * largePizza);
totalMediumPizza = (mPizzaPrice * mediumPizza);
totalSmallPizza = (sPizzaPrice * smallPizza);
totalBreadSticks = (bSticksPrice * breadSticks);
totalLargeField.setText("" + totalLargePizza);
totalMediumField.setText("" + totalMediumPizza);
totalSmallField.setText("" + totalSmallPizza);
totalBreadField.setText("" + totalBreadSticks);
totalSales = (totalLargePizza + totalMediumPizza + totalSmallPizza + totalBreadSticks);
totalTax = (totalSales * tax);
netSales = (totalSales - totalTax);
profit = (netSales - dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit > 0) {
profitLabel.setText("Profit of ");
} else if (profit < 0) {
profitLabel.setText("Loss of ");
} else if (profit == 0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {//close button closes the program when clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}
There's still a lot you can do to make this better, but this works.
public class DailySales extends JPanel {
final int lPizzaPrice = 12, mPizzaPrice = 9, sPizzaPrice = 6, bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza, mPizza, sPizza, bSticks;
int largePizza, mediumPizza, smallPizza, breadSticks, totalLargePizza,
totalMediumPizza, totalSmallPizza, totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
JLabel lPizzaLabel = new JLabel("Large Pizza");
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");// Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(new GridLayout(4, 2));
subPanel1.add(lPizzaLabel);
subPanel1.add(largeField);
subPanel1.add(mPizzaLabel);
subPanel1.add(mediumField);
subPanel1.add(sPizzaLabel);
subPanel1.add(smallField);
subPanel1.add(bSticksLabel);
subPanel1.add(breadField);
subPanel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
// subPanel2.setLayout(new BoxLayout(subPanel2, BoxLayout.Y_AXIS)); // Same as next line
subPanel2.setLayout(new GridLayout(4, 1));
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
subPanel3.setLayout(new GridLayout(5, 2));
subPanel3.add(totalSalesLabel);
subPanel3.add(totalSalesField);
subPanel3.add(totalTaxLabel);
subPanel3.add(totalTaxField);
subPanel3.add(netSalesLabel);
subPanel3.add(netSalesField);
subPanel3.add(dailyCostLabel);
subPanel3.add(dailyCostField);
subPanel3.add(profitLabel);
subPanel3.add(profitField);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
top.setBackground(Color.YELLOW);
totalSalesField.setEditable(false);// making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() // creating a constructor
{
/**
* The constructor with all the layout informations and operators Also
* adding all labels, textfields, and buttons to frame. making the total
* field uneditable
*/
new GUI();
JPanel mainPanel = new JPanel(new GridLayout(2, 2));
mainPanel.add(subPanel1);
mainPanel.add(subPanel2);
mainPanel.add(subPanel3);
JPanel buttonPanel = new JPanel();
buttonPanel.add(clearButton);
buttonPanel.add(calculateButton);
buttonPanel.add(exitButton);
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(top, BorderLayout.PAGE_START);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
frame.setSize(600, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {// initial button
// removes all
// entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {// update button
// calculates
// all the
// inputs and
// displays
// everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice*largePizza);
totalMediumPizza = (mPizzaPrice*mediumPizza);
totalSmallPizza = (sPizzaPrice*smallPizza);
totalBreadSticks = (bSticksPrice*breadSticks);
totalLargeField.setText(""+totalLargePizza);
totalMediumField.setText(""+totalMediumPizza);
totalSmallField.setText(""+totalSmallPizza);
totalBreadField.setText(""+totalBreadSticks);
totalSales = (totalLargePizza+totalMediumPizza+totalSmallPizza+totalBreadSticks);
totalTax = (totalSales*tax);
netSales = (totalSales-totalTax);
profit = (netSales-dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit>0) {
profitLabel.setText("Profit of ");
} else if (profit<0) {
profitLabel.setText("Loss of ");
} else if (profit==0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {// close button
// closes the
// program when
// clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}

Categories