Storing hundreds of tables/models - java

I know this information is everywhere but its so vast its hard to choose the right method. So even pointing me to right place works as well.
I am developing software for a client where he inputs his stock trades and it outputs the various data into a table. There is no accessing stock data of any sort, it is all internal and just for his personal use.
What I am stuck on is he wants to be able to shuffle through Monday to Friday, or view inputted data from a year ago. So how would I store the daily table data.
Should I save the table's models to a file or a database? Perhaps there is a different method I am unaware of.
The tables are 10 columns wide have about a 900 rows long if that matters to anyone.
Edit*
To answer the request for more code here is what I have broken down.`
MainFrame() {
super("Stack Overflow Stock Software");
model.addColumn("Exchange");
model.addColumn("Inv/Sec");
model.addColumn("Name");
model.addColumn("Qty");
// model.addColumn("Fd");
model.addColumn("Average Cost");
model.addColumn("Market");
model.addColumn("Balance");
// model.addColumn("Interest");
model.addColumn("Today's PL");
model.addColumn("Total Pl");
// model.addColumn("Multiplier");
// model.addRow(data);
table = new JTable(model);
modelTotal.addColumn("Balance");
modelTotal.addColumn("Today PL");
modelTotal.addColumn("Total PL");
table2 = new JTable(modelTotal);
setLayout(new BorderLayout());
// JComboBox<String> comboBox = new JComboBox<>(exchangeStrings);
// sorter = new TableRowSorter<TableModel>(table.getModel());
JPanel panel1 = new JPanel();
text1 = new JTextField(5);
text1.setText("ABA");
text1.setHorizontalAlignment(SwingConstants.CENTER);
text2 = new JTextField(12);
text2.setText("1000");// quanity
text2.setHorizontalAlignment(SwingConstants.CENTER);
text3 = new JTextField(10);
text3.setText("10.00");// price
text3.setHorizontalAlignment(SwingConstants.CENTER);
button1 = new JButton("Buy");
button1.addActionListener(this);
button2 = new JButton("Sell");
button2.addActionListener(this);
JScrollPane scrollPane = new JScrollPane(table);
JScrollPane scrollPane2 = new JScrollPane(table2);
// sets table settings
table.setFillsViewportHeight(true);
table.getColumnModel().getColumn(0).setMaxWidth(80);
table.getColumnModel().getColumn(1).setPreferredWidth(80);
table.getColumnModel().getColumn(2).setPreferredWidth(180);
table.getColumnModel().getColumn(4).setPreferredWidth(24);
table.getColumnModel().getColumn(6).setPreferredWidth(24);
table.getColumnModel().getColumn(7).setPreferredWidth(24);
// table.getColumnModel().getColumn(9).setPreferredWidth(0);
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
setCellsAlignment(table, SwingConstants.CENTER);
setCellsAlignment(table2, SwingConstants.CENTER);
// add panels/buttons/etc to page
add(panel1, BorderLayout.PAGE_START);
panel1.setPreferredSize(new Dimension(1280, 50));
add(scrollPane, BorderLayout.CENTER);
add(scrollPane2, BorderLayout.PAGE_END);
scrollPane2.setPreferredSize(new Dimension(1280, 50));
// add(scrollPane, BorderLayout.CENTER);
panel1.add(comboBox, BorderLayout.SOUTH);
panel1.add(text1, BorderLayout.SOUTH);
panel1.add(text3, BorderLayout.SOUTH);// price
panel1.add(text2, BorderLayout.SOUTH);
panel1.add(button1, BorderLayout.NORTH);
panel1.add(button2, BorderLayout.NORTH);
setMenuBar();
modelTotal.addRow(data2);
setExtendedState(MAXIMIZED_BOTH);
setMinimumSize(new Dimension(1280, 485));
setSize(640, 485);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void setMenuBar() {...}
/*Set the menu bar up*/
public static void setCellsAlignment(JTable table, int alignment) {
DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(alignment);
TableModel tableModel = table.getModel();
for (int columnIndex = 0; columnIndex < tableModel.getColumnCount(); columnIndex++) {
table.getColumnModel().getColumn(columnIndex).setCellRenderer(rightRenderer);
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {// if button 1 pressed to buy
purchaseMade = true;
// input data in data object for adding or combining.
String comboString = comboBox.getSelectedItem().toString();
String stringCombo = comboString;
data[0] = stringCombo;
data[1] = text1.getText();
data[2] = text1.getText(); // turn into long string
data[3] = text2.getText();// quanity
data[5] = text3.getText();// price
data[4] = text3.getText();// average market price
double String1 = Double.parseDouble(data[3].toString());
double String2 = Double.parseDouble(data[4].toString());
data[6] = String1 * String2;
double dataQuanity = Double.parseDouble(data[3].toString());
double dataPrice = Double.parseDouble(data[4].toString());
data[7] = dataQuanity * dataPrice * -1;
data[8] = dataQuanity * dataPrice * -1;
data[4] = Double.parseDouble(data[4].toString());
data[4] = df.format(data[4]);
data[5] = Double.parseDouble(data[5].toString());
data[5] = df.format(data[5]);
data[6] = Double.parseDouble(data[6].toString());
data[6] = df.format(data[6]);
data[7] = Double.parseDouble(data[7].toString());
data[7] = df.format(data[7]);
data[8] = Double.parseDouble(data[8].toString());
data[8] = df.format(data[8]);
// add data and continue on
model.addRow(data);
dataCount++;
combineData(model);
sortData(table);
}
if (e.getSource() == button2) {
purchaseMade = false;
// input data in data object for adding or combining.
data[0] = comboBox.getSelectedItem();// exchange
data[1] = text1.getText();// symbol
data[2] = text1.getText(); // turn into long string//name
data[3] = text2.getText();// quanity
data[4] = text3.getText();// average price
data[5] = text3.getText();// closing bid / market
data[9] = 1;
// data 5 can wait
double String1 = Double.parseDouble(data[3].toString());
double String2 = Double.parseDouble(data[4].toString());
data[6] = String1 * String2;
// pl
double dataQuanity = Double.parseDouble(data[3].toString());
double dataPrice = Double.parseDouble(data[4].toString());
data[7] = dataQuanity * dataPrice * -1;
data[8] = dataQuanity * dataPrice * -1;
// add data and continue on
dataCount++;
combineData(model);
sortData(table);
}
}
private void combineData(DefaultTableModel model2) {
/*This section of codes adds the new data to a table or combines it with a duplicate entry*/
}
private void sortData(JTable table) {...}
/*This is where I sort my table*/
private void calculateLowerData(DefaultTableModel lowerModel, DefaultTableModel dataModel) {...}
/* This is where I calculate a number not relevant to the question*/
private void printTable() {...}
/* This is where I print my data to a table */
}`

