I'm trying to create a address book and all I currently need is a table to store the data, however I cannot get it to display on the panel, any ideas why? I've got a method which should be creating the table on execution but its not.
private String name;
private String surname;
private String phone;
private String address;
static String summary;
private JPanel panel;
private JFrame frame;
private JLabel lblName;
private JLabel lblAddress;
private JLabel lblSurname;
private JLabel lblPhone;
private JTextField txtName;
private JTextField txtSurname;
private JTextField txtPhone;
private JTextField txtAddress;
private JButton btnSave;
private JButton btnUpload;
private JButton btnDelete;
String columns[] = {"Name","Surname","Phone","Address"};
String[][] data =
{{"human", "bean","07443244","somewhere"},
{"Max", "Kenny","044353534","Somewhere"}};
public AddressBook() {
createForm();
createLabels();
createTextField();
createButton();
createTable();
frame.add(panel);
frame.setVisible(true);
}
public void createLabels(){
lblName = new JLabel ("Name");
lblName.setBounds(10, 30, 100, 20);
panel.add (lblName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(10, 50, 100, 20);
panel.add (lblSurname);
lblAddress = new JLabel ("Address");
lblAddress.setBounds(10, 70, 100, 20);
panel.add (lblAddress);
lblPhone = new JLabel ("Phone");
lblPhone.setBounds(10, 90, 100, 20);
panel.add (lblPhone);
}
public void createTextField(){
txtName = new JTextField (null);
txtName.setBounds(110, 30, 150, 20);
panel.add (txtName);
txtSurname = new JTextField (null);
txtSurname.setBounds(110, 50, 150, 20);
panel.add (txtSurname);
txtAddress = new JTextField (null);
txtAddress.setBounds(110, 70, 150, 20);
panel.add (txtAddress);
txtPhone = new JTextField (null);
txtPhone.setBounds(110, 90, 150, 20);
panel.add (txtPhone);
}
public void createForm(){
panel = new JPanel();
panel.setBorder (BorderFactory.createLineBorder (Color.RED, 3));
panel.setLayout(null);
frame = new JFrame();
frame.setTitle("Address Book");
frame.setSize(800,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void createButton(){
btnSave = new JButton ("Save to a file");
btnSave.setBounds(50, 200, 200, 20);
btnSave.addActionListener(new SaveHandler());
panel.add (btnSave);
btnDelete = new JButton ("Delete from the table");
btnDelete.setBounds(50, 300, 200, 20);
panel.add (btnDelete);
btnUpload = new JButton ("Upload file to table");
btnUpload.setBounds(50, 400, 200, 20);
panel.add (btnUpload);
}
public void createTable(){
JTable table = new JTable(data, columns);
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns);
table.setModel(model);
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
panel.add(table);
}
class SaveHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnSave)
{
name = ("");
surname = ("");
phone = ("");
address = ("");
name = txtName.getText();
surname = txtSurname.getText();
phone = txtPhone.getText();
address = txtAddress.getText();
summary = ("Name:" +name)+(surname)+("Phone:" + phone)+("Address:" + address);
String saveFile = summary;
try {
BufferedWriter reader = new BufferedWriter(new FileWriter(new File("userinfo.txt"), true));
reader.write(saveFile);
reader.newLine();
reader.close();
JOptionPane.showMessageDialog(frame, "The details were sucessfuly saved");
} catch (IOException e1) {
e1.printStackTrace();
}
}
} }
public static void main(String[] args) {
new AddressBook();
}
}
panel.setLayout(null);
You chose to use no layout manager and handle all of the layout yourself.
JTable table = new JTable(data, columns);
table.setModel(model);
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
However, you did not specify a size and position for the JTable.
I recommend learning to use the layout managers instead. It will work better, it will handle the user resizing the window, and will make the code more maintainable.
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.
I'm having really hard time splitting up my class into two classes, right now I have the GUI and the logic all together in one class and I want it to be separate, I had a read on objects and classes but I still don't understand how I would split it up for my example, my only "logic" in this program is 3 inner classes which determine what the buttons do (Delete record, save record etc...)
Heres my code, can anyone point me in the right direction?
private String name;
private String surname;
private String phone;
private String address;
private String postcode;
private String email;
static String summary;
private JPanel panel;
private JPanel buttonspanel;
private JPanel labelspanel;
private JPanel tablepanel;
private JFrame frame;
private JLabel lblName;
private JLabel lblEmail;
private JLabel lblPostcode;
private JLabel lblAddress;
private JLabel lblSurname;
private JLabel lblPhone;
private JTextField txtName;
private JTextField txtSurname;
private JTextField txtPostcode;
private JTextField txtEmail;
private JTextField txtPhone;
private JTextField txtAddress;
private JButton btnSave;
private JButton btnUpload;
private JButton btnDelete;
String columns[] = {"Name","Surname","Phone","Address","Postcode","Email"};
private DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
public AddressBook() {
createForm();
createLabels();
createTextField();
createButton();
createTable();
frame.add(panel);
frame.setVisible(true);
}
public void createLabels(){
lblName = new JLabel ("Name");
lblName.setBounds(10, 30, 100, 20);
labelspanel.add (lblName);
lblSurname = new JLabel ("Surname");
lblSurname.setBounds(10, 50, 100, 20);
labelspanel.add (lblSurname);
lblAddress = new JLabel ("Address");
lblAddress.setBounds(10, 70, 100, 20);
labelspanel.add (lblAddress);
lblPhone = new JLabel ("Phone");
lblPhone.setBounds(10, 90, 100, 20);
labelspanel.add (lblPhone);
lblPostcode = new JLabel ("Postcode");
lblPostcode.setBounds(10, 110, 100, 20);
labelspanel.add (lblPostcode);
lblEmail = new JLabel ("Email");
lblEmail.setBounds(10, 130, 100, 20);
labelspanel.add (lblEmail);
}
public void createTextField(){
txtName = new JTextField (null);
txtName.setBounds(110, 30, 150, 20);
labelspanel.add (txtName);
txtSurname = new JTextField (null);
txtSurname.setBounds(110, 50, 150, 20);
labelspanel.add (txtSurname);
txtAddress = new JTextField (null);
txtAddress.setBounds(110, 70, 150, 20);
labelspanel.add (txtAddress);
txtPhone = new JTextField (null);
txtPhone.setBounds(110, 90, 150, 20);
labelspanel.add (txtPhone);
txtPostcode = new JTextField (null);
txtPostcode.setBounds(110, 110, 150, 20);
labelspanel.add (txtPostcode);
txtEmail = new JTextField (null);
txtEmail.setBounds(110, 130, 150, 20);
labelspanel.add (txtEmail);
}
public void createForm(){
frame = new JFrame();
frame.setTitle("Address Book");
frame.setSize(800,800);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
buttonspanel = new JPanel();
buttonspanel.setLayout(new FlowLayout());
buttonspanel.setBorder (BorderFactory.createEtchedBorder ());
labelspanel = new JPanel();
labelspanel.setBorder (BorderFactory.createEtchedBorder ());
labelspanel.setLayout(null);
labelspanel.setPreferredSize(new Dimension (400,200));
tablepanel = new JPanel();
tablepanel.setLayout(new BorderLayout());
panel.add(buttonspanel);
panel.add(labelspanel);
panel.add(tablepanel);
}
public void createButton(){
btnSave = new JButton ("Save to a file");
btnSave.addActionListener(new SaveHandler());
buttonspanel.add (btnSave);
btnDelete = new JButton ("Delete from the table");
btnDelete.addActionListener(new DeleteHandler());
buttonspanel.add (btnDelete);
btnUpload = new JButton ("Add details to table");
btnUpload.addActionListener(new AddHandler());
buttonspanel.add (btnUpload);
}
public void createTable(){
model.setColumnIdentifiers(columns);
JScrollPane scrollPane = new JScrollPane(table);
tablepanel.add(scrollPane, BorderLayout.SOUTH);
}
class SaveHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnSave)
{
name = ("");
surname = ("");
phone = ("");
address = ("");
postcode = ("");
email = ("");
name = txtName.getText();
surname = txtSurname.getText();
phone = txtPhone.getText();
address = txtAddress.getText();
postcode = txtPostcode.getText();
email = txtEmail.getText();
summary = ("Name:" +name)+("Surname:" +surname)+("Phone:" + phone)+("Address:" + address)+("Postcode:" + postcode)+("Email:" + email);
String saveFile = summary;
try {
BufferedWriter reader = new BufferedWriter(new FileWriter(new File("userinfo.txt"), true));
reader.write(saveFile);
reader.newLine();
reader.close();
JOptionPane.showMessageDialog(frame, "The details were sucessfuly saved");
} catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "Something went wrong, please try again");
}
}
}
}
class AddHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnUpload)
{
String nameRow = txtName.getText();
String surnameRow = txtSurname.getText();
String phoneRow = txtPhone.getText();
String addressRow = txtAddress.getText();
String postcodeRow = txtPostcode.getText();
String emailRow = txtEmail.getText();
Object[] row = {nameRow,surnameRow,phoneRow,addressRow,postcodeRow,emailRow};
model.addRow(row);
}
}
}
class DeleteHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnDelete)
{
int i = table.getSelectedRow();
if(i >= 0){
model.removeRow(i);
}
}
}
}
public static void main(String[] args) {
new AddressBook();
}
class GUI{
Jbutton btnsave;
Jbutton Delete;
jbutton update
HandleAll btnHandler = new HandleAll();
btnSave.addActionListener(btnHandler);
Deletea.ddActionListener(btnHandler);
update.addActionListener(btnHandler);
class HandleAll implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnSave){
//on click save button
}else if(e.getSource()==Delete){
//on click delete button
}else if(e.getSource()==update){
//on click update button
}
}
}
}
you can follow above approach to seperate logic from Gui . by the way i have made the HandleAll class a inner class. HandleAll implements actionListner interface . on every button press actionperformed on this class will get call but by selecting e.getsource you can check which button was pressed exactly.try this approach
I am encountering problems with event handling in java.
I want to add the image1 if button 1 is pressed, image2 if button 2 is pressed, et cetera.
This is my code till now; Can anyone help? This code doesn't compile.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.ImageIcon;
public class MyPanel extends JPanel {
private JLabel jcomp1;
private JButton jcomp2;
private JButton jcomp3;
private JButton jcomp4;
private JButton jcomp5;
private JButton jcomp6;
private JButton jcomp7;
private JButton jcomp8;
private JButton jcomp9;
private ImageIcon image1;
private ImageIcon image2;
private ImageIcon image3;
private ImageIcon image4;
private ImageIcon image5;
private ImageIcon image6;
private ImageIcon image7;
private ImageIcon image8;
public MyPanel() {
//construct components
image1 = new ImageIcon(getClass().getResource("hang1.jpg"));
image2 = new ImageIcon(getClass().getResource("hang2.jpg"));
image3 = new ImageIcon(getClass().getResource("hang3.jpg"));
image4 = new ImageIcon(getClass().getResource("hang4.jpg"));
image5 = new ImageIcon(getClass().getResource("hang5.jpg"));
image6 = new ImageIcon(getClass().getResource("hang6.jpg"));
image7 = new ImageIcon(getClass().getResource("hang7.jpg"));
image8 = new ImageIcon(getClass().getResource("hang8.jpg"));
jcomp1 = new JLabel (image1);
jcomp2 = new JButton ("1");
jcomp3 = new JButton ("2");
jcomp4 = new JButton ("3");
jcomp5 = new JButton ("4");
jcomp6 = new JButton ("5");
jcomp7 = new JButton ("6");
jcomp8 = new JButton ("7");
jcomp9 = new JButton ("8");
//events
jcomp2.setActionCommand("1");
jcomp3.setActionCommand("2");
jcomp4.setActionCommand("3");
jcomp5.setActionCommand("4");
jcomp6.setActionCommand("5");
jcomp7.setActionCommand("6");
jcomp8.setActionCommand("7");
jcomp9.setActionCommand("8");
jcomp2.addActionListener(new ButtonClickListener());
jcomp3.addActionListener(new ButtonClickListener());
jcomp4.addActionListener(new ButtonClickListener());
jcomp5.addActionListener(new ButtonClickListener());
jcomp6.addActionListener(new ButtonClickListener());
jcomp7.addActionListener(new ButtonClickListener());
jcomp8.addActionListener(new ButtonClickListener());
jcomp9.addActionListener(new ButtonClickListener());
//adjust size and set layout
setPreferredSize(new Dimension(624, 537));
setLayout(null);
//add components
add(jcomp2);
add(jcomp3);
add(jcomp4);
add(jcomp5);
add(jcomp6);
add(jcomp7);
add(jcomp8);
add(jcomp9);
// set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds(15, 10, 595, 350);
jcomp2.setBounds(35, 375, 100, 25);
jcomp3.setBounds(190, 375, 100, 25);
jcomp4.setBounds(320, 375, 100, 25);
jcomp5.setBounds(465, 375, 100, 25);
jcomp6.setBounds(35, 450, 100, 25);
jcomp7.setBounds(190, 450, 100, 25);
jcomp8.setBounds(320, 450, 100, 25);
jcomp9.setBounds(465, 450, 100, 25);
}
class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("1")) {
jcomp1.set(image1);
}
}
}
public static void main (String[] args) {
JFrame frame = new JFrame("MyPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyPanel());
frame.pack();
frame.setVisible (true);
}
}
I believe you are trying to get something like this:
public class MyPanel extends JPanel {
private JLabel label;
private JButton[] buttons = new JButton[8];
private ImageIcon[] images = new ImageIcon[8];
public MyPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(2, 4, 15, 10));
for (int i = 0; i < images.length; i++) {
images[i] = new ImageIcon(getClass().getResource(i+1 + ".png"));
buttons[i] = new JButton(String.valueOf(i+1));
buttons[i].setActionCommand(String.valueOf(i+1));
buttons[i].addActionListener(new ButtonClickListener());
buttonPanel.add(buttons[i]);
}
label = new JLabel(images[0]);
setLayout(new BorderLayout());
add(label);
add(buttonPanel, BorderLayout.PAGE_END);
}
class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setIcon(images[Integer.parseInt(e.getActionCommand()) - 1]);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("MyPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyPanel());
frame.pack();
frame.setVisible(true);
}
}
Notes:
Don't forget to change the image file name.
You can play with the layout manager to get what you want.
I removed setPreferredSize(new Dimension(624, 537)); because you didn't specify a resize behavior which would make this line meaningless. pack() would take care of the sizes for you.
Set the icon of the button or label. To do this, you need to create an ImageIcon, which has multiple constructors to create from a filename or a loaded image.
jcomp1.setIcon(new ImageIcon(...));
I've been working at this problem for hours now, with no results. I cannot seem to get the applet to display properly when viewing the HTML page OR when running the applet through Eclipse. It is always blank. I've been searching for a long time now and decided just to ask.
Here's the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class Topics extends Applet{
String topicTotal = "";
JPanel topicPanel;
JLabel title, username, topic, paragraph, topicsTitle;
JTextField nameField, topicField;
JButton submitButton;
JTextArea paragraphArea;
public String getTopicTotal() {
return topicTotal;
}
public JPanel createContentPane(){
final JPanel topicGUI = new JPanel();
topicGUI.setLayout(null);
//posting panel
final JPanel postPanel = new JPanel();
postPanel.setLayout(null);
postPanel.setLocation(0, 0);
postPanel.setSize(500, 270);
topicGUI.add(postPanel);
setVisible(true);
// JLabels
JLabel title = new JLabel("Make A Post");
title.setLocation(170, 3);
title.setSize(150,25);
title.setFont(new Font("Serif", Font.PLAIN, 25));
title.setHorizontalAlignment(0);
postPanel.add(title);
JLabel username = new JLabel("Username: ");
username.setLocation(20, 30);
username.setSize(70,15);
username.setHorizontalAlignment(0);
postPanel.add(username);
JLabel topic = new JLabel("Topic: ");
topic.setLocation(20, 50);
topic.setSize(40,15);
topic.setHorizontalAlignment(0);
postPanel.add(topic);
JLabel paragraph = new JLabel("Paragraph: ");
paragraph.setLocation(20, 70);
paragraph.setSize(70,15);
paragraph.setHorizontalAlignment(0);
postPanel.add(paragraph);
// JTextFields
nameField = new JTextField(8);
nameField.setLocation(90, 30);
nameField.setSize(150, 18);
postPanel.add(nameField);
topicField = new JTextField(8);
topicField.setLocation(60, 50);
topicField.setSize(180, 18);
postPanel.add(topicField);
// JTextAreas
paragraphArea = new JTextArea(8, 5);
paragraphArea.setLocation(20, 85);
paragraphArea.setSize(450, 100);
paragraphArea.setLineWrap(true);
paragraphArea.setEditable(true);
JScrollPane scrollParagraph = new JScrollPane (paragraphArea);
scrollParagraph.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
postPanel.add(paragraphArea);
// JButton
JButton submitButton = new JButton("SUBMIT");
submitButton.setLocation(250, 30);
submitButton.setSize(100, 30);
submitButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
topicTotal = topicTotal + "/n" + nameField + "/n" + topicTotal + "/n" + paragraphArea + "/n";
}
});
postPanel.add(submitButton);
setVisible(true);
return topicGUI;
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("");
Topics display = new Topics();
frame.setContentPane(display.createContentPane());
frame.setSize(500, 270);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
In order to run as an applet, you need to override the init method. You don't need a main method. Just add all you components inside the init method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class Topics extends Applet {
String topicTotal = "";
JPanel topicPanel;
JLabel title, username, topic, paragraph, topicsTitle;
JTextField nameField, topicField;
JButton submitButton;
JTextArea paragraphArea;
public String getTopicTotal() {
return topicTotal;
}
public void init() {
final JPanel topicGUI = new JPanel();
topicGUI.setLayout(null);
// posting panel
final JPanel postPanel = new JPanel();
postPanel.setLayout(null);
postPanel.setLocation(0, 0);
postPanel.setSize(500, 270);
add(postPanel);
setVisible(true);
// JLabels
JLabel title = new JLabel("Make A Post");
title.setLocation(170, 3);
title.setSize(150, 25);
title.setFont(new Font("Serif", Font.PLAIN, 25));
title.setHorizontalAlignment(0);
add(title);
JLabel username = new JLabel("Username: ");
username.setLocation(20, 30);
username.setSize(70, 15);
username.setHorizontalAlignment(0);
add(username);
JLabel topic = new JLabel("Topic: ");
topic.setLocation(20, 50);
topic.setSize(40, 15);
topic.setHorizontalAlignment(0);
add(topic);
JLabel paragraph = new JLabel("Paragraph: ");
paragraph.setLocation(20, 70);
paragraph.setSize(70, 15);
paragraph.setHorizontalAlignment(0);
add(paragraph);
// JTextFields
nameField = new JTextField(8);
nameField.setLocation(90, 30);
nameField.setSize(150, 18);
add(nameField);
topicField = new JTextField(8);
topicField.setLocation(60, 50);
topicField.setSize(180, 18);
add(topicField);
// JTextAreas
paragraphArea = new JTextArea(8, 5);
paragraphArea.setLocation(20, 85);
paragraphArea.setSize(450, 100);
paragraphArea.setLineWrap(true);
paragraphArea.setEditable(true);
JScrollPane scrollParagraph = new JScrollPane(paragraphArea);
scrollParagraph
.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(paragraphArea);
// JButton
JButton submitButton = new JButton("SUBMIT");
submitButton.setLocation(250, 30);
submitButton.setSize(100, 30);
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
topicTotal = topicTotal + "/n" + nameField + "/n" + topicTotal
+ "/n" + paragraphArea + "/n";
}
});
add(submitButton);
}
}
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);
}
}