I'm sorry for posting this but, I can't find out why my Array of JButtons won't display in my ButtonsPanel. After adding them, I tried using my code in a separate class to test my code and it worked!, but why don't my buttons show up in this class?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class WordGui extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JLabel lblNewLabel_1;
private JPanel buttonPanel;
private JTextArea txtrShuffleHistory;
private Word word ;
private boolean val;
private JButton btnGo;
private JButton button;
private JButton btnShuffleText;
private JPanel panel_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
com.jtattoo.plaf.noire.NoireLookAndFeel.setTheme("Small-Font","","05:Bageo,Dexter");
UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel");
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WordGui frame = new WordGui();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WordGui() {
setTitle("Word App Gui");
setResizable(false);
setBounds(new Rectangle(100, 100, 600, 200));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 719, 394);
contentPane = new JPanel();
contentPane.setBounds(new Rectangle(100, 100, 600, 200));
contentPane.setSize(new Dimension(600, 250));
contentPane.setPreferredSize(new Dimension(600, 250));
contentPane.setBorder(new LineBorder(new Color(204, 0, 255), 5, true));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(204, 0, 255), 3, true));
panel.setBounds(10, 11, 683, 45);
contentPane.add(panel);
panel_1 = new JPanel();
panel_1.setBorder(new LineBorder(new Color(204, 0, 255), 3, true));
panel_1.setBounds(140, 59, 553, 286);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel = new JLabel("Enter a new word here:");
lblNewLabel.setBounds(10, 11, 183, 14);
panel_1.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(224, 8, 157, 20);
panel_1.add(textField);
textField.setColumns(10);
btnGo = new JButton("Go");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
if(ev.getSource()== btnGo){
assignWord(textField.getText());
}
}
});
btnGo.setBounds(391, 7, 57, 23);
panel_1.add(btnGo);
JLabel lblOriginalText = new JLabel("Original Text:");
lblOriginalText.setBounds(10, 36, 84, 14);
panel_1.add(lblOriginalText);
lblNewLabel_1 = new JLabel("New label");
lblNewLabel_1.setToolTipText("This is the original text entered\r\n");
lblNewLabel_1.setHorizontalTextPosition(SwingConstants.CENTER);
lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel_1.setBorder(new LineBorder(new Color(204, 0, 255), 3, true));
lblNewLabel_1.setBounds(90, 36, 358, 79);
panel_1.add(lblNewLabel_1);
JLabel lblShuffledText = new JLabel("Shuffled Text:");
lblShuffledText.setBounds(10, 126, 110, 14);
panel_1.add(lblShuffledText);
buttonPanel = new JPanel();
buttonPanel.setBorder(new LineBorder(new Color(204, 0, 255), 4, true));
buttonPanel.setBounds(10, 147, 533, 56);
panel_1.add(buttonPanel);
buttonPanel.setLayout(new GridLayout(1, 0, 0, 0));
btnShuffleText = new JButton("Shuffle Text");
btnShuffleText.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
if(ev.getSource() == btnShuffleText){
shuffle();
}
}
});
btnShuffleText.setBounds(90, 214, 196, 39);
panel_1.add(btnShuffleText);
button = new JButton("Reset");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
if(ev.getSource() == button){
textField.setText("");
getGoBtn().setEnabled(true);
getShuffleBtn().setEnabled(false);
getButtonPanel().removeAll();
}
}
});
button.setBounds(294, 214, 196, 39);
panel_1.add(button);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBounds(10, 59, 128, 258);
contentPane.add(scrollPane);
txtrShuffleHistory = new JTextArea();
txtrShuffleHistory.setToolTipText("View Shuffle History");
txtrShuffleHistory.setText("Shuffle History\r\n=================");
txtrShuffleHistory.setEditable(false);
scrollPane.setViewportView(txtrShuffleHistory);
JButton btnClear = new JButton("Clear");
btnClear.setBounds(10, 322, 126, 23);
contentPane.add(btnClear);
valid();
}
public void valid(){
JTextField field = new JTextField();
while(val == false){
int result = JOptionPane.showConfirmDialog(null,field, "Enter a Text?", JOptionPane.OK_CANCEL_OPTION);
if(result == JOptionPane.OK_OPTION){
String s = field.getText();
assignWord(s);
}
else if(result == JOptionPane.CANCEL_OPTION){
getResetBtn().setEnabled(false);
getShuffleBtn().setEnabled(false);
val = true;
}
}
}
public void assignWord(String s){
try{word = new Word(s);
val = true;
getTextLabel().setText("<html><body><font size = 30 >"+s+"</font></body></html>");
getTextArea().append("\nOriginal Word :"+s+"\n=================");
getGoBtn().setEnabled(false);
getResetBtn().setEnabled(true);
getShuffleBtn().setEnabled(true);
}
catch(RuntimeException e){JOptionPane.showMessageDialog(getParent(),e.getMessage()); val = false;}
}
public void shuffle(){
word.shuffle();
getButtonPanel().removeAll();
String temp = word.getShuffledText();
JButton[] buttons = new JButton[word.getText().length()];
for(int x = 0; x < word.getShuffledText().length(); x++){
buttons[x] = new JButton(""+temp.charAt(x));
getBody().add(buttons[x]);
buttons[x].setVisible(true);
}
getTextArea().append("\n"+word.getShuffledText());
}
public JLabel getTextLabel() {
return lblNewLabel_1;
}
public JPanel getButtonPanel() {
return buttonPanel;
}
public JTextArea getTextArea() {
return txtrShuffleHistory;
}
public JTextField getTextField() {
return textField;
}
public JButton getGoBtn() {
return btnGo;
}
public JButton getResetBtn() {
return button;
}
public JButton getShuffleBtn() {
return btnShuffleText;
}
public JPanel getBody() {
return panel_1;
}
}
I have the shuffle method which does the adding of JButtons, I'm sorry for posting this long long code, but can somebody compile this and figure out why the buttons wont show ? I tried changing the panels layout but still doesn't work,
here's the supporting class
import java.util.*;
public class Word {
private String text;
private List<Character> charList;
private String shuffled;
public Word(String str) {
if (str.length() < 3) {
throw new RuntimeException("Word must be more than 2 characters...");
}
if(invalid(str)) {
throw new RuntimeException("Word must not be composed of a single character...");
}
text = str.toUpperCase();
charList = getChars();
shuffle();
}
private boolean invalid(String s) {
int count = 1;
for (int i = 1; i < s.length(); i++) {
if (Character.toLowerCase(s.charAt(0)) == Character.toLowerCase(s.charAt(i)))
count++;
}
return (count == s.length());
}
private ArrayList<Character> getChars() {
ArrayList<Character> tempList = new ArrayList<Character>();
for (int i = 0; i < text.length(); i++) {
tempList.add(text.charAt(i));
}
return tempList;
}
public void shuffle() {
String orig = shuffled;
String tempShuffled;
do {
Collections.shuffle(charList);
tempShuffled = listToString();
} while (tempShuffled.equals(orig) || tempShuffled.equals(text));
shuffled = tempShuffled;
}
private String listToString() {
String strTemp = "";
for (Character ch: charList) {
strTemp += ch;
}
return strTemp;
}
public String toString() {
return text;
}
public String getShuffledText() {
return shuffled;
}
public String getText(){
return text;
}
}
You're using absolute positioning (null layout) for the JPanel panel_1. Each component in the JButton array buttons will have a default size of 0 x 0 so will not appear.
Swing was designed to use a layout manager so its recommended to always use one.
It removes the need to set component dimensions and locations. Use one for panel_1, such as GridLayout.
Also invoke
panel_1.revalidate();
panel_1.repaint();
after adding all of the buttons from the array.
Aside: Java naming conventions show that variables use camelCase such as panelOne instead of panel_1.
panel_1.setLayout(null);
Here, you're basically left with absolute positioning, so you'll need to set size and position for each of your JButtons. Use setBounds
Related
I am trying to stop my JDialog from closing when the Enter key is pushed. I have already tried using getRootPane().setDefaultButton(null); but it is still not working. I am calling this constructor for my JDialog from the main JFrame. Here is my code:
public class CustomSaleDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField txtScanBarcode;
private JTextField txtNumSold;
private String barcode;
private int numTickets;
public void setNumTickets(int num) {
numTickets = num;
}
public void setBarCode(String code) {
barcode = code;
}
public int getNumTickets() {
return numTickets;
}
public String getBarCode() {
return barcode;
}
public CustomSaleDialog(JFrame f) {
getRootPane().setDefaultButton(null); //This is what I tried
setTitle("Custom Sale");
setBounds(100, 100, 450, 300);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
JLabel lblMakeACustom = new JLabel("Make a Custom Sale");
lblMakeACustom.setFont(new Font("Tahoma", Font.PLAIN, 25));
lblMakeACustom.setHorizontalAlignment(SwingConstants.CENTER);
lblMakeACustom.setBounds(10, 11, 414, 44);
contentPanel.add(lblMakeACustom);
}
{
JLabel lblScanTicket = new JLabel("Scan Ticket");
lblScanTicket.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblScanTicket.setBounds(20, 73, 102, 20);
contentPanel.add(lblScanTicket);
}
{
JLabel lblNumberOfTickets = new JLabel("Number of Tickets Being Sold");
lblNumberOfTickets.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblNumberOfTickets.setBounds(20, 136, 262, 25);
contentPanel.add(lblNumberOfTickets);
}
{
txtScanBarcode = new JTextField();
txtScanBarcode.setBounds(132, 73, 284, 20);
contentPanel.add(txtScanBarcode);
txtScanBarcode.setColumns(10);
}
{
txtNumSold = new JTextField();
txtNumSold.setBounds(292, 141, 124, 20);
contentPanel.add(txtNumSold);
txtNumSold.setColumns(10);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
barcode = txtScanBarcode.getText();
String numTickets = txtNumSold.getText();
int numTicketsInt = 0;
if (barcode.length() > 0
&& numTickets.matches("[0-9]+")
&& numTickets.length() >= 1) {
numTicketsInt = Integer.parseInt(numTickets);
setBarCode(barcode);
setNumTickets(numTicketsInt);
}
setVisible(false);
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
setLocationRelativeTo(f);
setVisible(true);
}
}
And you forget to remove...
getRootPane().setDefaultButton(okButton);
This...
is why you don't use null layouts
Set focusable method or something like this that focuses to false.
remove this line getRootPane().setDefaultButton(okButton); it should work :)
being new to programming, i'm having a slight issue resizing the text fields I've added to the JPanel. While I could go the route of creating individual panels with their own text field, I though it would be better to add all the components into one panel. Part of my overall idea is to have my add button reference the panel, containing the text fields, to add more text fields on the tracker for users to fill out, and while I can get the fields to display when I implement the setBounds method on my panel object, i'm having tough time figuring out how resize them in the panel itself. And if you have any other advice on my overall structure, I welcome it.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class UI {
JFrame frame;
JLabel Title,Name, CheckOut, CheckIn, Email;
JTextField NameField,CheckOutField, CheckInField, EmailField;
JButton Add, Delete;
JPanel buttons, textfields, primary;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UI window = new UI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public UI(){
design();
}
private void design(){
frame = new JFrame("Form 48 Tracker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 750, 400);
frame.getContentPane().setLayout(null);
Title = new JLabel();
Title.setText("Form 48 Tracker");
Title.setFont(new Font("Calibri", Font.PLAIN, 28));
Title.setBounds(233, 11, 200, 75);
frame.getContentPane().add(Title);
Title.setForeground(Color.BLACK);
Name = new JLabel();
Name.setText("Name");
Name.setFont(new Font("Calibri", Font.PLAIN, 15));
Name.setBounds(50, 80, 128, 20);
frame.getContentPane().add(Name);
Name.setForeground(Color.BLACK);
CheckOut = new JLabel();
CheckOut.setText("Check Out Date");
CheckOut.setFont(new Font("Calibri", Font.PLAIN, 15));
CheckOut.setBounds(200, 80, 128, 20);
frame.getContentPane().add(CheckOut);
CheckOut.setForeground(Color.BLACK);
CheckIn = new JLabel();
CheckIn.setText("Check In Date");
CheckIn.setFont(new Font("Calibri", Font.PLAIN, 15));
CheckIn.setBounds(350, 80, 128, 20);
frame.getContentPane().add(CheckIn);
CheckIn.setForeground(Color.BLACK);
Email = new JLabel();
Email.setText("Email");
Email.setFont(new Font("Calibri", Font.PLAIN, 15));
Email.setBounds(500, 80, 128, 20);
frame.getContentPane().add(Email);
Email.setForeground(Color.BLACK);
Add = new JButton("Add");
buttons = new JPanel();
buttons.add(Add);
buttons.setBounds(200, 270, 157, 50); //x , y , width , height//
frame.getContentPane().add(buttons);
Add.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
Delete = new JButton("Delete");
buttons = new JPanel();
buttons.add(Delete);
buttons.setBounds(605, 101, 128, 50);
frame.getContentPane().add(buttons);
primary = new JPanel();
NameField = new JTextField();
CheckOutField = new JTextField();
CheckInField = new JTextField();
EmailField = new JTextField();
primary.add(NameField);
primary.add(CheckOutField);
primary.add(CheckInField);
primary.add(EmailField);
primary.setBounds(50, 110, 128, 20);
frame.getContentPane().add(primary);
}
}
Let's concentrate on the code that's causing the problem, and only that code. I've created a minimal example program, one that has enough code to compile and run, and that demonstrates the problem, but that has no unnecessary code:
import javax.swing.*;
public class UiFoo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null); // **** no!! ****
JPanel primary = new JPanel();
JTextField NameField = new JTextField();
JTextField CheckOutField = new JTextField();
JTextField CheckInField = new JTextField();
JTextField EmailField = new JTextField();
primary.add(NameField);
primary.add(CheckOutField);
primary.add(CheckInField);
primary.add(EmailField);
primary.setBounds(50, 110, 128, 20);
frame.getContentPane().add(primary);
frame.setSize(600, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
So, if you run this code, you'll see 4 very small JTextFields. Why are they so small? Because you've not set the columns property for the JTextFields, and so they default to columns size 0 and show up like so:
So it's better if you can give the JTextField a columns property so that they have some width, e.g., make this change:
JPanel primary = new JPanel();
int columns = 8;
JTextField NameField = new JTextField(columns);
JTextField CheckOutField = new JTextField(columns);
JTextField CheckInField = new JTextField(columns);
JTextField EmailField = new JTextField();
But this just shows one JTextField, and cuts off the bottom as well:
Why? Because you're artificially constraining the size of the containing JPanel, primary via:
primary.setBounds(50, 110, 128, 20);
This containing JPanel is only 128 pixels wide by 20 pixels high, meaning that it won't even display one JTextField well.
One solution is to use a mix of layout managers and JPanels as well as a JScrollPane to allow for a grid of JPanels to be added, something like so (try it out!):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class UiFoo2 extends JPanel {
JPanel singleColumnPanel = new JPanel(new GridLayout(0, 1, 2, 2));
public UiFoo2() {
JButton addButton = new JButton("Add");
addButton.addActionListener(e -> {
JPanel rowPanel = new JPanel(new GridLayout(1, 4, 2, 2));
for (int i = 0; i < 4; i++) {
rowPanel.add(new JTextField(8));
}
singleColumnPanel.add(rowPanel);
singleColumnPanel.revalidate();
singleColumnPanel.repaint();
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
JPanel labelPanel = new JPanel(new GridLayout(1, 4, 2, 2));
labelPanel.add(new JLabel("Name", SwingConstants.CENTER));
labelPanel.add(new JLabel("Check Out Date", SwingConstants.CENTER));
labelPanel.add(new JLabel("Check In Date", SwingConstants.CENTER));
labelPanel.add(new JLabel("Email", SwingConstants.CENTER));
singleColumnPanel.add(labelPanel);
JPanel containerPanel = new JPanel(new BorderLayout(5, 5));
containerPanel.add(singleColumnPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(containerPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setPreferredSize(new Dimension(650, 400));
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
UiFoo2 mainPanel = new UiFoo2();
JFrame frame = new JFrame("UiFoo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
This will create a row JPanel that holds four JTextFields that get added to the JScrollPane when the add JButton is pressed, and looks like so:
but we still can do better. Why not instead create a class to hold a row of data, something like so:
import java.util.Date;
public class Form48Customer {
private String name;
private Date checkIn;
private Date checkOut;
private String Email;
public Form48Customer(String name, Date checkIn, Date checkOut, String email) {
this.name = name;
this.checkIn = checkIn;
this.checkOut = checkOut;
Email = email;
}
public Date getCheckIn() {
return checkIn;
}
public void setCheckIn(Date checkIn) {
this.checkIn = checkIn;
}
public Date getCheckOut() {
return checkOut;
}
public void setCheckOut(Date checkOut) {
this.checkOut = checkOut;
}
public String getName() {
return name;
}
public String getEmail() {
return Email;
}
// should override hashCode and equals here
}
and then create a JTable complete with custom model to display objects of this type, and then display them in the GUI. This is much cleaner, more flexible, and extendable. Something like so:
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.*;
import java.util.Date;
import javax.swing.*;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.table.*;
#SuppressWarnings("serial")
public class Form48TrackerPanel extends JPanel {
public static final String TITLE = "Form 48 Tracker";
private static final String DATE_FORMAT_TXT = "MM/dd/yyyy";
private Form48TableModel model = new Form48TableModel();
private JTable table = new JTable(model);
private JButton addButton = new JButton("Add");
private JButton deleteButton = new JButton("Delete");
private JButton exitButton = new JButton("Exit");
public Form48TrackerPanel() {
final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_TXT);
TableCellRenderer dateRenderer = new DefaultTableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if( value instanceof Date) {
value = dateFormat.format(value);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
};
table.getColumnModel().getColumn(1).setCellRenderer(dateRenderer);
table.getColumnModel().getColumn(2).setCellRenderer(dateRenderer);
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 28f));
addButton.addActionListener(new AddListener());
addButton.setMnemonic(KeyEvent.VK_A);
deleteButton.addActionListener(new DeleteListener());
deleteButton.setMnemonic(KeyEvent.VK_D);
exitButton.addActionListener(new ExitListener());
exitButton.setMnemonic(KeyEvent.VK_X);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(exitButton);
setPreferredSize(new Dimension(800, 500));
int ebGap = 8;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
setLayout(new BorderLayout(ebGap, ebGap));
add(titleLabel, BorderLayout.PAGE_START);
add(new JScrollPane(table), BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
model.addRow(new Form48Customer("John Smith", new Date(), new Date(), "JSmith#Yahoo.com"));
model.addRow(new Form48Customer("Fred Flinstone", new Date(), new Date(), "FFlinstone#GMail.com"));
}
private class AddListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
AddForm48Panel addFormPanel = new AddForm48Panel();
int result = JOptionPane.showConfirmDialog(Form48TrackerPanel.this,
addFormPanel, "Add Customer", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
Form48Customer customer = addFormPanel.getForm48Customer();
model.addRow(customer);
}
}
}
private class DeleteListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO *** finish this code ***
}
}
private class ExitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor(Form48TrackerPanel.this);
win.dispose();
}
}
private static void createAndShowGui() {
Form48TrackerPanel mainPanel = new Form48TrackerPanel();
JFrame frame = new JFrame(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class AddForm48Panel extends JPanel {
private static final int TFIELD_COLS = 10;
private static final String DATE_FORMAT_TXT = "MM/dd/yyyy";
private static final Format DATE_FORMAT = new SimpleDateFormat(DATE_FORMAT_TXT);
private static final Insets INSETS = new Insets(5, 5, 5, 5);
private JTextField nameField = new JTextField(TFIELD_COLS);
private JFormattedTextField checkOutDateField = new JFormattedTextField(DATE_FORMAT);
private JFormattedTextField checkInDateField = new JFormattedTextField(DATE_FORMAT);
private JTextField emailField = new JTextField(TFIELD_COLS);
private JComponent[] fields = {nameField, checkOutDateField, checkInDateField, emailField};
private String[] labels = {"Name", "Check Out Date", "Check In Date", "Email"};
public AddForm48Panel() {
InputVerifier verifier = new DateFieldVerifier();
checkInDateField.setInputVerifier(verifier);
checkOutDateField.setInputVerifier(verifier);
setLayout(new GridBagLayout());
for (int i = 0; i < fields.length; i++) {
add(new JLabel(labels[i] + ":"), createGbc(0, i));
add(fields[i], createGbc(1, i));
}
}
public String getName() {
return nameField.getText();
}
public String getEmail() {
return emailField.getText();
}
public Date getCheckOut() {
return (Date) checkOutDateField.getValue();
}
public Date getCheckIn() {
return (Date) checkInDateField.getValue();
}
public Form48Customer getForm48Customer() {
String name = getName();
Date checkOut = getCheckOut();
Date checkIn = getCheckIn();
String email = getEmail();
return new Form48Customer(name, checkIn, checkOut, email);
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = INSETS;
gbc.anchor = x == 0 ? GridBagConstraints.WEST :GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
return gbc;
}
private class DateFieldVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
if (input instanceof JFormattedTextField) {
JFormattedTextField ftf = (JFormattedTextField)input;
AbstractFormatter formatter = ftf.getFormatter();
if (formatter != null) {
String text = ftf.getText();
try {
formatter.stringToValue(text);
return true;
} catch (ParseException pe) {
return false;
}
}
}
return true;
}
#Override
public boolean shouldYieldFocus(JComponent input) {
boolean verify = verify(input);
if (!verify) {
String message = "Enter a valid date, e.g.: 01/05/2017";
String title = "Invalid Date Format";
int type = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(input, message, title, type);
}
return verify;
}
}
}
#SuppressWarnings("serial")
class Form48TableModel extends DefaultTableModel {
private static final String[] COL_NAMES = {"Name", "Check Out Date", "Check In Date", "Email"};
public Form48TableModel() {
super(COL_NAMES, 0);
}
public void addRow(Form48Customer customer) {
Object[] rowData = {
customer.getName(),
customer.getCheckOut(),
customer.getCheckIn(),
customer.getEmail()
};
addRow(rowData);
}
public Form48Customer getRow(int row) {
String name = (String) getValueAt(row, 0);
Date checkIn = (Date) getValueAt(row, 1);
Date checkOut = (Date) getValueAt(row, 2);
String email = (String) getValueAt(row, 3);
return new Form48Customer(name, checkIn, checkOut, email);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 1:
return Date.class;
case 2:
return Date.class;
default:
break;
}
return super.getColumnClass(columnIndex);
}
}
Which would look like:
I'm trying to filter data in my array list according to my comboBox selected item wise. I still can't solve this problem.
public class FoodItem {
private String name;
private String type;
public FoodItem(String n,String t){
name=n;
type=t;
}
public String getType(){
return type;
}
public String getName(){
return name;
}
}
sample.java
<code>
public class A2Demo extends JFrame {
private JPanel contentPane;
private JTextField txtName;
List listFoodItem = new List();
JComboBox comboType = new JComboBox();
FoodItem[] foodItems;
private final JTextField txtBudget = new JTextField();
private final JButton btnBudget = new JButton("Search Budget");
private final JTextField textField = new JTextField();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
A2Demo frame = new A2Demo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public A2Demo() {
textField.setBounds(93, 247, 134, 28);
textField.setColumns(10);
txtBudget.setBounds(183, 11, 86, 20);
txtBudget.setColumns(10);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 334);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
foodItems=new FoodItem[2];
foodItems[0]=new FoodItem("Chicken Cutlet","Main");
foodItems[1]=new FoodItem("Chendol","Dessert");
comboType.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
comboType.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
JOptionPane.showMessageDialog(null,comboType.getSelectedItem());
}
});
comboType.setBounds(32, 11, 93, 20);
contentPane.add(comboType);
for(int i=0; i<foodItems.length; i++)
comboType.addItem(foodItems[i].getType());
listFoodItem.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
txtName.setText(listFoodItem.getSelectedItem());
}
});
listFoodItem.setBounds(37, 63, 330, 125);
contentPane.add(listFoodItem);
JLabel lblName = new JLabel("Name");
lblName.setBounds(37, 217, 46, 14);
contentPane.add(lblName);
txtName = new JTextField();
txtName.setBounds(93, 214, 134, 20);
contentPane.add(txtName);
txtName.setColumns(10);
contentPane.add(txtBudget);
btnBudget.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, comboType.getSelectedItem()+ " "+txtBudget.getText());
}
});
btnBudget.setBounds(280, 10, 127, 23);
contentPane.add(btnBudget);
contentPane.add(textField);
}
}
i want to display food name in the list. but combobox changeing to different type my list need to change according l
Something strange happened to me. For some reason, it takes a long time(1.60900 seconds) till it runs the following line:
textArea = new JTextArea();
I declared textArea variable as globally.
This only happens in one window (Jframe). In others it does not happen.
public class FAQ extends JFrame
{
/*--------attributes--------*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panel;
private JScrollPane scrollPaneInput;
private JScrollPane scrollPaneQuestions;
private JPanel paneQuestions;
private JPanel paneSelectOrNewFAQ;
private JButton btnEditSelection;
private JButton btnNewFAQ;
public JTextArea textArea;
private JLabel lblQuestions;
public JList list;
private User user;
private FAQ currentWindow;
private int selectedFaq = 0;
private DatabaseManager DManager;
private Vector<FAQ_class> Faqs = new Vector<FAQ_class>();
private JButton btnNewButton;
/*--------methods--------*/
public FAQ(User _user,DatabaseManager DM)
{
setResizable(false);
DManager = DM;
addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent arg0) {
}
});
addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent arg0) {
Menu menu = new Menu(user,DManager);
menu.setVisible(true);
}
});
currentWindow = this;
user = _user;
addGui();
if(!user.rule.equals("patient"))
{
btnEditSelection.setEnabled(true);
btnNewFAQ.setEnabled(true);
}
loadFaqs();
}//end of FAQ
public void loadFaqs()
{
Faqs = DManager.getQuestionsList();
Vector<String> temp = new Vector<String>();
for(int i = 0 ; i < Faqs.size();i++)
{
temp.addElement(Faqs.get(i).question);
}
list.setListData(temp);
}
public void addGui()
{
setTitle("FAQ - Online medical help");
setIconImage(Toolkit.getDefaultToolkit().getImage(FAQ.class.getResource("/Images/question.png")));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 708, 438);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(1, 0, 0, 0));
addPanel();
addPanes();
addButtons();
addGroupLayout();
addJTextArea();
}//end of addGui
public void addPanel()
{
panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.add(panel);
}//end of addPanel
public void addPanes()
{
scrollPaneInput = new JScrollPane();
scrollPaneInput.setBounds(327, 0, 365, 398);
paneQuestions = new JPanel();
paneQuestions.setBounds(0, 0, 317, 38);
paneQuestions.setBackground(new Color(154, 205, 50));
}//end of addScrollPanes
public void addButtons()
{
}//end of addButtons
public void addJTextArea()
{
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setFont(new Font("Courier New", Font.PLAIN, 14));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setAlignmentX(Component.RIGHT_ALIGNMENT);
scrollPaneInput.setViewportView(textArea);
}//end of addJTextArea
public void addGroupLayout()
{
lblQuestions = new JLabel("Questions");
lblQuestions.setHorizontalAlignment(SwingConstants.CENTER);
lblQuestions.setBounds(0, 0, 317, 38);
lblQuestions.setForeground(new Color(255, 255, 255));
lblQuestions.setFont(new Font("Tahoma", Font.BOLD, 22));
panel.setLayout(null);
scrollPaneQuestions = new JScrollPane();
scrollPaneQuestions.setBounds(0, 37, 317, 318);
list = new JList();
list.setSelectionBackground(new Color(154, 205, 50));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
try
{
for(int i = 0; i<Faqs.size();i++)
{
if(!list.isSelectionEmpty())
if(Faqs.get(i).question.equals(list.getSelectedValue().toString()))
{
textArea.setText(Faqs.get(i).answer);
selectedFaq = i;
break;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
scrollPaneQuestions.setViewportView(list);
panel.add(scrollPaneQuestions);
panel.add(paneQuestions);
paneQuestions.setLayout(null);
paneQuestions.add(lblQuestions);
panel.add(scrollPaneInput);
paneSelectOrNewFAQ = new JPanel();
paneSelectOrNewFAQ.setBounds(0, 348, 317, 50);
btnEditSelection = new JButton("Edit Selected");
btnEditSelection.setBounds(68, 11, 131, 40);
btnEditSelection.setEnabled(false);
btnEditSelection.addActionListener(new ActionListener() {
//open EditFAQ to edit FAQ
public void actionPerformed(ActionEvent e) {
if(!list.isSelectionEmpty())
{
EditFAQ faq = new EditFAQ(user,Faqs.get(selectedFaq),currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
else
{
JOptionPane.showMessageDialog(null,"You must select for the list first.");
}
}
});
btnEditSelection.setIcon(new ImageIcon(FAQ.class.getResource("/Images/tool.png")));
btnNewFAQ = new JButton("New FAQ");
btnNewFAQ.setBounds(203, 11, 114, 40);
btnNewFAQ.setEnabled(false);
btnNewFAQ.addActionListener(new ActionListener() {
//open EditFAQ to make new FAQ
public void actionPerformed(ActionEvent e) {
EditFAQ faq = new EditFAQ(user,null,currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
});
btnNewFAQ.setMinimumSize(new Dimension(95, 23));
btnNewFAQ.setMaximumSize(new Dimension(95, 23));
btnNewFAQ.setPreferredSize(new Dimension(95, 23));
btnNewFAQ.setIcon(new ImageIcon(FAQ.class.getResource("/Images/add.png")));
btnNewButton = new JButton("");
btnNewButton.setBounds(0, 10, 42, 41);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnNewButton.setIcon(new ImageIcon(FAQ.class.getResource("/Images/left.png")));
panel.add(paneSelectOrNewFAQ);
paneSelectOrNewFAQ.setLayout(null);
paneSelectOrNewFAQ.add(btnNewButton);
paneSelectOrNewFAQ.add(btnEditSelection);
paneSelectOrNewFAQ.add(btnNewFAQ);
}//end of addGroupLayout
}//end of class
Something strange happened to me. For some reason, it takes a long time(5 second~) till it runs the following line: Run this class and give me the result:
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JTextArea;
public class JTextAreaRunningTime {
JTextArea textArea;
public JTextAreaRunningTime(){
long startTime = System.currentTimeMillis();
textArea = new JTextArea();
long endTime = System.currentTimeMillis();
NumberFormat nf = new DecimalFormat("#0.00000");
String totalTime = nf.format((endTime-startTime)/1000d);
System.out.println("Execution time is " + totalTime + " seconds");
}
public static void main (String...argW){
new JTextAreaRunningTime();
}
}
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);
}
}