Chose a database that you're more familiar with, in preference Relational Database, and use the Date Time column as index for faster search
With a database is better because you will can get the data that you want specifying the parameters
If is to personal use only, you can choose a local database to the Operating System that you're using, like SQL Server, and make sure to perform backups
Hugs

Related

Random Number won't appear in a JTextField

I have a problem.I created a program that will add two random numbers. I'm trying to put a Math.random() in a JTextField but it won't appear. Here's my code by the way:
public class RandomMathGame extends JFrame {
public RandomMathGame(){
super("Random Math Game");
int random2;
JButton lvl1 = new JButton("LEVEL 1");
JButton lvl2 = new JButton("LEVEL 2");
JButton lvl3 = new JButton("LEVEL 3");
JLabel line1 = new JLabel("Line 1: ");
final JTextField jtf1 = new JTextField(10);
JLabel line2 = new JLabel("Line 2: ");
final JTextField jtf2 = new JTextField(10);
JLabel result = new JLabel("Result: ");
final JTextField jtf3 = new JTextField(10);
JButton ans = new JButton("Answer");
JLabel score = new JLabel("Score: ");
JTextField jtf4 = new JTextField(3);
JLabel itm = new JLabel("Number of Items: ");
JTextField items = new JTextField(3);
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(lvl1);
add(lvl2);
add(lvl3);
add(line1);
add(jtf1);
add(line2);
add(jtf2);
add(result);
add(jtf3);
add(ans);
add(score);
add(jtf4);
add(itm);
add(items);
setSize(140,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
lvl1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int i, j = 10;
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
int i3 = i1 + i2;
final int random1 = (int)(Math.random() * 10 + 1);
for (i = 0; i <= j + 1; i++){
try{
jtf1.setText(String.valueOf(random1));
jtf2.setText(String.valueOf(random1));
jtf3.setText(String.valueOf(i3));
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
}
Never mind the lvl2 and lvl3 because it's the same in lvl1. And also, I want to loop them 10 times. I'm having difficulties on putting up those codes. Can someone help me? Thanks for your help. :)
Updating text fields in a loop won't produce the animated display that you likely want; only the last update will be seen. Instead, use a javax.swing.Timer to periodically update the fields. Related examples may be found here, here and here.

Listbox in Java

I was trying to build the Font window of Notepad using Java using the code shown below. But, I'm facing a problem in setting the size of the text as specified inside listbox.
I'm trying to get the respective size corresponding to the index of the selected item but couldn't find any such method.
f = new Frame("Font");
f.setLayout(new GridLayout(3, 3));
b1 = new Button("OK");
l1 = new Label("Font :");
l2 = new Label("Size :");
l3 = new Label("Font Style :");
lb1 = new List(10, false);
lb2 = new List(10, false);
lb3 = new List(5, false);
String [] s = {"Times New Roman", "Arial", "Verdana", "Trebuchet MS", "Papyrus","Monotype Corsiva","Microsoft Sans Serif", "Courier", "Courier New"};
for(int i = 0; i < s.length; i++)
{
lb1.add(s[i]);
}
for(int i = 8; i <=72; i += 2)
{
lb2.add(i + "");
}
String [] s1 = {"BOLD", "ITALIC", "PLAIN"};
for(int i = 0; i < s1.length; i++)
{
lb3.add(s1[i]);
}
f.add(l1);
f.add(l2);
f.add(l3);
f.add(lb1);
f.add(lb2);
f.add(lb3);
f.add(b1);
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
if(lb3.isIndexSelected(0))
fo = new Font(lb1.getSelectedItem(), Font.BOLD, **lb2.getSelectedIndex**());
else if(lb3.isIndexSelected(1))
fo = new Font(lb1.getSelectedItem(), Font.ITALIC, lb2.getSelectedIndex());
else
fo = new Font(lb1.getSelectedItem(), Font.PLAIN, lb2.getSelectedIndex());
ta1.setFont(fo);
MyFrame15.f.dispose();
}
});
f.setSize(300, 300);
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int)((d.getWidth() / 2) - 200);
int y = (int)((d.getHeight() / 2) - 200);
f.setLocation(x, y);
f.setVisible(true);
}
To get the size as required by user we can use:
lb2.getSelectedItem();
which returns a String but the third argument of Font constructor requires an integer.Therefore, we use parseInt() method of Integer class to convert the string received to integer.The code is as follows:
Font(lb1.getSelectedItem(), Font.BOLD, Integer.parseInt(lb2.getSelectedItem()));
I would suggest you use Swing for this. You can start with the Swing tutorial on Text Component Features which already contains a working example that does what you want.

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String

