I have a Table inside Jpanel and the size of the table is fixed i wanted to make it dynamic. if we maximize the frame the size of the table should increase
below is the code
public class LogsAutomationUIFrame extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTable table;
private JTextField fieldDownloadPath = new JTextField(30);
JLabel lblNewLabel_4;
JLabel lblNewLabel_3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LogsAutomationUIFrame frame = new LogsAutomationUIFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
static DefaultTableModel model= new DefaultTableModel(0, 0);
private JPasswordField passwordField;
/**
* Create the frame.
*/
public LogsAutomationUIFrame() {
JFrame frame = new JFrame();
table = new JTable();
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
table.setAutoCreateRowSorter(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 783, 567);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblEnvironment = new JLabel("Environment");
lblEnvironment.setBounds(10, 44, 81, 21);
contentPane.add(lblEnvironment);
/*textField = new JTextField();
textField.setBounds(103, 44, 109, 20);
contentPane.add(textField);*/
//textField.setColumns(10);
String[] choices = { "CHOICE 1","CHOICE 2", "CHOICE 3","CHOICE 4","CHOICE 5","CHOICE 6"};
final JComboBox<String> cb = new JComboBox<String>();
//ComboBoxModel<String[]> choice = new ComboBoxModel<String[]>();
final File folder = new File("");
File folderParent = new File(folder.getAbsolutePath());
List<String> choiceVal = listFilesForFolder(folderParent);
//List<String> choiceVal = new ArrayList<String>();
cb.setModel(new ToComboBoxModel(choiceVal));
cb.setBounds(103, 44, 109, 20);
cb.setVisible(true);
contentPane.add(cb);
JLabel Path = new JLabel("Path");
Path.setBounds(10, 76, 46, 14);
contentPane.add(Path);
textField_1 = new JTextField();
textField_1.setBounds(103, 73, 109, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
JLabel lblNewLabel = new JLabel("Search String");
lblNewLabel.setBounds(10, 101, 81, 21);
contentPane.add(lblNewLabel);
textField_2 = new JTextField();
textField_2.setBounds(103, 101, 109, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);
JButton btnSearchString = new JButton("Search String");
btnSearchString.setBounds(231, 103, 137, 23);
btnSearchString.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try {
LogsAutomationServiceImpl serviceImpl = new LogsAutomationServiceImpl();
String searchEnvironment = cb.getSelectedItem().toString();
String searchPath = textField_1.getText();
String searchString = textField_2.getText();
/*Properties prop = LogsAutomationServiceImpl.getProperties();
lblNewLabel_4.setText(prop.getProperty("results_limit"));*/
//System.out.println("textField:::"+textField.getText());
String password = passwordField.getText();
model = serviceImpl.setTableData(searchEnvironment, searchPath, searchString, lblNewLabel_3, lblNewLabel_4, password);
table.setModel(model);
resizeColumnWidth(table);
table.setRowHeight(50);
} catch (Exception excption) {
excption.printStackTrace();
}
}
});
contentPane.add(btnSearchString);
JLabel lblNewLabel_1 = new JLabel("Results Number");
lblNewLabel_1.setBounds(10, 150, 101, 14);
contentPane.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel("Results Limit");
lblNewLabel_2.setBounds(10, 178, 81, 14);
contentPane.add(lblNewLabel_2);
lblNewLabel_3 = new JLabel();
lblNewLabel_3.setBounds(103, 150, 60, 14);
contentPane.add(lblNewLabel_3);
lblNewLabel_4 = new JLabel();
lblNewLabel_4.setBounds(103, 178, 60, 14);
contentPane.add(lblNewLabel_4);
Object[] columnNames = {"host", "folder", "file", "grepResult"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50)},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25)},
{"Sell", "Apple", new Integer(3000), new Double(7.35)},
{"Buy", "Nortel", new Integer(4000), new Double(20.00)}
};
table.setModel(model);
// table.setCellSelectionEnabled(true);
table.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
int row = table.rowAtPoint(evt.getPoint());
int col = table.columnAtPoint(evt.getPoint());
if (col == 2) {
System.out.println("row is :::"+ row+":::"+col+"::::"+table.getValueAt(row, col));
String fileName = table.getValueAt(row, col).toString();
String hostName = table.getValueAt(row, 0).toString();
String folderName = table.getValueAt(row, 1).toString();
Exec obj = new Exec();
String password = passwordField.getText();
obj.downloadFile(hostName, cb.getSelectedItem().toString(), fileName, folderName, password);
}
}
});
//table.getSelectionModel().addListSelectionListener(new CustomTableCellRenderer());
//table.setDefaultRenderer(Object.class, new CustomTableCellRenderer());
table.setSize(this.WIDTH, this.HEIGHT);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(10, 267, 650, 205);
getContentPane().add(scrollPane);
//scrollPane.setSize(this.WIDTH, this.HEIGHT);
contentPane.add(scrollPane, BorderLayout.CENTER);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(10, 212, 81, 14);
contentPane.add(lblPassword);
passwordField = new JPasswordField();
passwordField.setBounds(103, 203, 109, 20);
contentPane.add(passwordField);
contentPane.setSize(this.WIDTH, this.HEIGHT);
//frame.getContentPane().add(contentPane);
}
public static void resizeColumnWidth(JTable table) {
final TableColumnModel columnModel = table.getColumnModel();
for (int column = 0; column < table.getColumnCount(); column++) {
int width = 15; // Min width
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
width = Math.max(comp.getPreferredSize().width +1 , width);
}
if(width > 500)
width=500;
columnModel.getColumn(column).setPreferredWidth(width);
}
}
class MyRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
JTextField editor = new JTextField();
if (value != null)
editor.setText(value.toString());
editor.setBackground((row % 2 == 0) ? Color.white : Color.cyan);
return editor;
}
}
public static List<String> listFilesForFolder(final File folder) {
List<String> fileNames = new ArrayList<String>();
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
if(fileEntry.getName().toString().contains(".properties")) {
fileNames.add(fileEntry.getName());
}
}
}
return fileNames;
}
}
I tried so many ways looking at the stack overflow links like setting size to "this.widht" and "this.height" none of them worked.
when i make the Jpanel width to "this.width" and launch the application the size is very very small and
when i tried to put the same thing for scrollbar data is not getting displayed
I would first add the JTable to a JScrollPane, then add this JScrollPane to a JPanel, having a LayoutManager like BorderLayout and then add the JPanel to the JFrame... something like this:
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JScrollPane scp = new JScrollPane(table);
panel.add(BorderLayout.CENTER,scp);
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(BorderLayout.CENTER,panel);
this.pack();
this.setVisible(true);
As Sergiy mentioned, as soon, as there is a LayoutManger, it rocks...
Related
I attempt to send Text Field values to Table using button click event. But using combo box I need to change Unit type as "Imperial" or "Metric".
When select "Imperial" from combo box and Click ADD Button, Table should fill using "Name" , "Unit Imperial" & "Price Imperial" Text Field values.
But When select "Metric" from combo box and Click ADD Button,Table should fill using "Name" , "Unit Metric" & "Price Metric" Text Field values.
I don't have clear idea to use comboBox Item change use to effect on Button click event. Thanks in advance to guiding me to solve this problem.
public class UnitTable {
private JFrame frame;
private JTable table;
private JTextField txtName;
private JTextField txtUImp;
private JTextField txtPImp;
private JTextField txtUMetric;
private JTextField txtPMetric;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UnitTable window = new UnitTable();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public UnitTable() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 649, 288);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 10, 526, 181);
frame.getContentPane().add(scrollPane);
table = new JTable();
Object[] columns = { "Name", "Unit", "Price" };
DefaultTableModel model = new DefaultTableModel();
scrollPane.setViewportView(table);
model.setColumnIdentifiers(columns);
table.setModel(model);
JLabel lblName = new JLabel("Name");
lblName.setBounds(10, 201, 96, 13);
frame.getContentPane().add(lblName);
txtName = new JTextField();
txtName.setBounds(10, 224, 96, 19);
frame.getContentPane().add(txtName);
txtName.setColumns(10);
JLabel lblUImp = new JLabel("Unit Imperial");
lblUImp.setBounds(121, 201, 91, 13);
frame.getContentPane().add(lblUImp);
txtUImp = new JTextField();
txtUImp.setBounds(116, 224, 96, 19);
frame.getContentPane().add(txtUImp);
txtUImp.setColumns(10);
JLabel lblPImp = new JLabel("Price Imperial");
lblPImp.setBounds(222, 201, 96, 13);
frame.getContentPane().add(lblPImp);
txtPImp = new JTextField();
txtPImp.setBounds(222, 224, 96, 19);
frame.getContentPane().add(txtPImp);
txtPImp.setColumns(10);
JLabel lblUMetric = new JLabel("Unit Metric");
lblUMetric.setBounds(330, 201, 94, 13);
frame.getContentPane().add(lblUMetric);
txtUMetric = new JTextField();
txtUMetric.setBounds(328, 224, 96, 19);
frame.getContentPane().add(txtUMetric);
txtUMetric.setColumns(10);
JLabel lblPMetric = new JLabel("Price Metric");
lblPMetric.setBounds(434, 201, 102, 13);
frame.getContentPane().add(lblPMetric);
txtPMetric = new JTextField();
txtPMetric.setBounds(434, 224, 96, 19);
frame.getContentPane().add(txtPMetric);
txtPMetric.setColumns(10);
JButton btnAdd = new JButton("ADD");
Object[] row = new Object[3];
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
row[0] = txtName.getText();
row[1] = txtUImp.getText();
row[2] = txtPImp.getText();
model.addRow(row);
}
});
btnAdd.setBounds(546, 45, 85, 21);
frame.getContentPane().add(btnAdd);
JComboBox cmbUType = new JComboBox();
cmbUType.setModel(new DefaultComboBoxModel(new String[] { "Imperial", "Metric" }));
cmbUType.setBounds(546, 8, 85, 21);
frame.getContentPane().add(cmbUType);
JButton btnDelete = new JButton("DELETE");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = table.getSelectedRow();
if (i >= 0) {
model.removeRow(i);
} else {
JOptionPane.showMessageDialog(null, "Please Select Item to Delete");
}
}
});
btnDelete.setBounds(546, 76, 85, 21);
frame.getContentPane().add(btnDelete);
}
}
You should not be using a null layout and absolute positioning. Study Swing layout managers.
A JComboBox can hold any object. You need to tell the compiler what type of object (String) you're passing. You also need to tell the compiler what type of object you're storing in the DefaultComboBoxModel.
Having said that, I made cmbUType a class variable so I could reference it in the Add button action listener.
Here's your modified code.
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class UnitTable {
private JFrame frame;
private JTable table;
private JTextField txtName;
private JTextField txtUImp;
private JTextField txtPImp;
private JTextField txtUMetric;
private JTextField txtPMetric;
private JComboBox<String> cmbUType;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UnitTable window = new UnitTable();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public UnitTable() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 649, 288);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 10, 526, 181);
frame.getContentPane().add(scrollPane);
table = new JTable();
Object[] columns = { "Name", "Unit", "Price" };
DefaultTableModel model = new DefaultTableModel();
scrollPane.setViewportView(table);
model.setColumnIdentifiers(columns);
table.setModel(model);
JLabel lblName = new JLabel("Name");
lblName.setBounds(10, 201, 96, 13);
frame.getContentPane().add(lblName);
txtName = new JTextField();
txtName.setBounds(10, 224, 96, 19);
frame.getContentPane().add(txtName);
txtName.setColumns(10);
JLabel lblUImp = new JLabel("Unit Imperial");
lblUImp.setBounds(121, 201, 91, 13);
frame.getContentPane().add(lblUImp);
txtUImp = new JTextField();
txtUImp.setBounds(116, 224, 96, 19);
frame.getContentPane().add(txtUImp);
txtUImp.setColumns(10);
JLabel lblPImp = new JLabel("Price Imperial");
lblPImp.setBounds(222, 201, 96, 13);
frame.getContentPane().add(lblPImp);
txtPImp = new JTextField();
txtPImp.setBounds(222, 224, 96, 19);
frame.getContentPane().add(txtPImp);
txtPImp.setColumns(10);
JLabel lblUMetric = new JLabel("Unit Metric");
lblUMetric.setBounds(330, 201, 94, 13);
frame.getContentPane().add(lblUMetric);
txtUMetric = new JTextField();
txtUMetric.setBounds(328, 224, 96, 19);
frame.getContentPane().add(txtUMetric);
txtUMetric.setColumns(10);
JLabel lblPMetric = new JLabel("Price Metric");
lblPMetric.setBounds(434, 201, 102, 13);
frame.getContentPane().add(lblPMetric);
txtPMetric = new JTextField();
txtPMetric.setBounds(434, 224, 96, 19);
frame.getContentPane().add(txtPMetric);
txtPMetric.setColumns(10);
JButton btnAdd = new JButton("ADD");
Object[] row = new Object[3];
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String type = (String) cmbUType.getSelectedItem();
if (type.equals("Imperial")) {
row[0] = txtName.getText();
row[1] = txtUImp.getText();
row[2] = txtPImp.getText();
} else {
row[0] = txtName.getText();
row[1] = txtUMetric.getText();
row[2] = txtPMetric.getText();
}
model.addRow(row);
}
});
btnAdd.setBounds(546, 45, 85, 21);
frame.getContentPane().add(btnAdd);
cmbUType = new JComboBox<>();
cmbUType.setModel(new DefaultComboBoxModel<String>
(new String[] { "Imperial", "Metric" }));
cmbUType.setBounds(546, 8, 85, 21);
frame.getContentPane().add(cmbUType);
JButton btnDelete = new JButton("DELETE");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = table.getSelectedRow();
if (i >= 0) {
model.removeRow(i);
} else {
JOptionPane.showMessageDialog(null, "Please Select Item to Delete");
}
}
});
btnDelete.setBounds(546, 76, 85, 21);
frame.getContentPane().add(btnDelete);
}
}
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.
I have two GUI classes. When I click a row in JTable in the first user interface, the second interface should display the corresponding values in JLabels.
But the second user interface does not show the values.
Here's my first GUI class:
public class ChequeGUI extends JFrame {
public String chqNo;
public String payName;
public double chkAmount = 10;
public Date chkDate;
JTable guiTable = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"Cheque Number","Payee Name","Cheque Amount","Cheque Date"});
public ChequeGUI() throws SQLException {
guiTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
//guiTable.getTableHeader().getDefaultRenderer();
int row = guiTable.getSelectedRow();
chqNo = (String) guiTable.getValueAt(row,0);
payName = (String) guiTable.getValueAt(row,1);
chkAmount = (Double) guiTable.getValueAt(row,2);
chkDate = (Date) guiTable.getValueAt(row, 3);
try {
PrintChequeGUI pcg = new PrintChequeGUI();
pcg.setTitle("Print Cheque");
pcg.setVisible(true);
System.out.println(chqNo);
System.out.println(payName);
System.out.println(chkAmount);
System.out.println(chkDate);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
guiTable.setModel(model);
add(new JScrollPane(guiTable));
DBConnection connection = new DBConnection();
//Populate Table
ChequeDAOImpl chqdi = new ChequeDAOImpl();
chqdi.setConnection(connection);
List<Cheque> cheques = chqdi.getCheques();
for(Cheque cq : cheques){
model.addRow(new Object[]{cq.getChqNum(), cq.getName(),cq.getAmount(),cq.getDate()});
}
}
}
This is my second GUI class:
public class PrintChequeGUI extends JFrame {
private JPanel contentPane;
private JTextField txtAmount;
/**
* Create the frame.
* #throws SQLException
*/
public PrintChequeGUI() throws SQLException {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 480, 400);
contentPane = new JPanel();
contentPane.setBackground(new Color(176, 224, 230));
contentPane.setForeground(SystemColor.inactiveCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 454, 84);
contentPane.add(panel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(220, 220, 220));
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_1.setBounds(10, 106, 454, 198);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("Date:");
lblNewLabel_1.setBounds(327, 11, 40, 14);
panel_1.add(lblNewLabel_1);
JLabel lblDate = new JLabel();
lblDate.setBounds(368, 11, 69, 14);
panel_1.add(lblDate);
JLabel lblNewLabel_2 = new JLabel("Payee to the Order of");
lblNewLabel_2.setBounds(10, 50, 125, 14);
panel_1.add(lblNewLabel_2);
JLabel lblName = new JLabel();
lblName.setBounds(134, 50, 214, 14);
panel_1.add(lblName);
JLabel lblRs = new JLabel("Rs.");
lblRs.setBounds(351, 50, 24, 14);
panel_1.add(lblRs);
JLabel lblAmount = new JLabel();
lblAmount.setBounds(375, 50, 69, 14);
panel_1.add(lblAmount);
txtAmount = new JTextField();
txtAmount.setBounds(10, 83, 338, 20);
panel_1.add(txtAmount);
txtAmount.setColumns(10);
JLabel lblRupees = new JLabel("Rupees");
lblRupees.setBounds(351, 86, 46, 14);
panel_1.add(lblRupees);
JLabel lbl = new JLabel("Cheque Number:");
lbl.setBounds(10, 126, 100, 14);
panel_1.add(lbl);
JLabel lblChequeNum = new JLabel();
lblChequeNum.setBounds(115, 126, 46, 14);
panel_1.add(lblChequeNum);
JLabel lblSig = new JLabel("<<Sig>>");
lblSig.setBounds(321, 151, 90, 14);
panel_1.add(lblSig);
JLabel lblSigName = new JLabel("A.B.C.Test Name");
lblSigName.setBounds(311, 176, 100, 14);
panel_1.add(lblSigName);
JPanel panel_2 = new JPanel();
panel_2.setBackground(new Color(220, 220, 220));
panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_2.setBounds(10, 315, 454, 40);
contentPane.add(panel_2);
panel_2.setLayout(null);
JButton btnPrint = new JButton("Print");
btnPrint.setBounds(102, 11, 89, 23);
panel_2.add(btnPrint);
JButton btnBack = new JButton("Back");
btnBack.setBounds(263, 11, 89, 23);
panel_2.add(btnBack);
ChequeGUI gui = new ChequeGUI();
lblChequeNum.setText(gui.chqNo);
lblAmount.setText(Double.toString(gui.chkAmount));
lblName.setText(gui.payName);
lblDate.setText(String.valueOf(gui.chkDate));
}
}
This can be solved in many ways:
1.
As I mentioned in my comment, Pass the current instance of ChequeGUI to the constructor of PrintChequeGUI and use that instance instead of creating new one in PrintChequeGUI
PrintChequeGUI pcg = new PrintChequeGUI(this);
and in PrintChequeGUI class
public PrintChequeGUI(ChequeGUI gui) throws SQLException {
(but i think its not a good approach)
2.
For Better option, Pass the selected instance of Cheque to PrintChequeGUI as constructor argument. For this you need to create a TableModel with instance of Cheque.
Sample is given below:
package com.test;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class ChequeGUI extends JFrame {
JTable guiTable = new JTable();
ChequeTableModel model;
public ChequeGUI() throws SQLException {
guiTable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// guiTable.getTableHeader().getDefaultRenderer();
int row = guiTable.getSelectedRow();
Cheque c = model.getChequeByRow(row);
try {
PrintChequeGUI pcg = new PrintChequeGUI(c);
pcg.setTitle("Print Cheque");
pcg.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
model = new ChequeTableModel();
guiTable.setModel(model);
add(new JScrollPane(guiTable));
model.loadData();
}
public class ChequeTableModel extends AbstractTableModel {
List<Cheque> dataModel;
String[] columns = { "Cheque Number", "Payee Name", "Cheque Amount",
"Cheque Date" };
public ChequeTableModel() {
super();
dataModel = new ArrayList<Cheque>();
}
#Override
public int getColumnCount() {
return columns.length;
}
#Override
public String getColumnName(int column) {
return columns[column];
}
#Override
public int getRowCount() {
return dataModel.size();
}
#Override
public Object getValueAt(int row, int column) {
Object value = null;
Cheque c = getChequeByRow(row);
switch (column) {
case 0:
value = c.chqNo;
break;
case 1:
value = c.payName;
break;
case 2:
value = c.chkAmount;
break;
case 3:
value = c.chkDate;
break;
default:
break;
}
return value;
}
public Cheque getChequeByRow(int row) {
if (dataModel.size() <= 0)
return null;
if (row < 0)
return null;
return dataModel.get(row);
}
public void loadData() {
/*
*
* //Uncomment this for database connection and load data from
* database; //Please note to disconnect database if not needed
*
*
* DBConnection connection = new DBConnection();
*
* // Populate Table ChequeDAOImpl chqdi = new ChequeDAOImpl();
* chqdi.setConnection(connection); List<Cheque> cheques =
* chqdi.getCheques();
*
* for (Cheque cq : cheques) { model.addRow(new Object[] {
* cq.getChqNum(), cq.getName(), cq.getAmount(), cq.getDate() }); }
*/
for (int i = 0; i < 10; i++) {
Cheque c = new Cheque();
c.chkAmount = i * 1000;
c.chqNo = String.valueOf(i);
c.chkDate = new Date(System.currentTimeMillis());
dataModel.add(c);
}
fireTableRowsInserted(0, dataModel.size());
}
}
public static void main(String[] args) throws SQLException {
ChequeGUI c = new ChequeGUI();
c.pack();
c.setVisible(true);
}
}
Second class
package com.test;
import java.awt.Color;
import java.awt.SystemColor;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class PrintChequeGUI extends JFrame {
private JPanel contentPane;
private JTextField txtAmount;
/**
* Create the frame.
*
* #throws SQLException
*/
public PrintChequeGUI(Cheque cheque) throws SQLException {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 480, 400);
contentPane = new JPanel();
contentPane.setBackground(new Color(176, 224, 230));
contentPane.setForeground(SystemColor.inactiveCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 454, 84);
contentPane.add(panel);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(220, 220, 220));
panel_1.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_1.setBounds(10, 106, 454, 198);
contentPane.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("Date:");
lblNewLabel_1.setBounds(327, 11, 40, 14);
panel_1.add(lblNewLabel_1);
JLabel lblDate = new JLabel();
lblDate.setBounds(368, 11, 69, 14);
panel_1.add(lblDate);
JLabel lblNewLabel_2 = new JLabel("Payee to the Order of");
lblNewLabel_2.setBounds(10, 50, 125, 14);
panel_1.add(lblNewLabel_2);
JLabel lblName = new JLabel();
lblName.setBounds(134, 50, 214, 14);
panel_1.add(lblName);
JLabel lblRs = new JLabel("Rs.");
lblRs.setBounds(351, 50, 24, 14);
panel_1.add(lblRs);
JLabel lblAmount = new JLabel();
lblAmount.setBounds(375, 50, 69, 14);
panel_1.add(lblAmount);
txtAmount = new JTextField();
txtAmount.setBounds(10, 83, 338, 20);
panel_1.add(txtAmount);
txtAmount.setColumns(10);
JLabel lblRupees = new JLabel("Rupees");
lblRupees.setBounds(351, 86, 46, 14);
panel_1.add(lblRupees);
JLabel lbl = new JLabel("Cheque Number:");
lbl.setBounds(10, 126, 100, 14);
panel_1.add(lbl);
JLabel lblChequeNum = new JLabel();
lblChequeNum.setBounds(115, 126, 46, 14);
panel_1.add(lblChequeNum);
JLabel lblSig = new JLabel("<<Sig>>");
lblSig.setBounds(321, 151, 90, 14);
panel_1.add(lblSig);
JLabel lblSigName = new JLabel("A.B.C.Test Name");
lblSigName.setBounds(311, 176, 100, 14);
panel_1.add(lblSigName);
JPanel panel_2 = new JPanel();
panel_2.setBackground(new Color(220, 220, 220));
panel_2.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
panel_2.setBounds(10, 315, 454, 40);
contentPane.add(panel_2);
panel_2.setLayout(null);
JButton btnPrint = new JButton("Print");
btnPrint.setBounds(102, 11, 89, 23);
panel_2.add(btnPrint);
JButton btnBack = new JButton("Back");
btnBack.setBounds(263, 11, 89, 23);
panel_2.add(btnBack);
// ChequeGUI gui = new ChequeGUI();
lblChequeNum.setText(cheque.chqNo);
lblAmount.setText(Double.toString(cheque.chkAmount));
lblName.setText(cheque.payName);
lblDate.setText(String.valueOf(cheque.chkDate));
}
}
The Cheque class you already used to get details from database
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
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);
}
}