I am working on an app which will get info from the user through the buttons and text frames in the MyPanel class. So far that part works. Now I want to display the courses-infos the user entered in the DisplayTable panel. I want it to update each time the add course button in the MyPanel class is pressed. I tried adding a function to DisplayTable to add a label each time the button is pressed but I could not get it to work since one is static and one is not. Any ideas on how to do that?(Or any tips on how to improve the app in general :) )
Class Main
public class Main {
//TODO
// PREVENT TYPE MISMATCH IN TEXT FIELDS
// DISPLAY A TABLE OF COURSE NAMES - COURSE CREDITS - COURSE NAME AND THE GPA
public static void main(String[] args) {
new MyFrame();
}
}
Class MyFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyFrame extends JFrame{
MainPanel mainPanel;
MyFrame(){
mainPanel = new MainPanel();
this.add(mainPanel);
this.setTitle("GPA Calculator");
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500,500);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
}
Class MainPanel
import javax.swing.*;
public class MainPanel extends JPanel {
MyPanel myPanel = new MyPanel();
DisplayPanel displayPanel = new DisplayPanel();
MainPanel() {
this.add(myPanel);
this.add(displayPanel);
}
}
Class DisplayPanel
import javax.swing.*;
import java.awt.*;
public class DisplayPanel extends JPanel {
static JLabel addLabel = new JLabel();
public DisplayPanel() {
this.setPreferredSize(new Dimension(500, 500));
this.setBackground(new Color(0xEED2CC));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
}
public static void addElements(String courseName, int courseCredits, double courseGrade) {
addLabel.setText(courseName + " " + courseCredits + " " + courseGrade);
addLabel.setText("");
}
}
Class MyPanel
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;
public class MyPanel extends JPanel implements ActionListener{
List<String> courseNames;
List<Integer> courseCredits;
List<Double> courseGrades;
Thread thread;
JLabel nameLabel;
JLabel creditLabel;
JLabel gradeLabel;
JTextField nameField;
JTextField creditField;
JTextField gradeField;
JButton calculateButton;
JButton addCourseButton;
JButton resetButton;
JLabel message;
double result = 0;
int tempInt = 0;
double tempDouble = 0;
MyPanel() {
message = new JLabel();
message.setHorizontalAlignment(JLabel.CENTER);
message.setFont(new Font("Helvetica Neue", Font.PLAIN, 35));
message.setForeground(new Color(0xA1683A));
message.setAlignmentX(JLabel.CENTER_ALIGNMENT);
courseNames = new ArrayList();
courseCredits = new ArrayList();
courseGrades = new ArrayList();
nameLabel = new JLabel();
nameLabel.setHorizontalAlignment(JLabel.CENTER);
nameLabel.setText("Course Name");
nameLabel.setFont(new Font("Helvetica Neue", Font.PLAIN, 25));
nameLabel.setForeground(new Color(0xA1683A));
nameLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
nameField = new JTextField();
nameField.setPreferredSize(new Dimension(300,30));
nameField.setMaximumSize(nameField.getPreferredSize());
creditLabel = new JLabel();
creditLabel.setHorizontalAlignment(JLabel.CENTER);
creditLabel.setText("Course Credits(ECTS)");
creditLabel.setFont(new Font("Helvetica Neue", Font.PLAIN, 25));
creditLabel.setForeground(new Color(0xA1683A));
creditLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
creditField = new JTextField();
creditField.setPreferredSize(new Dimension(300,30));
creditField.setMaximumSize(creditField.getPreferredSize());
gradeLabel = new JLabel();
gradeLabel.setHorizontalAlignment(JLabel.CENTER);
gradeLabel.setText("Your Grade");
gradeLabel.setFont(new Font("Helvetica Neue", Font.PLAIN, 25));
gradeLabel.setForeground(new Color(0xA1683A));
gradeLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
gradeField = new JTextField();
gradeField.setPreferredSize(new Dimension(300,30));
gradeField.setMaximumSize(gradeField.getPreferredSize());
resetButton = new JButton("Reset");
resetButton.setAlignmentX(JLabel.CENTER_ALIGNMENT);
resetButton.addActionListener(this);
addCourseButton = new JButton("Add Course");
addCourseButton.setAlignmentX(JLabel.CENTER_ALIGNMENT);
addCourseButton.addActionListener(this);
calculateButton = new JButton("Calculate GPA");
calculateButton.setAlignmentX(JLabel.CENTER_ALIGNMENT);
calculateButton.addActionListener(this);
//spacing and adding the elements
this.add(Box.createRigidArea(new Dimension(0,20)));
this.add(nameLabel);
this.add(Box.createRigidArea(new Dimension(0,10)));
this.add(nameField);
this.add(Box.createRigidArea(new Dimension(0,20)));
this.add(creditLabel);
this.add(Box.createRigidArea(new Dimension(0,10)));
this.add(creditField);
this.add(Box.createRigidArea(new Dimension(0,20)));
this.add(gradeLabel);
this.add(Box.createRigidArea(new Dimension(0,10)));
this.add(gradeField);
this.add(Box.createRigidArea(new Dimension(0,20)));
this.add(addCourseButton);
this.add(Box.createRigidArea(new Dimension(0,5)));
this.add(calculateButton);
this.add(Box.createRigidArea(new Dimension(0,5)));
this.add(resetButton);
this.add(Box.createRigidArea(new Dimension(0,30)));
this.add(message);
this.setPreferredSize(new Dimension(500, 500));
this.setBackground(new Color(0xEED2CC));
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
}
//calculate the GPA
public double calculateGPA(){
for (Integer courseCredit : courseCredits) {
tempInt += courseCredit;
}
for(int i = 0; i<courseGrades.size();i++){
tempDouble += courseGrades.get(i) * courseCredits.get(i);
}
return tempDouble/tempInt;
}
//create labels to display on the table
public void createLabel(){
}
#Override
public void actionPerformed(ActionEvent e) throws NumberFormatException {
if(e.getSource().equals(addCourseButton)){
//add items from the textFields to lists
String tempText = nameField.getText();
int tempCredit = Integer.parseInt(creditField.getText());
double tempGrade = Double.parseDouble(gradeField.getText());
courseNames.add(tempText);
courseCredits.add(tempCredit);
courseGrades.add(tempGrade);
//set textFields to empty
nameField.setText("");
creditField.setText("");
gradeField.setText("");
//display a message for 3 seconds
thread = new Thread();
thread.start();
message.setText("Course Added Successfully!");
Timer timer = new Timer(3000, a -> message.setText(null));
timer.setRepeats(false);
timer.start();
//add to table panel
DisplayPanel.addElements(){
}
}
//calculate the GPA, initialize the display panel
//to display the courses names-credits-results and the gpa
//as a table
if(e.getSource().equals(calculateButton)){
result = calculateGPA();
message.setText(result + "");
}
//clear the lists,text fields and the message
//get rid of the table panel
if(e.getSource().equals(resetButton)){
courseNames.clear();
courseGrades.clear();
courseCredits.clear();
nameField.setText("");
creditField.setText("");
gradeField.setText("");
message.setText(null);
}
}
}
You appear to have used static without need.
static JLabel addLabel = new JLabel();
Make the above non-static, (ideally also make private)
public static void addElements
Make the above non static also, rename to something like setLabelText
DisplayPanel displayPanel = new DisplayPanel();
MyPanel myPanel = new MyPanel(displayPanel);
As shown above, pass displayPanel as a parameter to myPanel.
Obviously in MyPanel, you would have one more instance variable:
DisplayPanel displayPanel;
which would be initialized in the constructor, using the constructor argument.
In MyPanel#actionPerformed, instead of:
//add to table panel
DisplayPanel.addElements(){
}
do:
displayPanel.addElements(....);
or rather
displayPanel.setLabelText(...);
invoke the DisplayPanel#setLabelText method on grade calculation and resetting also.
Also invoke the
Finally, remove line:
addLabel.setText("");
If you want DisplayPanel, why then also have the following?
public void createLabel(){
Related
So, I'm brand spankin' new to programming, so thanks in advance for your help. I'm trying to put this base 2 to base 10/base 10 to base 2 calculator I have made into a GUI. For the life of me I can't figure out how to nicely format it. I'm trying to make it look like the following: The two radio buttons on top, the input textfield bellow those, the convert button bellow that, the output field bellow that, and the clear button bellow that. Any ideas on how I can accomplish this?
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUI extends JFrame implements ActionListener
{
private JTextField input;
private JTextField output;
private JRadioButton base2Button;
private JRadioButton base10Button;
private JButton convert;
private JButton clear;
private Container canvas = getContentPane();
private Color GRAY;
public GUI()
{
this.setTitle("Base 10-2 calc");
this.setLayout(new FlowLayout(FlowLayout.LEFT));
//this.setLayout(new GridLayout(2,2));
base2Button = new JRadioButton( "Convert to base 2");
base10Button = new JRadioButton( "Convert to base 10");
ButtonGroup radioGroup = new ButtonGroup();
radioGroup.add(base2Button);
radioGroup.add(base10Button);
JPanel radioButtonsPanel = new JPanel();
radioButtonsPanel.setLayout( new FlowLayout(FlowLayout.LEFT) );
radioButtonsPanel.add(base2Button);
radioButtonsPanel.add(base10Button);
canvas.add(radioButtonsPanel);
base2Button.setSelected( true );
base10Button.setSelected( true );
input = new JTextField(18);
//input = new JFormattedTextField(20);
canvas.add(input);
output = new JTextField(18);
//output = new JFormattedTextField(20);
canvas.add(output);
convert = new JButton("Convert!");
convert.addActionListener(this);
canvas.add(convert);
clear = new JButton("Clear");
clear.addActionListener(this);
canvas.add(clear);
output.setBackground(GRAY);
output.setEditable(false);
this.setSize(300, 200);
this.setVisible(true);
this.setLocation(99, 101);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
GUI app = new GUI();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if(s.equals("Convert!"))
{
String numS = input.getText();
int numI = Integer.parseInt(numS);
if(base2Button.isSelected())
{
output.setText(Integer.toBinaryString(Integer.valueOf(numI)));
}
if(base10Button.isSelected())
{
output.setText("" + Integer.valueOf(numS,2));
}
}
if(s.equals("Clear"))
{
input.setText("");
output.setText("");
}
}
}
For a simple layout, you could use a GridLayout with one column and then use a bunch of child panels with FlowLayout which align the components based on the available space in a single row. If you want more control, I'd suggest learning about the GridBagLayout manager which is a more flexible version of GridLayout.
public class ExampleGUI {
public ExampleGUI() {
init();
}
private void init() {
JFrame frame = new JFrame();
// Set the frame's layout to a GridLayout with one column
frame.setLayout(new GridLayout(0, 1));
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Child panels, each with FlowLayout(), which aligns the components
// in a single row, until there's no more space
JPanel radioButtonPanel = new JPanel(new FlowLayout());
JRadioButton button1 = new JRadioButton("Option 1");
JRadioButton button2 = new JRadioButton("Option 2");
radioButtonPanel.add(button1);
radioButtonPanel.add(button2);
JPanel inputPanel = new JPanel(new FlowLayout());
JLabel inputLabel = new JLabel("Input: ");
JTextField textField1 = new JTextField(15);
inputPanel.add(inputLabel);
inputPanel.add(textField1);
JPanel convertPanel = new JPanel(new FlowLayout());
JButton convertButton = new JButton("Convert");
convertPanel.add(convertButton);
JPanel outputPanel = new JPanel(new FlowLayout());
JLabel outputLabel = new JLabel("Output: ");
JTextField textField2 = new JTextField(15);
outputPanel.add(outputLabel);
outputPanel.add(textField2);
// Add the child panels to the frame, in order, which all get placed
// in a single column
frame.add(radioButtonPanel);
frame.add(inputPanel);
frame.add(convertPanel);
frame.add(outputPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
ExampleGUI example = new ExampleGUI();
}
}
The end result:
I have a multi-class project involving some basic Java GUI. I am to create a loan calculator using 10 classes (6 of which are JPanel subclasses, a calculation class, a CombinedPanels class, a LoanCalculatorGUI class which creates instances of the CombinedPanels class and calculation class, and a driver). I have to make a reset button in one of the JPanel subclasses (ActionButtons) change a private JLabel in a different JPanel subclass (PaymentInformation). Here is the ActionButtons class:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class ActionButtons extends JPanel{
private JButton calc, reset, exit;
private JPanel actionButtons;
public ActionButtons(){
PaymentInformation pi = new PaymentInformation();
actionButtons = new JPanel(new GridLayout(1, 3, 20, 20));
calc = new JButton("Calculate");
reset = new JButton("Reset");
exit = new JButton("Exit");
actionButtons.add(calc);
actionButtons.add(reset);
actionButtons.add(exit);
actionButtons.setBorder(BorderFactory.createTitledBorder("Action Buttons"));
//Add ActionListeners
calc.addActionListener(new ButtonListener());
reset.addActionListener(new ButtonListener());
exit.addActionListener(new ButtonListener());
}
public JPanel getGUI(){
return actionButtons;
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
PaymentInformation pi = new PaymentInformation();
if(e.getActionCommand().equals("Exit")){
System.exit(0);
}
if(e.getActionCommand().equals("Reset")){
pi.changeValues("0.0");
}
if(e.getActionCommand().equals("Calculate")){
//TODO DO CALCULATIONS
}
}
}
}
And the PaymentInformation class:
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class PaymentInformation extends JPanel{
//Declare variables
private JPanel payInfo;
private JLabel loanAmt, monthPay, totalPay, loanVal, monthVal, totalVal;
public PaymentInformation(){
//Give panel layout
payInfo = new JPanel(new GridLayout(3, 2));
//Give titles, set alignment
loanAmt = new JLabel("Total Loan Amount: $", JLabel.LEFT);
monthPay = new JLabel("Monthly Payment: $", JLabel.LEFT);
totalPay = new JLabel("Total Payment: $", JLabel.LEFT);
loanVal = new JLabel("5.0", JLabel.RIGHT);
monthVal = new JLabel("0.0", JLabel.RIGHT);
totalVal = new JLabel("0.0", JLabel.RIGHT);
//Add stuff to JPanel
payInfo.add(loanAmt);
payInfo.add(loanVal);
payInfo.add(monthPay);
payInfo.add(monthVal);
payInfo.add(totalPay);
payInfo.add(totalVal);
//Set border
payInfo.setBorder(BorderFactory.createTitledBorder("Payment Information"));
}
//Method to get the JPanel
public JPanel getGUI(){
return payInfo;
}
public void changeValues(String val){
loanVal.setText(val);
}
}
I'm trying to use the setValue method in PaymentInformation to change the text of the JLabel, but it stays the same (at "5.0") when the reset button is clicked. I'm not sure if this is needed, but the CombinedPanels class (takes all the JLabel subclasses and puts them into a JFrame) is here:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class CombinedPanels extends JFrame{
public CombinedPanels(){
setTitle("Auto Loan Calculator");
setSize(700,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel center = new JPanel(new GridLayout(2, 2, 20, 20));
//Add other classes to this layout
TitleBar tb = new TitleBar();
add(tb.getGUI(), BorderLayout.NORTH);
ActionButtons ab = new ActionButtons();
add(ab.getGUI(), BorderLayout.SOUTH);
//Add center JPanel to the center of BorderLayout
add(center, BorderLayout.CENTER);
//Continue with adding rest of classes to center JPanel
PaymentInformation pi = new PaymentInformation();
center.add(pi.getGUI());
LoanTerm lt = new LoanTerm();
center.add(lt.getGUI());
FinancingInformation fi = new FinancingInformation();
center.add(fi.getGUI());
PriceWithOptions pwo = new PriceWithOptions();
center.add(pwo.getGUI());
}
}
Lastly, here is an image of the GUI: .
It stays the same when reset is hit, even though the "5.0" JLabel should be changed to "0.0". The exit button, however, is functional.
Sorry for the wall of text, but this problem is driving me crazy. Any help or explanation is much appreciated. Thanks in advance.
You have 3 seperate instances of PaymentInformation. First one in the CombinedPanels class (the one that is displayed), one in the ActionButtons class and one in the ButtonListener class. You only change the values of the last one (which is invisible).
So one solution would be to pass the (visible) pi of the CombinedPanels class to the ActionButtons class and call changeValues() on that instance and on no other.
Relevant code (changed):
public CombinedPanels() {
setTitle("Auto Loan Calculator");
setSize(700, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel center = new JPanel(new GridLayout(2, 2, 20, 20));
// Add other classes to this layout
PaymentInformation pi = new PaymentInformation();
ActionButtons ab = new ActionButtons(pi);
add(ab.getGUI(), BorderLayout.SOUTH);
// Add center JPanel to the center of BorderLayout
add(center, BorderLayout.CENTER);
// Continue with adding rest of classes to center JPanel
center.add(pi.getGUI());
setVisible(true);
}
public class ActionButtons extends JPanel {
private JButton calc, reset, exit;
private JPanel actionButtons;
PaymentInformation pi;
public ActionButtons(PaymentInformation pi) {
this.pi = pi;
actionButtons = new JPanel(new GridLayout(1, 3, 20, 20));
calc = new JButton("Calculate");
reset = new JButton("Reset");
exit = new JButton("Exit");
actionButtons.add(calc);
actionButtons.add(reset);
actionButtons.add(exit);
actionButtons.setBorder(BorderFactory.createTitledBorder("Action Buttons"));
// Add ActionListeners
calc.addActionListener(new ButtonListener());
reset.addActionListener(new ButtonListener());
exit.addActionListener(new ButtonListener());
}
public JPanel getGUI() {
return actionButtons;
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Exit")) {
System.exit(0);
}
if (e.getActionCommand().equals("Reset")) {
pi.changeValues("0.0");
}
if (e.getActionCommand().equals("Calculate")) {
// TODO DO CALCULATIONS
}
}
}
}
Try this
public void changeValues(String val){
loanVal=new JLabel(val, JLabel.RIGHT);
}
I want to create an input JFrame where the program reads three fields (model, week and plan), and after inserting one line the user can choose to input new values on a different row, this is done pressing a JLabel with a image add icon.
My expectation is to be able to add a new JPanel (called body in the subclass) right under the last one (JPanel lastContent global variable), and to be able to remove or add new ones as the user needs.
Below is my code so far:
package marquesina;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.jdesktop.swingx.HorizontalLayout;
import org.jdesktop.swingx.VerticalLayout;
public class JModificaciones extends Container {
private JPanel lastContent;
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("DEMO");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up the content pane.
JModificaciones mods = new JModificaciones();
frame.setContentPane(mods);
//Display the window.
frame.pack();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(
dim.width / 2 - frame.getSize().width / 2,
dim.height / 2 - frame.getSize().height / 2);
frame.setVisible(true);
});
}
public JModificaciones() {
initComponents();
System.out.println("New Panel Created");
}
private void initComponents() {
JPanel jHeader = new JPanel();
JLabel jLMod = new JLabel();
JLabel jLSem = new JLabel();
JLabel jLPlan = new JLabel();
JPanel jFooter = new JPanel();
JButton jGuardar = new JButton();
JButton jCancelar = new JButton();
setLayout(new VerticalLayout(10));
//HEADER
jHeader.setLayout(new HorizontalLayout());
jLMod.setText("Model");
jHeader.add(jLMod);
jLWeek.setText("Week");
jHeader.add(jLWeek);
jLPlan.setText("Plan");
jHeader.add(jLPlan);
add(jHeader);
//CONTENT
add(new jContent());
//FOOTER
jGuardar.setText("Save");
jFooter.add(jGuardar);
jCancelar.setText("Cancel");
jFooter.add(jCancel);
add(jFooter);
}
public class jContent extends JPanel {
JLabel jAdd = new javax.swing.JLabel();
JLabel jDelete = new javax.swing.JLabel();
public jContent() {
JPanel body = new JPanel(new HorizontalLayout());
JTextField jModel = new JTextField();
JTextField jWeek = new JTextField();
JTextField jPlan = new JTextField();
body.setLayout(new org.jdesktop.swingx.HorizontalLayout());
jModel.setPreferredSize(new java.awt.Dimension(100, 28));
body.add(jModel);
jWeek.setPreferredSize(new java.awt.Dimension(100, 28));
body.add(jWeek);
jPlan.setPreferredSize(new java.awt.Dimension(100, 28));
body.add(jPlan);
jAdd.setIcon(
new javax.swing.ImageIcon(
getClass().getResource("add.png")));
jAdd.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
}
});
body.add(jAdd);
jDelete.setIcon(
new javax.swing.ImageIcon(
getClass().getResource("delete.png")));
jDelete.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
remove(lastContent);
}
});
body.add(jDelete);
add(body);
}
}
}
However I'm not able to add a new JPanel (which I want to create when the user clicks on the jAdd JLabel), I can't come up with a way to reference the JPanel where I want to put my new Components and using just add() or remove() as I do in the above code just reference the MouseListener, not the JPanel created in the sublcass...
I was wondering how I would move my buttons to the bottom of the frame/window.
What I have now is this:
And what I want it to look like is this:
Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Font;
public class checkbook{
static JButton Button[] = new JButton[8];
JLabel begin, accountName, balance;
JFrame frame;
JPanel jpanel, jpanel1;
Container contentPane;
private JTextField textAccount, textBalance;
public static void main(String[] args){
checkbook checkbook = new checkbook();
checkbook.startFrame();
}
checkbook(){
frame = new JFrame("Checkbook");
}
public void startFrame(){
String bottomButtons[] = {
"Create a New Account", "Load Trans from a file", "Add New Transactions", "Search Transactions",
"Sort Transactions", "View/Delete Transactions", "Backup Transactions", "Exit"
};
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
Font beginFont = new Font("Arial", Font.PLAIN + Font.BOLD, 22);
textAccount = new JTextField(" ", 15);
textBalance = new JTextField("0.0", 15);
begin = new JLabel("Use The Buttons below To Manage Transactions");
begin.setFont(beginFont);
contentPane.add(begin);
//Container contentPane1 = frame.getContentPane();
//contentPane1.setLayout(new FlowLayout());
JPanel jpanel = new JPanel();
accountName = new JLabel ("Account Name: ");
jpanel.add(accountName);
jpanel.add(textAccount);
balance = new JLabel ("Balance: ");
jpanel.add(balance);
jpanel.add(textBalance);
JPanel jpanel1 = new JPanel();
jpanel1.setLayout(new GridLayout(2,4));
for(int i = 0; i < 8; i++){
Button[i] = new JButton(bottomButtons[i]);
jpanel1.add(Button[i]);
//Button[i].addActionListener(AL);
}
frame.pack();
frame.setSize(800, 300);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(jpanel);
frame.add(jpanel1);
}
}
So I was wondering what would I do to move the buttons down to the bottom. Would I have to use a BorderLayout and use BorderLayout.SOUTH etc or is there a way to do this with the GridLayout I already have. If I have to use the BorderLayout how would I keep my buttons in order (2 rows, 4 columns).
Would I have to use a BorderLayout and use BorderLayout.SOUTH
Yes, but the best answer is for you to try it and see what happens. Why don't you?
If I have to use the BorderLayout how would I keep my buttons in order(2 rows, 4 columns).
Nest JPanels. Put the buttons in a GridLayout using JPanel, and place that JPanel BorderLayout.SOUTH, or better, BorderLayout.PAGE_END
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class NestedPanels extends JPanel {
private static final String TITLE_TEXT = "Use The Buttons Below To Manage Transactions";
private static final String[] BTN_TEXTS = { "Create a New Account",
"Load a Trans from a File", "Add New Transactions",
"Search Transactions", "Sort Transactions",
"View/Delete Transactions", "Backup Transaction", "Exit" };
private static final int TITLE_POINTS = 24;
public NestedPanels() {
JLabel titleLabel = new JLabel(TITLE_TEXT, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD,
TITLE_POINTS));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel); // put it in a JPanel so it will expand to fill BoxLayout
JPanel accountBalancePanel = new JPanel();
accountBalancePanel.add(new JLabel("Account Name:"));
accountBalancePanel.add(new JTextField(10));
accountBalancePanel.add(Box.createHorizontalStrut(20));
accountBalancePanel.add(new JLabel("Balance:"));
accountBalancePanel.add(new JTextField(10));
JPanel northPanel = new JPanel();
northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.PAGE_AXIS));
northPanel.add(titlePanel);
northPanel.add(accountBalancePanel);
JPanel southBtnPanel = new JPanel(new GridLayout(2, 4, 1, 1));
for (String btnText : BTN_TEXTS) {
southBtnPanel.add(new JButton(btnText));
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(Box.createRigidArea(new Dimension(400, 400))); // just an empty placeholder
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
NestedPanels mainPanel = new NestedPanels();
JFrame frame = new JFrame("Nested Panels Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which displays as:
So basically the program will work like this. The first window comes up and asks with 2 buttons whether you want to continue the program or exit the program. if you choose to continue then the program continues on to whatever is in the if statement.
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
import java.io.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.*;
public class Herons extends JFrame implements ActionListener {
public static JTextField a;
public static JTextField b;
public static JTextField c;
public static JFrame main = new JFrame("Herons Formula");
public static JPanel myPanel = new JPanel(new GridLayout (0,1));
public static void main(String args[]){
//splashscr();
Herons object = new Herons();
}
Herons(){
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel myPanel1 = new JPanel(new GridBagLayout());
myPanel.setPreferredSize(new Dimension(515,125));
JLabel lab1 = new JLabel(
("Herons Formula uses the lenghts of the sides of a triangle to calculate its area."));
main.add(myPanel);
lab1.setHorizontalAlignment(JLabel.CENTER);
myPanel.add(lab1);
JButton button1 = new JButton("Use the Formula!");
button1.setPreferredSize(new Dimension(20, 20));
JButton button2 = new JButton("Exit the program");
myPanel.add(button1);
myPanel.add(button2);
button1.addActionListener(this);
button2.addActionListener(this);
main.pack();
main.setVisible(true);
//Not really sure what to do with this
if (myPanel1.hasBeenDisposed()){
//JFrame main = new JFrame("Herons Formula");
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JPanel myPanel = new JPanel(new GridLayout (0,1));
//JPanel pane = new JPanel(new GridLayout(0,1));
myPanel.setPreferredSize(new Dimension(325,275));
a = new JTextField(3);
b = new JTextField(3);
c = new JTextField(3);
JButton find = new JButton("Calculate!");
main.add(myPanel);
myPanel.add(new JLabel ("Input the lengh of each side of the triangle"));
main.add(myPanel);
myPanel.add(new JLabel ("Side A:"));
myPanel.add(a);
myPanel.add(new JLabel ("Side B:"));
myPanel.add(b);
myPanel.add(new JLabel ("Side C:"));
myPanel.add(c);
myPanel.add(find);
//find.setActionCommand("Calculate!");
find.addActionListener(this);
main.pack();
main.setVisible(true);
}
}
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
//System.out.println("Action command for pressed button: " + actionCommand);
if (actionCommand == "Calculate!") {
main.setVisible(false);
myPanel.setVisible(false);
main.dispose();
double aaa = Double.parseDouble(a.getText());
double bbb = Double.parseDouble(b.getText());
double ccc = Double.parseDouble(c.getText());
double s = 0.5 * (aaa + bbb + ccc);
double area = Math.sqrt(s*(s-aaa)*(s-bbb)*(s-ccc));
area = (int)(area*10000+.5)/10000.0;
if (area == 0){
area = 0;
}
JOptionPane.showMessageDialog(this, "The area of the triangle is: " + area,"Herons Formula", JOptionPane.PLAIN_MESSAGE);
}
if (actionCommand == "Use the Formula!" ){
myPanel1.setVisible(false);
}
if (actionCommand == "Exit the program"){
System.exit(0);
}
}
}