I've been having problems running this program it compiles but doesn't run properly. When I run it and attempt to perform the calculations it spits out a bunch errors. I think it has to with variable types. Here is the program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class area extends JFrame implements ActionListener, ItemListener{
//row 1
JPanel row1 = new JPanel();
JLabel select = new JLabel("Please select what you would like to caculate the area and volume of.");
//row 2
JPanel row2 = new JPanel();
JCheckBox circle = new JCheckBox("Circle", false);
JCheckBox cube = new JCheckBox("Cube", false);
//row 3
JPanel row3 = new JPanel();
JLabel radlab = new JLabel("Radius of the circle (in cm)");
JTextField rad = new JTextField(3);
JLabel sidelab = new JLabel("A side of the cube (in cm)");
JTextField side = new JTextField(3);
//row4
JPanel row4 = new JPanel();
JButton solve = new JButton("Solve!");
//row 5
JPanel row5 = new JPanel();
JLabel areacallab = new JLabel("Area");
JTextField areacal = new JTextField(10);
JLabel volumelab = new JLabel("Volume");
JTextField volume = new JTextField(10);
public area(){
setTitle("Area Caculator");
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//disables all text areas
rad.setEnabled(false);
side.setEnabled(false);
areacal.setEnabled(false);
volume.setEnabled(false);
//add listeners
circle.addItemListener(this);
cube.addItemListener(this);
solve.addActionListener(this);
FlowLayout one = new FlowLayout(FlowLayout.CENTER);
setLayout(one);
row1.add(select);
add(row1);
row2.add(circle);
row2.add(cube);
add(row2);
row3.add(radlab);
row3.add(rad);
row3.add(sidelab);
row3.add(side);
add(row3);
row4.add(solve);
add(row4);
row5.add(areacallab);
row5.add(areacal);
row5.add(volumelab);
row5.add(volume);
add(row5);
}
public void circlepick(){
//cube.setCurrent(false);
cube.setEnabled(false);
rad.setEnabled(true);
}
public void cubepick(){
circle.setEnabled(false);
side.setEnabled(true);
}
#Override
public void itemStateChanged(ItemEvent event) {
Object item = event.getItem();
if (item == circle){
circlepick();
}
else if (item == cube){
cubepick();
}
}
#Override
public void actionPerformed(ActionEvent evt){
//String radi = rad.getText();
//String sid = side.getText();
//circlesolve();
//cubesolve();
String radi = rad.getText();
String sid = side.getText();
double radius = Double.parseDouble(radi);
double length = Double.parseDouble(sid);
double cirarea = Math.PI * Math.pow(radius, 2);
double cirvolume = (4.0 / 3) * Math.PI * Math.pow(radius, 3);
double cubearea = Math.pow(length, 2);
double cubevolume = Math.pow(length, 3);
areacal.setText("" + cirarea + cubearea + "");
volume.setText("" + cirvolume + cubevolume + "");
}
public static void main(String[] args) {
area are = new area();
}
}
Here are the errors is printing out when attempting to perform the math (sorry it really long).
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1038)
at java.lang.Double.parseDouble(Double.java:548)
at area.actionPerformed(area.java:112)
...
Thanks so much in advance for an help!
When calling the functions:
double radius = Double.parseDouble(radi);
double length = Double.parseDouble(sid);
either radi or sid is am Empty String, thats what
java.lang.NumberFormatException: empty String
tells you.
You might consider adding a System.out.println(raid + ", " + sid) before parsing to check what values are empty Strings and make sure, that the Strings are not empty.
Double.parseDouble(String s) throws a NumberFormatException when the given String s can not be parsed into a double value.

