Related
I need to build a GUI that will allow users to enter basic details about themselves for a new patient form and have that information saved to a .txt file. This data should then be viewable at a later time, but I can't get the save button to work.
//Import packages
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
//Main class
public class PatientDetailsWindow{
//Declare variables
public JFrame frame1;
public JPanel panel;
public JButton btnSave, btnExit;
public JLabel lblFirstName, lblSurname, lblGender, lblDOB, lblSmoker, lblMedHistory, lblFSlash1, lblFSlash2, lblImage;
public JTextField txtFirstName, txtSurname, txtGender, txtSmoker, txtMedHistory, txtDOB1, txtDOB2, txtDOB3;
public Insets insets;
public JTextArea textArea = new JTextArea();
public static void main (String args[]){
new PatientDetailsWindow();
}
public PatientDetailsWindow(){
createFrame();
createLabels();
createTextFields();
createButtons();
}
//Create the frame
public void createFrame(){
frame1 = new JFrame ("Personal details");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setSize (600,600);
panel = new JPanel();
panel.setBackground(Color.gray);
panel.setBounds(0, 0, 600, 600);
panel.setLayout(null);
frame1.add(panel);
frame1.setVisible(true);
}
//Creating Labels
public void createLabels(){
lblFirstName = new JLabel ("First Name: ");
lblFirstName.setBounds(50, 50, 500, 20);
lblFirstName.setForeground(Color.blue);
panel.add (lblFirstName);
lblSurname = new JLabel ("Surname: ");
lblSurname.setBounds(50, 100, 500, 20);
lblSurname.setForeground(Color.blue);
panel.add (lblSurname);
lblGender = new JLabel ("Gender: ");
lblGender.setBounds(50, 150, 500, 20);
lblGender.setForeground(Color.blue);
panel.add (lblGender);
lblDOB = new JLabel ("Date of Birth: ");
lblDOB.setBounds(50, 200, 500, 20);
lblDOB.setForeground(Color.blue);
panel.add (lblDOB);
lblFSlash1 = new JLabel ("/");
lblFSlash1.setBounds(440, 200, 20, 20);
lblFSlash1.setForeground(Color.blue);
panel.add (lblFSlash1);
lblFSlash2 = new JLabel ("/");
lblFSlash2.setBounds(490, 200, 40, 20);
lblFSlash2.setForeground(Color.blue);
panel.add (lblFSlash2);
lblSmoker = new JLabel ("Are you a smoker? ");
lblSmoker.setBounds(50, 250, 500, 20);
lblSmoker.setForeground(Color.blue);
panel.add (lblSmoker);
lblMedHistory = new JLabel ("Any other previous medical history? ");
lblMedHistory.setBounds(50, 300, 500, 20);
lblMedHistory.setForeground(Color.blue);
panel.add (lblMedHistory);
/*ImageIcon image= new ImageIcon("heartandstethoscope.jpg");
JLabel lblImage = new JLabel(image);
panel.add(lblImage);
*/
}
//Creating Text Fields
public void createTextFields(){
txtFirstName = new JTextField (10);
txtFirstName.setBounds(400, 50, 100, 20);
txtFirstName.setForeground(Color.blue);
panel.add (txtFirstName);
txtSurname = new JTextField (10);
txtSurname.setBounds(400, 100, 100, 20);
txtSurname.setForeground(Color.blue);
panel.add (txtSurname);
txtGender = new JTextField (10);
txtGender.setBounds(400, 150, 100, 20);
txtGender.setForeground(Color.blue);
panel.add (txtGender);
txtDOB1 = new JTextField (2);
txtDOB1.setBounds(400, 200, 40, 20);
txtDOB1.setForeground(Color.blue);
panel.add (txtDOB1);
txtDOB2 = new JTextField (2);
txtDOB2.setBounds(450, 200, 40, 20);
txtDOB2.setForeground(Color.blue);
panel.add (txtDOB2);
txtDOB3 = new JTextField (4);
txtDOB3.setBounds(500, 200, 80, 20);
txtDOB3.setForeground(Color.blue);
panel.add (txtDOB3);
txtSmoker = new JTextField (3);
txtSmoker.setBounds(400, 250, 100, 20);
txtSmoker.setForeground(Color.blue);
panel.add (txtSmoker);
txtMedHistory = new JTextField (300);
txtMedHistory.setBounds(400, 300, 100, 60);
txtMedHistory.setForeground(Color.blue);
panel.add (txtMedHistory);
JScrollPane areaScrollPane = new JScrollPane(txtMedHistory);
areaScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
textArea.setBounds(400, 300, 100, 80);
JScrollPane scroll = new JScrollPane (textArea);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textArea.setLineWrap(true);
textArea.setEditable(true);
textArea.setVisible(true);
panel.add(textArea);
}
//Creating buttons
public void createButtons(){
btnSave = new JButton ("Save");
btnSave.setBounds(130, 350, 100, 20);
btnSave.setForeground(Color.blue);
btnSave.addActionListener(new SaveHandler());
panel.add (btnSave);
btnSave.setVisible(true);
btnExit = new JButton ("Exit");
btnExit.setBounds(240, 350, 100, 20);
btnExit.setForeground(Color.blue);
btnExit.addActionListener(new ExitHandler());
panel.add (btnExit);
btnExit.setVisible(true);
}
class ExitHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame1,
"Are you sure you want to exit?", "Exit?",JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
System.out.println("EXIT SUCCESSFUL");
}
}
}
class SaveHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
try( PrintWriter out = new PrintWriter( "DetailsofPatient.txt" )){
out.println(txtFirstName.getText());
out.println(txtGender.getText());
out.println(txtDOB1.getText());
out.println(txtDOB2.getText());
out.println(txtDOB3.getText());
out.println(txtSmoker.getText());
out.println(txtMedHistory.getText());
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
System.out.println("Save successful");
}
}
}
Alright for starters, you didn't add an ActionListener to your save button, so you need to add it like this.
btnSave = new JButton ("Save");
btnSave.setBounds(130, 350, 100, 20);
btnSave.setForeground(Color.blue);
btnSave.addActionListener(new SaveHandler());
panel.add (btnSave);
btnSave.setVisible(true);
Also, in your SaveHandler, your PrintWriter isn't actually printing anything.
Your Code: out.println( ); would not write anything.
Let's say you wanted to write the contents of txtFirstName, you would need to do
out.println(txtFirstName.getText());
Edit: You also need another closing braces at the end of your ExitHandler class
class ExitHandler implements ActionListener{
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showConfirmDialog(frame1,
"Are you sure you want to exit?", "Exit?",JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION){
System.exit(0);
System.out.println("EXIT SUCCESSFUL");
}
}
}
You will also then need to remove a closing brace at the end of the program.
so im making a program for my project.
and when i clicked a button it must open anohter frame and make the button unclickable. and when you closed the popup frame the button must re enable. so this is
my main frame
package Option2;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MainMenu {
int intCtr1 = 0;
JFrame frame1 = new JFrame("EXD LAN PARTY");
JButton Button1 = new JButton();
JButton Button2 = new JButton();
JButton Button3 = new JButton();
JButton Button4 = new JButton();
JLabel Label1 = new JLabel();
public void MainMenu(){
//BUTTON1
Button1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/PI2.jpg")));
Button1.setBackground(Color.white);
Button1.setBounds(50, 350, 150, 150);
Button1.setToolTipText("Personal Info");
//BUTTON1 END
//BUTTON2
Button2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/PC.jpg")));
Button2.setBackground(Color.white);
Button2.setBounds(250, 350, 150, 150);
Button2.setToolTipText("PC INFO");
//BUTTON2 END
//BUTTON3
Button3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Games.jpg")));
Button3.setBackground(Color.white);
Button3.setBounds(450, 350, 150, 150);
Button3.setToolTipText("Games");
//BUTTON3 END
//BUTTON4 END
Button4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Players.jpg")));
Button4.setBackground(Color.white);
Button4.setBounds(650, 350, 150, 150);
Button3.setToolTipText("Players");
//BUTTON4 END
//LABEL1
Label1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/EXD.jpg")));
Label1.setBounds(50, 50, 800, 250);
//LABEL1 END
//Frame1
frame1.getContentPane().setBackground(Color.black);
frame1.setResizable(false);
frame1.setLayout(null);
frame1.setSize(870,650);
frame1.setVisible(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.add(Label1);
frame1.add(Button1);
frame1.add(Button2);
frame1.add(Button3);
frame1.add(Button4);
//Frame1 END
Button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
PersonalInfo objPI = new PersonalInfo();
objPI.Menu1();
Button1.setEnabled(false);
}
});
Button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
PCInfo objPCI = new PCInfo();
objPCI.Menu2();
}
});
Button3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
Games objGames = new Games();
objGames.Menu3();
}
});
Button4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
Players objPlayers = new Players();
objPlayers.Menu4();
}
});
}
public void dim1(){
if(intCtr1 == 1){
MainMenu objMM = new MainMenu();
objMM.Button1.setEnabled(true);
System.out.println("SD");
}
}
}
**and this is my sub frame**
package Option2;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PersonalInfo {
String[] arrSex = {"Male","Female"};
JFrame frame1 = new JFrame("Personal Info");
JLabel label1 = new JLabel("ID");
JLabel label2 = new JLabel("Last Name");
JLabel label3 = new JLabel("First Name");
JLabel label4 = new JLabel("Middle Name");
JLabel label5 = new JLabel("SEX");
JLabel label6 = new JLabel();
JTextField tf1 = new JTextField();
JTextField tf2 = new JTextField();
JTextField tf3 = new JTextField();
JTextField tf4 = new JTextField();
JComboBox CB1 = new JComboBox(arrSex);
JButton Button1 = new JButton("NEW");
JButton Button2 = new JButton("SAVE");
JButton Button3 = new JButton("EDIT");
JButton Button4 = new JButton("CANCEL");
JButton Button5 = new JButton();
JButton Button6 = new JButton();
JButton Button7 = new JButton();
JButton Button8 = new JButton();
public void Menu1(){
//Frame1
frame1.add(label6);
frame1.add(label1);
frame1.add(tf1);
frame1.add(label2);
frame1.add(tf2);
frame1.add(label3);
frame1.add(tf3);
frame1.add(label4);
frame1.add(tf4);
frame1.add(label5);
frame1.add(CB1);
frame1.add(Button1);
frame1.add(Button2);
frame1.add(Button3);
frame1.add(Button4);
frame1.add(Button5);
frame1.add(Button6);
frame1.add(Button7);
frame1.add(Button8);
frame1.setVisible(true);
frame1.getContentPane().setBackground(Color.black);
frame1.setSize(600,600);
frame1.setResizable(false);
frame1.setLayout(null);
frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame1.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
MainMenu objMM = new MainMenu();
objMM.intCtr1=1;
objMM.dim1();
}
});
//Frame1 End
//LABEL6
label6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/PI.jpg")));
label6.setBounds(30, 5, 800, 250);
//LABEL6 END
//LABEl1
label1.setBounds(100, 220, 50,50);
label1.setForeground(Color.white);
label1.setFont(new Font("Serif", Font.BOLD, 18));
//Label1 end
//Tf
tf1.setBounds(130, 230, 400,30);
tf1.setEnabled(false);
SmartC objSMC = new SmartC();
tf1.setText(objSMC.SmartCounter("ABC123415XYZS"));
//tf end
//label2
label2.setBounds(35, 255, 120,50);
label2.setForeground(Color.white);
label2.setFont(new Font("Serif", Font.BOLD, 18));
//label2 end
//Tf2
tf2.setBounds(130, 270, 400,30);
//tf2 end
//label3
label3.setBounds(35, 295, 120,50);
label3.setForeground(Color.white);
label3.setFont(new Font("Serif", Font.BOLD, 18));
//label3 end
//Tf3
tf3.setBounds(130, 310 , 400, 30);
//tf3 end
//label4
label4.setBounds(15, 335, 120,50);
label4.setForeground(Color.white);
label4.setFont(new Font("Serif", Font.BOLD, 18));
//label4 end
//Tf4
tf4.setBounds(130, 350 , 400, 30);
//tf4 end
//label4
label5.setBounds(85, 375, 120,50);
label5.setForeground(Color.white);
label5.setFont(new Font("Serif", Font.BOLD, 18));
//label4 end
//cb1
CB1.setBounds(130, 390, 100, 30);
CB1.setBackground(Color.white);
//cb1 end
//button1
Button1.setBounds(35, 450, 100, 30);
Button1.setBackground(Color.white);
//
//
Button2.setBounds(150, 450, 100, 30);
Button2.setBackground(Color.white);
//
//
Button3.setBounds(335, 450, 100, 30);
Button3.setBackground(Color.white);
//
//
Button4.setBounds(450, 450, 100, 30);
Button4.setBackground(Color.white);
//
//
Button5.setBounds(35, 500, 100, 50);
Button5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/First.jpg")));
Button5.setBackground(Color.white);
//
//
Button6.setBounds(150, 500, 100, 50);
Button6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Previous.jpg")));
Button6.setBackground(Color.white);
//
//
Button7.setBounds(335, 500, 100, 50);
Button7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Next.jpg")));
Button7.setBackground(Color.white);
//
//
Button8.setBounds(450, 500, 100, 50);
Button8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Option2/Last.jpg")));
Button8.setBackground(Color.white);
//
//
}
}
Any Suggestions about my coding is accepted. Sorry Still learning about Java :)
and when i clicked a button it must open anohter frame
You should NOT be creating another JFrame.
Instead you should be creating a modal JDialog. The dialog will not allow you to click on the frame until the dialog is closed.
Any Suggestions about my coding is accepted
Follow Java naming conventions. Variable names should NOT start with an upper case character. Sometimes you follow this guideline and sometimes you don't. Be consistent!
Don't use setBounds(...). Swing was designed to be used with layout managers!
First, please read Java naming conventions.
You need to pass the reference of MainMenu to PersonalInfo in order to achieve what you need, here:
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent a){
PersonalInfo objPI = new PersonalInfo(this);
objPI.menu1();
button1.setEnabled(false);
}
});
And you need to add a constructor to PersonalInfo:
private MainMenu m;
public PersonalInfo(MainMenu m) {
this.m = m;
}
Add a public method to MainMenu:
public void enableMyButton() {
button1.setEnabled(true);
}
Now you can add an event listener to PersonalInfo to enable the button of the MainMenu frame:
frame1.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
this.m.enableMyButton();
}
});
I need help with my program because I'll want to put a password and username to my program, so if the username is test && password is 12345 my program will appear a new frame but unfortunately my second didn't work for my label, button and etc here is my code so far.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwapFields extends JFrame{
public static void main(String[] args) {
SwapFields frameTabel = new SwapFields();
}
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
JLabel lab = new JLabel("Username :");
JLabel pas = new JLabel("Password :");
JLabel cos;
// JPanel panel = new JPanel();
JButton y1;
JButton y2;
SwapFields() {
super("Enter Your Account !");
setSize(300, 200);
setLocation(500, 280);
panel.setLayout(null);
txuser.setBounds(90, 30, 150, 20);
pass.setBounds(90, 65, 150, 20);
blogin.setBounds(110, 100, 80, 20);
lab.setBounds(15, 28, 150, 20);
pas.setBounds(15, 63, 150, 20);
panel.add(lab);
panel.add(pas);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin() {
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String puname = txuser.getText();
String ppaswd = pass.getText();
if (puname.equals("test") && ppaswd.equals("12345")) {
JFrame frame = new JFrame("Customer");
JPanel panel1 = new JPanel();
frame.setVisible(true);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cos = new JLabel("Do you have a Customer ?");
y1 = new JButton("Yes");
y2 = new JButton("No");
panel1.setLayout(null);
cos.setBounds(70, 30, 150, 20);
y1.setBounds(80, 65, 150, 20);
y2.setBounds(140, 65, 150, 20);
y1.setSize(55, 30);
y2.setSize(55, 30);
panel1.add(y1);
panel1.add(y2);
panel1.add(cos);
frame.getContentPane().add(panel1);
// this is the code ill change this is the second frame .
dispose();
} else {
JOptionPane.showMessageDialog(null, "Wrong Password / Username");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
}
});
}
}
change
panel.setLayout(null);
to
panel.setLayout(new Flowlayout());
I am having a lot of issues with this application. I have been at this all day and cannot get this figured out. I have a Java application that is for a class. The issue that I am having is trying to get the JRadioButtons assigned to variables in the array then passing them into the formula. If someone could help I would appreciate it a lot.
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JRadioButton;
public class MortgageCalculatorGUI8 extends JFrame {
JPanel panel1 = new JPanel();
double Principal;
double [] Interest = {5.35, 5.5, 5.75};
double temp_Interest;
int [] Length = {7, 15, 30};
int temp_Length;
boolean ok = false;
public MortgageCalculatorGUI8(){
getContentPane ().setLayout (null);
setSize (400,400);
panel1.setLayout (null);
panel1.setBounds (0, 0, 2000, 800);
add (panel1);
JLabel mortgageLabel = new JLabel("Mortgage Amount $", JLabel.LEFT);
mortgageLabel.setBounds (15, 15, 150, 30);
panel1.add (mortgageLabel);
final JTextField mortgageText = new JTextField(10);
mortgageText.setBounds (130, 15, 150, 30);
panel1.add (mortgageText);
JLabel termLabel = new JLabel("Mortgage Term (Years)", JLabel.LEFT);
termLabel.setBounds (340, 40, 150, 30);
panel1.add (termLabel);
JTextField termText = new JTextField(3);
termText.setBounds (340, 70, 150, 30);
panel1.add (termText);
JLabel intRateLabel = new JLabel("Interest Rate (%)", JLabel.LEFT);
intRateLabel.setBounds (340, 94, 150, 30);
panel1.add (intRateLabel);
JTextField intRateText = new JTextField(5);
intRateText.setBounds (340, 120, 150, 30);
panel1.add (intRateText);
JLabel mPaymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
mPaymentLabel.setBounds (550, 40, 150, 30);
panel1.add (mPaymentLabel);
JTextField mPaymentText = new JTextField(10);
mPaymentText.setBounds (550, 70, 150, 30);
panel1.add (mPaymentText);
// JLabel paymentLabel = new JLabel ("Payment #");
// JLabel balLabel = new JLabel (" Balance");
// JLabel ytdPrincLabel = new JLabel (" Principal");
// JLabel ytdIntLabel = new JLabel (" Interest");
JTextArea textArea = new JTextArea(10, 31);
textArea.setBounds (550, 100, 150, 30);
panel1.add (textArea);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setBounds (450, 200, 300, 150);
panel1.add (scroll);
public void rbuttons(){
JLabel tYears = new JLabel("Years of Loan Amount");
tYears.setBounds (30, 35, 150, 30);
panel1.add (tYears);
JRadioButton b7Yr = new JRadioButton("7 Years",false);
b7Yr.setBounds (30, 58, 150, 30);
panel1.add (b7Yr);
JRadioButton b15Yr = new JRadioButton("15 Years",false);
b15Yr.setBounds (30, 80, 150, 30);
panel1.add (b15Yr);
JRadioButton b30Yr = new JRadioButton("30 Years",false);
b30Yr.setBounds (30, 101, 150, 30);
panel1.add (b30Yr);
JLabel tInterest = new JLabel("Interest Rate Of the Loan");
tInterest.setBounds (175, 35, 150, 30);
panel1.add(tInterest);
JRadioButton b535Int = new JRadioButton("5.35% Interest",false);
b535Int.setBounds (178, 58, 150, 30);
panel1.add (b535Int);
JRadioButton b55Int = new JRadioButton("5.5% Interest",false);
b55Int.setBounds (178, 80, 150, 30);
panel1.add (b55Int);
JRadioButton b575Int = new JRadioButton("5.75% Interest",false);
b575Int.setBounds (178, 101, 150, 30);
panel1.add (b575Int);
}
JButton calculateButton = new JButton("CALCULATE");
calculateButton.setBounds (30, 400, 120, 30);
panel1.add (calculateButton);
calculateButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if(e.getSource () == b7Yr){
b7Yr = Length[0];
}
if(e.getSource () == b15Yr){
b15Yr = Length[1];
}
if(e.getSource () == b30Yr){
b30Yr = Length[2];
}
if(e.getSource () == b535Int){
b535Int = Interest[0];
}
if(e.getSource () == b55Int){
b55Int = Interest[1];
}
if(e.getSource () == b575Int){
b575Int = Interest[2];
}
double Principal;
// double [] Interest;
// int [] Length;
double M_Interest = Interest /(12*100);
double Months = Length * 12;
Principal = Double.parseDouble (mortgageText.getText());
double M_Payment = Principal * ( M_Interest / (1 - (Math.pow((1 + M_Interest), - Months))));
NumberFormat Money = NumberFormat.getCurrencyInstance();
}
});
JButton clearButton = new JButton("CLEAR");
clearButton.setBounds (160, 400, 120, 30);
panel1.add (clearButton);
clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
mortgageText.setText (null);
b7Yr.setSelected (false);
b15Yr.setSelected (false);
b30Yr.setSelected (false);
b535Int.setSelected (false);
b55Int.setSelected (false);
b575Int.setSelected (false);
}
});
JButton exitButton = new JButton("EXIT");
exitButton.setBounds (290, 400, 120, 30);
panel1.add (exitButton);
exitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args) {
MortgageCalculatorGUI8 frame = new MortgageCalculatorGUI8();
frame.setBounds (400, 200, 800, 800);
frame.setTitle ("Mortgage Calculator 1.0.4");
frame.setDefaultCloseOperation (EXIT_ON_CLOSE);
frame.setVisible (true);
}
}
Shoot, I'll show you in an example of what I meant in my last comment:
Myself, I'd create an array of JRadioButtons as a class field for each group that I used as well as a ButtonGroup object for each cluster of JRadioButtons. Then in my calculate JButton's ActionListener, I'd get the selected radiobutton by either looping through the radio button array or from the ButtonGroups getSelection method (note though that this returns a ButtonModel object or null if nothing is selected).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InfoFromRadioBtns extends JPanel {
private static final long serialVersionUID = 1L;
private int[] foobars = {1, 2, 5, 10, 20};
private JRadioButton[] foobarRButtons = new JRadioButton[foobars.length];
private ButtonGroup foobarBtnGroup = new ButtonGroup();
public InfoFromRadioBtns() {
// jpanel to hold one set of radio buttons
JPanel radioBtnPanel = new JPanel(new GridLayout(0, 1));
radioBtnPanel.setBorder(BorderFactory
.createTitledBorder("Choose a Foobar"));
// iterate through the radio button array creating buttons
// and adding them to the radioBtnPanel and the
// foobarBtnGroup ButtonGroup
for (int i = 0; i < foobarRButtons.length; i++) {
// string for radiobutton to dislay -- just the number
String buttonText = String.valueOf(foobars[i]);
JRadioButton radiobtn = new JRadioButton("foobar " + buttonText);
radiobtn.setActionCommand(buttonText); // one way to find out which
// button is selected
radioBtnPanel.add(radiobtn); // add radiobutton to its panel
foobarBtnGroup.add(radiobtn); // add radiobutton to its button group
// add to array
foobarRButtons[i] = radiobtn;
}
// one way to get the selected JRadioButton
JButton getRadioChoice1 = new JButton("Get Radio Choice 1");
getRadioChoice1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel seletedModel = foobarBtnGroup.getSelection();
if (seletedModel != null) {
String actionCommand = seletedModel.getActionCommand();
System.out.println("selected foobar: " + actionCommand);
} else {
System.out.println("No foobar selected");
}
}
});
// another way to get the selected JRadioButton
JButton getRadioChoice2 = new JButton("Get Radio Choice 2");
getRadioChoice2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String actionCommand = "";
for (JRadioButton foobarRButton : foobarRButtons) {
if (foobarRButton.isSelected()) {
actionCommand = foobarRButton.getActionCommand();
}
}
if (actionCommand.isEmpty()) {
System.out.println("No foobar selected");
} else {
System.out.println("selected foobar: " + actionCommand);
}
}
});
JPanel jBtnPanel = new JPanel();
jBtnPanel.add(getRadioChoice1);
jBtnPanel.add(getRadioChoice2);
// make main GUI use a BordeLayout
setLayout(new BorderLayout());
add(radioBtnPanel, BorderLayout.CENTER);
add(jBtnPanel, BorderLayout.PAGE_END);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("InfoFromRadioBtns");
frame.getContentPane().add(new InfoFromRadioBtns());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Whatever you do, don't try to copy and paste any of this code into your program, because it simply isn't going to work that way (on purpose). It was posted only to illustrate the concepts that I've discussed above.
I would extend JRadioButton to create a class capable of holding the variables you want. You can do this as an inner class to keep things simple.
private double pctinterest;
private int numyears; // within scope of your containing class
private class RadioButtonWithYears extends JRadioButton {
final private int years;
private int getYears() { return years; }
public RadioButtonWithYears(int years) {
super(years + " years",false);
this.years = years;
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
numyears = getYears();
}
});
}
}
// elsewhere
RadioButtonWithYears b7Yr = new RadioButtonWithYears(7);
RadioButtonWithYears b15Yr = new RadioButtonWithYears(15);
RadioButtonWithYears b30Yr = new RadioButtonWithYears(30);
// then later
double M_Interest = java.lang.Math.pow((pctinternet / 100)+1, numyears);
Update: It isn't too far gone to salvage. I have incorporated the ButtonGroup as per Eels suggestion, and made the GUI part of it work (although you'll have to fix the layout) and marked where you need to sort out the calculation.
package stack.swing;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JRadioButton;
public class MortgageCalculatorGUI8 extends JFrame {
JPanel panel1 = new JPanel();
Integer Principal;
boolean ok = false;
private BigDecimal temp_Interest;
private int temp_Length; // within scope of your containing class
private class JRadioButtonWithYears extends JRadioButton {
final private int years;
private int getYears() { return years; }
public JRadioButtonWithYears(int years) {
super(years + " years",false);
this.years = years;
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
temp_Length = getYears();
}
});
}
}
private class JRadioButtonWithPct extends JRadioButton {
final private BigDecimal pct;
private BigDecimal getPct() { return pct; }
public JRadioButtonWithPct(String pct) {
super(pct + "%",false);
this.pct = new BigDecimal(pct);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
temp_Interest = getPct();
}
});
}
}
public MortgageCalculatorGUI8() {
getContentPane ().setLayout (null);
setSize (400,400);
panel1.setLayout (null);
panel1.setBounds (0, 0, 2000, 800);
add (panel1);
JLabel mortgageLabel = new JLabel("Mortgage Amount $", JLabel.LEFT);
mortgageLabel.setBounds (15, 15, 150, 30);
panel1.add (mortgageLabel);
final JTextField mortgageText = new JTextField(10);
mortgageText.setBounds (130, 15, 150, 30);
panel1.add (mortgageText);
JLabel termLabel = new JLabel("Mortgage Term (Years)", JLabel.LEFT);
termLabel.setBounds (340, 40, 150, 30);
panel1.add (termLabel);
JTextField termText = new JTextField(3);
termText.setBounds (340, 70, 150, 30);
panel1.add (termText);
JLabel intRateLabel = new JLabel("Interest Rate (%)", JLabel.LEFT);
intRateLabel.setBounds (340, 94, 150, 30);
panel1.add (intRateLabel);
JTextField intRateText = new JTextField(5);
intRateText.setBounds (340, 120, 150, 30);
panel1.add (intRateText);
JLabel mPaymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
mPaymentLabel.setBounds (550, 40, 150, 30);
panel1.add (mPaymentLabel);
JTextField mPaymentText = new JTextField(10);
mPaymentText.setBounds (550, 70, 150, 30);
panel1.add (mPaymentText);
// JLabel paymentLabel = new JLabel ("Payment #");
// JLabel balLabel = new JLabel (" Balance");
// JLabel ytdPrincLabel = new JLabel (" Principal");
// JLabel ytdIntLabel = new JLabel (" Interest");
JTextArea textArea = new JTextArea(10, 31);
textArea.setBounds (550, 100, 150, 30);
panel1.add (textArea);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setBounds (450, 200, 300, 150);
panel1.add (scroll);
// jpanel to hold one set of radio buttons
JPanel yearsPanel = new JPanel(new GridLayout(0, 1));
yearsPanel.setBorder(BorderFactory
.createTitledBorder("Years of Loan Amount"));
yearsPanel.setBounds(30, 55, 150, 150);
panel1.add (yearsPanel);
final ButtonGroup yearsGroup = new ButtonGroup();
int years[] = { 7, 15, 30 };
for (int i = 0; i < years.length; i++) {
JRadioButtonWithYears radiobtn = new JRadioButtonWithYears(years[i]);
yearsPanel.add(radiobtn); // add radiobutton to its panel
yearsGroup.add(radiobtn); // add radiobutton to its button group
}
// jpanel to hold one set of radio buttons
JPanel pctPanel = new JPanel(new GridLayout(0, 1));
pctPanel.setBorder(BorderFactory
.createTitledBorder("Interest Rate Of the Loan"));
pctPanel.setBounds(175, 55, 180, 150);
panel1.add (pctPanel);
final ButtonGroup pctGroup = new ButtonGroup();
String pct[] = { "5.35", "5.5", "5.75" };
for (int i = 0; i < pct.length; i++) {
JRadioButtonWithPct radiobtn = new JRadioButtonWithPct(pct[i]);
pctPanel.add(radiobtn); // add radiobutton to its panel
pctGroup.add(radiobtn); // add radiobutton to its button group
}
final JButton calculateButton = new JButton("CALCULATE");
calculateButton.setBounds (30, 400, 120, 30);
panel1.add (calculateButton);
calculateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double M_Interest = temp_Interest.doubleValue() /(12*100);
double Months = temp_Length * 12;
Principal = Integer.parseInt(mortgageText.getText());
double M_Payment = Principal * ( M_Interest / (1 - (Math.pow((1 + M_Interest), - Months))));
NumberFormat Money = NumberFormat.getCurrencyInstance();
/** MORE STUFF TO HAPPEN HERE */
}
});
JButton clearButton = new JButton("CLEAR");
clearButton.setBounds (160, 400, 120, 30);
panel1.add (clearButton);
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mortgageText.setText (null);
yearsGroup.clearSelection();
pctGroup.clearSelection();
}
});
JButton exitButton = new JButton("EXIT");
exitButton.setBounds (290, 400, 120, 30);
panel1.add (exitButton);
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
MortgageCalculatorGUI8 frame = new MortgageCalculatorGUI8();
frame.setBounds (400, 200, 800, 800);
frame.setTitle ("Mortgage Calculator 1.0.4");
frame.setDefaultCloseOperation (EXIT_ON_CLOSE);
frame.setVisible (true);
}
}
I'm new to java so bear with me:
I want the size of the window/pane/panel to chance once the tab is clicked/changed.
How would I do/impletement this?
I've done it successfully on a button click/event, but how do I do a tab click/event?
Here is my code: (I'm sorry for any bad/bloated/unnessicary code in advance)
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
//Class shows how to setup up a tabbed window
public class GUI implements ActionListener
{
static JFrame aWindow = new JFrame("Project");
JTabbedPane myTabs = new JTabbedPane();
JPanel loginMainPanel = new JPanel();
JPanel displayMainPanel = new JPanel();
JPanel editMainPanel = new JPanel();
JLabel loginLabel = new JLabel("Username:");
JTextField loginField = new JTextField();
JLabel loginLabel2 = new JLabel("Password:");
JPasswordField loginPass = new JPasswordField();
JButton displayButton = new JButton("Press This Button");
JButton loginButton = new JButton("Login");
JLabel editLabel = new JLabel("Write a story:");
JTextArea editArea = new JTextArea();
public GUI()
{
Toolkit theKit = aWindow.getToolkit();
Dimension wndSize=theKit.getScreenSize();
aWindow.setBounds(wndSize.width/3, wndSize.height/3, 200, 200); //set position, then dimensions
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(1,1);
Container content = aWindow.getContentPane();
content.setLayout(grid);
createLoginPanel();
createDisplayPanel();
createEditPanel();
myTabs.addTab("Login", loginMainPanel);
myTabs.addTab("Display", displayMainPanel);
myTabs.addTab("Edit", editMainPanel);
myTabs.setSelectedIndex(0);
//myTabs.setEnabledAt(1,false);
myTabs.setEnabledAt(2, false);
content.add(myTabs);
aWindow.setVisible(true);
}
public void createLoginPanel()
{
loginMainPanel.setLayout(null);
loginLabel.setBounds(10, 15, 150, 20);
loginMainPanel.add(loginLabel);
loginField.setBounds(10, 35, 150, 20);
loginMainPanel.add(loginField);
loginLabel2.setBounds(10, 60, 150, 20);
loginMainPanel.add(loginLabel2);
loginPass.setBounds(10, 80, 150, 20);
loginMainPanel.add(loginPass);
loginButton.addActionListener(this);
loginButton.setBounds(50, 110, 80, 20);
loginMainPanel.add(loginButton);
}
public void createDisplayPanel()
{
//Toolkit theKit = aWindow.getToolkit();
//Dimension wndSize = theKit.getScreenSize();
//aWindow.setBounds(20, 20, 20, 20); //set position, then dimensions
displayMainPanel.setLayout(null);
displayButton.addActionListener(this);
displayButton.setBounds(10, 80, 150, 20);
displayMainPanel.add(displayButton);
}
public void createEditPanel()
{
editMainPanel.setLayout(null);
editLabel.setBounds(10, 15, 150, 20);
editMainPanel.add(editLabel);
editArea.setBounds(10, 65, 150, 50);
editMainPanel.add(editArea);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == loginButton)
{
//System.out.println("Working...");
Toolkit theKit = aWindow.getToolkit();
Dimension wndSize = theKit.getScreenSize();
aWindow.setBounds(wndSize.width / 4, wndSize.height / 4, 300, 300);
}
//Would the event go here?
}
public static void main(String[] args)
{
GUI tw1 = new GUI();
}
}
Thanks very much :)
James,
but how do I do a tab click/event?
Use a ChangeListener.