Java radio buttons

I'm having trouble with my radio buttons. I can click on all three at the same time. It should be when you click on one the other one turns off?
I'm using a grid layout. So when I try group.add it doesn't work.
Example:
I have the buttons declared like this
JRadioButton seven = new JRadioButton("7 years at 5.35%", false);
JRadioButton fifteen = new JRadioButton("15 years at 5.5%", false);
JRadioButton thirty = new JRadioButton("30 years at 5.75%", false);
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
This is my code:
/*Change Request #6
Write the program in Java (with a graphical user interface)
so that it will allow the user to select which way
they want to calculate a mortgage:
by input of the amount of the mortgage,
the term of the mortgage,
and the interest rate of the mortgage payment
or by input of the amount of a mortgage and
then select from a menu of mortgage loans:
- 7 year at 5.35%
- 15 year at 5.5 %
- 30 year at 5.75%
In either case, display the mortgage payment amount
and then, list the loan balance and interest paid
for each payment over the term of the loan.
Allow the user to loop back and enter a new amount
and make a new selection, or quit.
Insert comments in the program to document the program.
*/
import java.text.NumberFormat;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WK4 extends JFrame implements ActionListener
{
int loanTerms[] = { 7, 15, 30 };
double annualRates[] = { 5.35, 5.5, 5.75 };
// Labels
JLabel AmountLabel = new JLabel(" Loan Amount $ ");
JLabel PaymentLabel = new JLabel(" Monthly Payment ");
JLabel InterestLabel = new JLabel(" Interest Rate % ");
JLabel TermLabel = new JLabel(" Years of Loan ");
// Text Fields
JTextField mortgageAmount = new JTextField(6);
JTextField Payment = new JTextField(6);
JTextField InterestRate = new JTextField(3);
JTextField Term = new JTextField(3);
// Radio Buttons
ButtonGroup radioGroup = new ButtonGroup();
JRadioButton seven = new JRadioButton("7 years at 5.35%");
JRadioButton fifteen = new JRadioButton("15 years at 5.5%");
JRadioButton thirty = new JRadioButton("30 years at 5.75%");
// Buttons
JButton exitButton = new JButton("Exit");
JButton resetButton = new JButton("Reset");
JButton calculateButton = new JButton("Calculate ");
// Text Area
JTextArea LoanPayments = new JTextArea(20, 50);
JTextArea GraphArea = new JTextArea(20, 50);
JScrollPane scroll = new JScrollPane(LoanPayments);
public WK4(){
super("Mortgage Calculator");
//Window
setSize(700, 400);
setLocation(200, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel(new GridLayout(2, 2));
Container grid = getContentPane();
grid.setLayout(new GridLayout(4, 10, 0, 12)); //rows, cols, hgap, vgap
pane.add(grid);
pane.add(scroll);
grid.add(AmountLabel);
grid.add(mortgageAmount);
grid.add(InterestLabel);
grid.add(InterestRate);
grid.add(TermLabel);
grid.add(Term);
grid.add(PaymentLabel);
grid.add(Payment);
grid.add(Box.createHorizontalStrut(15));
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
grid.add(calculateButton);
grid.add(resetButton);
grid.add(exitButton);
Payment.setEditable(false);
setContentPane(pane);
setContentPane(pane);
setVisible(true);
// Action Listeners
mortgageAmount.addActionListener(this);
InterestRate.addActionListener(this);
Term.addActionListener(this);
Payment.addActionListener(this);
seven.addActionListener(this);
fifteen.addActionListener(this);
thirty.addActionListener(this);
calculateButton.addActionListener(this);
exitButton.addActionListener(this);
resetButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Object command = e.getSource();
if (command == exitButton) {
System.exit(0);
}
else if (command == seven) {
calcLoan(loanTerms[0], annualRates[0]);
}
else if (command == fifteen) {
calcLoan(loanTerms[1], annualRates[1]);
}
else if (command == thirty) {
calcLoan(loanTerms[2], annualRates[2]);
}
else if (command == calculateButton) {
double years = 0;
double rates = 0;
try {
years = Double.parseDouble(Term.getText());
rates = Double.parseDouble(InterestRate.getText());
}
catch (Exception ex) {
LoanPayments.setText("Invalid Amount");
return;
}
calcLoan(years, rates);
}
else if (command == resetButton) {
mortgageAmount.setText("");
Payment.setText("");
InterestRate.setText("");
Term.setText("");
LoanPayments.setText("");
}
}
private void calcLoan(double years, double rates) {
Term.setText(String.valueOf(years));
InterestRate.setText(String.valueOf(rates));
double amount = 0;
try {
amount = Double.parseDouble(mortgageAmount.getText());
}
catch (Exception ex) {
LoanPayments.setText("Invalid Amount");
return;
}
double interestRate = rates;
double intRate = (interestRate / 100) / 12;
int months = (int) years * 12;
double rate = (intRate / 12);
double payment = amount * intRate
/ (1 - (Math.pow(1 / (1 + intRate), months)));
double remainingPrincipal = amount;
double MonthlyInterest = 0;
double MonthlyAmt = 0;
NumberFormat CurrencyFormatter = NumberFormat.getCurrencyInstance();
Payment.setText(CurrencyFormatter.format(payment));
LoanPayments.setText(" Month\tPrincipal\tInterest\tEnding Balance\n");
int currentMonth = 0;
while (currentMonth < months) {
MonthlyInterest = (remainingPrincipal * intRate);
MonthlyAmt = (payment - MonthlyInterest);
remainingPrincipal = (remainingPrincipal - MonthlyAmt);
LoanPayments.append((++currentMonth) + "\t"
+ CurrencyFormatter.format(MonthlyAmt) + "\t"
+ CurrencyFormatter.format(MonthlyInterest) + "\t"
+ CurrencyFormatter.format(remainingPrincipal) + "\n");
GraphArea.append("" + remainingPrincipal);
}
}
public static void main(String[] args) {
new WK4();
}
}
You're adding the radio buttons to the grid but you also need to add them to the button group that you defined.
Maybe this:
ButtonGroup group = new ButtonGroup();
grid.add(seven);
grid.add(fifteen);
grid.add(thirty);
Should be this: ??? (Copy/paste bug?)
ButtonGroup group = new ButtonGroup();
group.add(seven);
group.add(fifteen);
group.add(thirty);
Or maybe you need to do both. The radio buttons have to belong to a container as well as a button group to be displayed and to behave properly.

table with buttons

I want to create a column and install a button in this last column in this table.
public JPanel pinakas(String[] pinaka) {
int sr = 0;
//int ari8mos =0;
String[] COLUMN_NAMES = {"Κωδικός", "Ποσότητα", "Τιμή", "Περιγραφή", "Μέγεθος", "Ράτσα"};
//pio panw mporoume na pros8esoume ws prwto column to "#", wste na deixnei ton ari8mo ths ka8e kataxwrhshs
DefaultTableModel modelM = new DefaultTableModel(COLUMN_NAMES, 0);
JTable tableM = new JTable(modelM);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(new JScrollPane(tableM), BorderLayout.CENTER);
Display disp = new Display();
while (pinaka[sr] != null) // !!!!tha ektupwsei kai mia parapanw "/n" logo ths kataxwrhshs prwtou h teleytaiou mahmatos
{
String[] temp5 = disp.lineDelimiter(pinaka[sr],6, "#");
Object[] doge = { temp5[0], temp5[1], temp5[2], temp5[3], temp5[4], temp5[5]};//edw mporoume sthn arxh na valoume to ari8mos gia na fainetai o ari8mos twn kataxwrhsewn
modelM.addRow(doge);
sr++;
//ari8mos++;
}
return mainPanel;
}
Table Button Column shows one possible solution.

Categories