Array of JLabel HELP
how would I create an array of JLabels?
If you are not sure of how many object you want to place within the array, ArrayLists can grow dynamically. Here is how to use it:
java.util.ArrayList arraylist = new java.util.ArrayList();
//To Add Your Class:
YourClass yourClass = new YourClass();
arraylist.add(yourClass);
//To Use Your Class:
YourClass yourClass = (YourClass)arrayList.get(0);
Similar Messages
-
Hi, I was hoping someone could explain the concept behind using an array for a level in a 2d game. The only tutorial I could find on the subject was not helpfull. I do not see how to take the array and create a grid where I could place a character or wall into an array location. any help is greatly appreciated. Thx for reading
Although all gfx are essencially primative arrays ([] not [][]), through abstraction Java tries to hide this concept from you. In Java, all images that can be rendered to the screen are subclasses of the Image class.
There are subclasses of Image (java.awt.image.BufferedImage) that allow ou to manipulate the underlying primitive representation, but, for the most part you don't need to do this.
Simply creating a BufferedImage with the desired width and height and an appropriate TYPE_ like this..
BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //(the TYPE_ is how the image data will be stored in the underlying primitive [] - in this case it is integer packed RGB values, with no alpha)when you want to draw the image to a Graphics context, simply use the method in the Graphics class, drawImage(Image,x,y,ImageObserver)
public void paint(Graphics g)
g.drawImage(bufferedImage,x,y,null);//in this case you need not worry about the ImageObserver
rob, -
i have one problem about using addKeyListener, i'm using array to create JLabel but once i've compile it, it came out a message as i shown, so where is my problem, hope someone can fix it for me and explain it for me, thank you
---------- Capture Output ----------
"C:\Program Files\Java\jdk1.6.0_03\bin\javac.exe" Login.javaLogin.java:78: not a statement
inputTextName[1]KeyPressed( event );
^
Login.java:78: ';' expected
inputTextName[1]KeyPressed( event );
^
2 errors
Terminated with exit code 1.---------- Capture Output ----------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Login extends JFrame
//JLabel[] lblName = {"lblName1","lblName2"};
JLabel[] labelName;
//JTextField[] txtfldName = {input1,input2};
JTextField[] inputTextName;
//JLabel[] array = new JLabel[veryLargeNumber];
JButton[] btnName = new JButton[3];
public void userInterface()
this.setBackground(Color.blue);
this.setTitle("Log in");
this.setSize(285,130);
this.setVisible(true);
Container contentPane = getContentPane();
contentPane.setLayout(null);
labelName[0] = new JLabel();
labelName[0].setText("ID: ");
labelName[0].setBounds(16, 16, 130, 21);
this.add(labelName[0]);
inputTextName[0] = new JTextField();
inputTextName[0].setText(" ");
inputTextName[0].setBounds(50, 16, 150, 21);
inputTextName[0].setHorizontalAlignment(JTextField.LEFT);
this.add(inputTextName[0]);
labelName[1] = new JLabel();
labelName[1].setText("Password: ");
labelName[1].setBounds(16, 48, 104, 21);
this.add(labelName[1]);
inputTextName[1] = new JTextField();
inputTextName[1].setText(" ");
inputTextName[1].setBounds(50, 48, 150, 21);
inputTextName[1].setHorizontalAlignment(JTextField.LEFT);
this.add(inputTextName[1]);
btnName[0] = new JButton();
btnName[0].setText("login");
btnName[0].setBounds(120,80,65,20);
this.add(btnName[0]);
btnName[1] = new JButton();
btnName[1].setText("exit");
btnName[1].setBounds(190,80,65,20);
this.add(btnName[1]);
inputTextName[1].addKeyListener(
new KeyAdapter() // anonymous inner class
// method called when user types in cartonsJTextField
public void keyPressed( KeyEvent event )
inputTextName[1]KeyPressed( event );
} // end anonymous inner class
); // end call to addKeyListener
//call function
public Login()
userInterface();
public static void main (String args[])
Login application = new Login();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}Edited by: slamgundam on Oct 24, 2007 11:48 PMslamgundam wrote:
the purpose is try to get the text in the inputTextField
inputTextName[1].addKeyListener(
new KeyAdapter()
// method called when user types in cartonsJTextField
public void keyPressed( KeyEvent event )
String str = inputTextName[1].getText();
System.out.println(str);
); -
Swing Arrays! Please help!!
how do you assign the values of an array to another array?
example:
String A[] = {"a","b","c"};
String B = {};//initial as an empty array
String text;
if text == null
how do you assign the values of array A to array B;
Please help
Thanks in advanceThis should work
String[] A = {"a","b","c"};
String[] B = null;
boolean condition = true;
if (condition)
int size = A.length;
B = new String[size];
for (int i = 0; i < size; i++)
B[i] = A;
note that the B array size is not dynamic, you have to allocate memory when you come to know what size it should be. If you don t want to worry about these array problems, you can use a Vector or an ArrayList. -
Possible to make arrays of JLabels?
I would like to make arrays of JLabels, Iconimages, and Jpanels, but I can't find how to do it.
Is it eaven possible?
How can I proceed instead...?Why not????
Infact you can make an array of any premitive type or of any object... Just you need to use this syntax...
dataType[] arrVarName = new dataType[size];
for example,
JLabel[] lblArr = new JLabel[10];
This will create the new array of JLabel type of 10 elements size... You can initialize each element like this:
for(int i = 0; i < lblArr.length; i++){
lblArr[i] = new JLabel("Hello " + i);
and you can print each element like this:
for(int i = 0; i < lblArr.length; i++){
System.out.println(lblArr.getText());
Okay... Still if you are having any doubt you are always welcome -
Need help pulling data from an outside file into my array. Please help =)
Hi,
I need help adapting my array to read the interest rates from an outside file. Here is my code and the outside file I wrote. Please help. Oh, the array in question is on line 259, inside of my calculation() method.
Thanks...
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.io.*;
import javax.swing.JOptionPane;
public class Workshop5 extends JFrame implements ActionListener
//declare gui components
//declare labels
JPanel contentPane = new JPanel();
JPanel graphPane = new JPanel();
JLabel instructionLabel = new JLabel();
JLabel amountLabel = new JLabel();
JLabel orLabel = new JLabel();
JLabel comboBoxLabel = new JLabel();
JLabel termLabel = new JLabel();
JLabel rateLabel = new JLabel();
JLabel calcLabel = new JLabel();
JLabel paymentLabel = new JLabel();
JLabel tableLabel = new JLabel();
//declare font object
Font labelFont = new Font("Tahoma", Font.PLAIN, 16);
//declare text fields
JTextField amountField = new JTextField(20);
JTextField termField = new JTextField(20);
JTextField rateField = new JTextField(20);
JTextField paymentField= new JTextField(20);
//declare combo box for loan selection
JComboBox comboBox = new JComboBox();
//declare button group and radio buttons
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton enterRadioButton = new JRadioButton("Enter amount, term, & rate", true);
JRadioButton selectRadioButton = new JRadioButton("Select a preset term/rate loan", false);
//declare button objects
JButton clearButton = new JButton();
JButton calcButton = new JButton();
JButton quitButton = new JButton();
//declare text area for amortization
JTextArea amortTextArea = new JTextArea();
JTextArea testTextArea = new JTextArea();
//declare scroll bar for amortization table
JScrollPane scrollPane = new JScrollPane(amortTextArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
public Workshop5()
instructionLabel.setText("Choose one of the following payment calculation options:");
instructionLabel.setFont(new Font("Tahoma",Font.PLAIN,16));
//adds both buttons to button group
buttonGroup.add(enterRadioButton);
buttonGroup.add(selectRadioButton);
enterRadioButton.setFont(labelFont);
enterRadioButton.setBackground(Color.WHITE);
enterRadioButton.setContentAreaFilled(false);
enterRadioButton.addActionListener(this); //adds action listener to enter radio button
orLabel.setText("OR");
orLabel.setFont(new Font("Tahoma",Font.BOLD,18));
selectRadioButton.setFont(labelFont);
selectRadioButton.setBackground(Color.WHITE);
selectRadioButton.setContentAreaFilled(false);
selectRadioButton.addActionListener(this); //adds action listener to select radio button
amountLabel.setText("Enter mortgage amount");
amountLabel.setFont(new Font("Tahoma", Font.PLAIN,16));
amountField.requestFocusInWindow();
termLabel.setText("Enter term length in years:");
termLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
rateLabel.setText("Enter interest rate:");
rateLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
comboBoxLabel.setText("Select a loan:");
comboBoxLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
comboBox.setBackground(new Color(255,255,255));
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 14));
comboBox.setEnabled(false);
ComboBox();
calcLabel.setText("Press Calculate button to determine monthly payment.");
calcLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
calcButton.setText("Calculate");
calcButton.setFont(new Font("Tahoma", Font.BOLD, 14));
calcButton.addActionListener(this);
//define monthly payment label
paymentLabel.setText("Monthly payment:");
paymentLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
//define monthly payment text field
paymentField.setFont(new Font("Tahoma", Font.BOLD,16));
paymentField.setBackground(new Color(255,255,255));
paymentField.setEditable(false);
//define clear button
clearButton.setText("Clear");
clearButton.setFont(new Font("Tahoma", Font.BOLD,14));
clearButton.addActionListener(this);
//define quit button
quitButton.setText("Quit");
quitButton.setFont(new Font("Tahoma", Font.BOLD,14));
quitButton.addActionListener(this);
tableLabel.setText("Amoritization Table");
tableLabel.setFont(new Font("Tahoma", Font.BOLD, 16));
graphPane.setBackground(Color.WHITE);
//add components to content
getContentPane().add(contentPane);
contentPane.setLayout(null);
addComponent(contentPane, instructionLabel, 80,10,450,26);
addComponent(contentPane, enterRadioButton, 30,40,220,30);
addComponent(contentPane, orLabel, 280,40,100,30);
addComponent(contentPane, selectRadioButton, 335,40,350,30);
addComponent(contentPane, amountLabel, 100,80,220,26);
addComponent(contentPane, amountField, 300,80,150,26);
addComponent(contentPane, termLabel, 15,125,200,30);
addComponent(contentPane, termField, 195,125,125,30);
addComponent(contentPane, rateLabel, 62,160,200,30);
addComponent(contentPane, rateField, 195,165,125,30);
addComponent(contentPane, comboBoxLabel, 400,125,200,26);
addComponent(contentPane, comboBox, 400,155,150,30);
addComponent(contentPane, calcLabel, 100,200,400,30);
addComponent(contentPane, calcButton, 250,240,100,30);
addComponent(contentPane, paymentLabel, 150,285,200,30);
addComponent(contentPane, paymentField, 300,285,100,30);
addComponent(contentPane, clearButton, 100,330,100,30);
addComponent(contentPane, quitButton, 400,330,100,30);
addComponent(contentPane, tableLabel, 200,370,300,26);
addComponent(contentPane, scrollPane, 10,400,450,360);
addComponent(contentPane, graphPane, 475,400,305,360);
//add window listener to close window when user presses X
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
pack();
//method to add components
private void addComponent(Container container, Component c, int x, int y, int width, int height)
c.setBounds(x, y, width, height);
container.add(c);
//action performed method
public void actionPerformed(ActionEvent event)
Object source = event.getSource();
if (source == calcButton)
Calculate();
if (source == clearButton)
Clear();
if (source == quitButton)
Exit();
//defines active area based on user selection of mortgage calculation method
//if user chooses to enter the mortgage manually, combo box fields are inactive
if (source == enterRadioButton)
comboBox.setEnabled(false);
termField.setEnabled(true);
termField.setEditable(true);
rateField.setEnabled(true);
rateField.setEditable(true);
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
//if user chooses to select from a preset mortgage, rate and term fields are inactive
if (source == selectRadioButton)
comboBox.setEnabled(true);
termField.setEnabled(false);
termField.setEditable(false);
rateField.setEnabled(false);
rateField.setEditable(false);
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
}//end of action performed method
//combo box method
public void ComboBox()
String[] LoanArray = {" 7 years at 5.35 %", " 15 years at 5.50 %", " 30 years at 5.75 %"};
for (int i = 0; i < LoanArray.length; i++)
comboBox.addItem(LoanArray);
}//end combo box method
//calculation method
void Calculate()
//resets fields
paymentField.setText("");
amortTextArea.setText("");
//calculation variables
NumberFormat currency = NumberFormat.getCurrencyInstance();
int [] termArray = {7, 15, 30}; //array of years
double [] yearlyInterestArray = {5.35, 5.5, 5.75}; //array of interest
int totalMonths = 0; //total months
double Loan = 0.0; //amount of loan
double MonthlyInterest = 0.0; //monthly interest rate
double Payment = 0.0; //calculate payment
double monthlyPayment = 0.0; //calculate monthly payment
double Interest = 0.0; //variable for Interest Array input
int Term = 0; //variable for Term Array input
double NewMonthlyInterest = 0.0; //new interest amount
double NewLoan = 0.0; //new loan amount
double Reduction = 0.0; //principle reduction
//validate input
try
Loan = Double.parseDouble(amountField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid Entry. Please enter valid loan amount.", "Error", JOptionPane.WARNING_MESSAGE);
//resets input fields after error message
amountField.setText("");
amountField.requestFocusInWindow();
//if select button is chosen
if (selectRadioButton.isSelected())
int index = comboBox.getSelectedIndex();
Term = termArray[index];
Interest = yearlyInterestArray[index];
//if user chooses to enter mortgage information
else
if (enterRadioButton.isSelected())
//validates input
try
Term = Integer.parseInt(termField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid entry. Please enter valid term length in years.", "Error",JOptionPane.WARNING_MESSAGE);
//clears fields after error message
termField.setText("");
termField.requestFocusInWindow();
try
Interest = Double.parseDouble(rateField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid entry. Please enter valid rate (without percent symbol).","Error",JOptionPane.WARNING_MESSAGE);
//clears fields after error message
rateField.setText("");
rateField.requestFocusInWindow();
//perform calculations
if (Loan > 0)
Loan = Double.parseDouble(amountField.getText());
MonthlyInterest = (Interest / 12)/100;
totalMonths = Term * 12;
monthlyPayment = Loan * MonthlyInterest *(Math.pow((1 + MonthlyInterest), totalMonths)/(Math.pow((1 + MonthlyInterest), totalMonths)-1));
paymentField.setText("" + currency.format(monthlyPayment));
//send information to amortization text area
amortTextArea.append("Number\t");
amortTextArea.append(" Amount\t");
amortTextArea.append("Interest\t");
amortTextArea.append("Principle\t");
amortTextArea.append("Balance\n");
NewLoan = Loan;
for (int i = 1; i <= totalMonths; i++)
NewMonthlyInterest = MonthlyInterest * NewLoan;
Reduction = monthlyPayment - NewMonthlyInterest;
NewLoan = NewLoan - Reduction;
amortTextArea.append(" " + i +"\t");
amortTextArea.append(" " + currency.format(monthlyPayment) + "\t");
amortTextArea.append(" " + currency.format(NewMonthlyInterest)+ "\t");
amortTextArea.append(" " + currency.format(Reduction) + "\t");
amortTextArea.append(" " + currency.format(NewLoan) + "\n");
//resets fields if loan amount is less than zero
if((Loan <= 0 || Term <= 0 || Interest <= 0))
paymentField.setText("");
amortTextArea.setText("");
}//end calcualtion method
//clear method
void Clear()
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
}//end of clear method
//main method
public static void main(String args[])
Workshop5 f = new Workshop5();
f.setTitle("Carol's Mortgage Calculator");
f.setBounds(200,100,800,800);
f.setResizable(false);
f.setVisible(true);
}//end of main method
//exit method
void Exit()
System.exit(0);
}//end of exit method
}//program end
My data file is called: "InterestData.dat" and only contains the following text:
5.35, 5.5, 5.75Ok, now I am getting this error message:
cannot resolve symbol method lenght()
Please help me out here, this is due tomorrow and I've been killing myself on it...
attaching program with revised code included, see beginning of calculation method line 250:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.* ;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.io.*;
import javax.swing.JOptionPane;
public class Workshop5 extends JFrame implements ActionListener
//declare gui components
//declare labels
JPanel contentPane = new JPanel();
JPanel graphPane = new JPanel();
JLabel instructionLabel = new JLabel();
JLabel amountLabel = new JLabel();
JLabel orLabel = new JLabel();
JLabel comboBoxLabel = new JLabel();
JLabel termLabel = new JLabel();
JLabel rateLabel = new JLabel();
JLabel calcLabel = new JLabel();
JLabel paymentLabel = new JLabel();
JLabel tableLabel = new JLabel();
//declare font object
Font labelFont = new Font("Tahoma", Font.PLAIN, 16);
//declare text fields
JTextField amountField = new JTextField(20);
JTextField termField = new JTextField(20);
JTextField rateField = new JTextField(20);
JTextField paymentField= new JTextField(20);
//declare combo box for loan selection
JComboBox comboBox = new JComboBox();
//declare button group and radio buttons
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton enterRadioButton = new JRadioButton("Enter amount, term, & rate", true);
JRadioButton selectRadioButton = new JRadioButton("Select a preset term/rate loan", false);
//declare button objects
JButton clearButton = new JButton();
JButton calcButton = new JButton();
JButton quitButton = new JButton();
//declare text area for amortization
JTextArea amortTextArea = new JTextArea();
JTextArea testTextArea = new JTextArea();
//declare scroll bar for amortization table
JScrollPane scrollPane = new JScrollPane(amortTextArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
public Workshop5()
instructionLabel.setText("Choose one of the following payment calculation options:");
instructionLabel.setFont(new Font("Tahoma",Font.PLAIN,16));
//adds both buttons to button group
buttonGroup.add(enterRadioButton);
buttonGroup.add (selectRadioButton);
enterRadioButton.setFont(labelFont);
enterRadioButton.setBackground(Color.WHITE);
enterRadioButton.setContentAreaFilled(false);
enterRadioButton.addActionListener(this); //adds action listener to enter radio button
orLabel.setText("OR");
orLabel.setFont(new Font("Tahoma",Font.BOLD,18));
selectRadioButton.setFont(labelFont);
selectRadioButton.setBackground(Color.WHITE);
selectRadioButton.setContentAreaFilled(false);
selectRadioButton.addActionListener (this); //adds action listener to select radio button
amountLabel.setText("Enter mortgage amount");
amountLabel.setFont(new Font("Tahoma", Font.PLAIN,16));
amountField.requestFocusInWindow();
termLabel.setText("Enter term length in years:");
termLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
rateLabel.setText("Enter interest rate:");
rateLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
comboBoxLabel.setText("Select a loan:");
comboBoxLabel.setFont(new Font("Tahoma", Font.PLAIN,14));
comboBox.setBackground(new Color(255,255,255));
comboBox.setFont(new Font("Tahoma", Font.PLAIN, 14));
comboBox.setEnabled(false);
ComboBox();
calcLabel.setText("Press Calculate button to determine monthly payment.");
calcLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
calcButton.setText("Calculate");
calcButton.setFont(new Font("Tahoma", Font.BOLD, 14));
calcButton.setBackground(new Color(202,255,112));
calcButton.addActionListener(this);
//define monthly payment label
paymentLabel.setText("Monthly payment:");
paymentLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
//define monthly payment text field
paymentField.setFont (new Font("Tahoma", Font.BOLD,16));
paymentField.setBackground(new Color(255,255,255));
paymentField.setEditable(false);
//define clear button
clearButton.setText("Clear");
clearButton.setFont(new Font("Tahoma", Font.BOLD,14));
clearButton.setBackground(new Color(202,255,112));
clearButton.addActionListener(this);
//define quit button
quitButton.setText("Quit");
quitButton.setFont(new Font("Tahoma", Font.BOLD,14));
quitButton.setBackground(new Color(202,255,112));
quitButton.addActionListener(this);
//define label for amortization table
tableLabel.setText ("Amoritization Table");
tableLabel.setFont(new Font("Tahoma", Font.BOLD, 16));
graphPane.setBackground(Color.WHITE);
//add components to content
getContentPane().add(contentPane);
contentPane.setLayout(null);
addComponent(contentPane, instructionLabel, 80,10,450,26);
addComponent(contentPane, enterRadioButton, 30,40,220,30);
addComponent(contentPane, orLabel, 280,40,100,30);
addComponent(contentPane, selectRadioButton, 335,40,350,30);
addComponent(contentPane, amountLabel, 100,80,220,26);
addComponent(contentPane, amountField, 300,80,150,26);
addComponent(contentPane, termLabel, 15,125,200,30);
addComponent(contentPane, termField, 195,125,125,30);
addComponent(contentPane, rateLabel, 62,160,200,30);
addComponent(contentPane, rateField, 195,165,125,30);
addComponent(contentPane, comboBoxLabel, 400,125,200,26);
addComponent(contentPane, comboBox, 400,155,150,30);
addComponent(contentPane, calcLabel, 100,200,400,30);
addComponent(contentPane, calcButton, 250,240,100,30);
addComponent(contentPane, paymentLabel, 150,285,200,30);
addComponent(contentPane, paymentField, 300,285,100,30);
addComponent(contentPane, clearButton, 100,330,100,30);
addComponent(contentPane, quitButton, 400,330,100,30);
addComponent(contentPane, tableLabel, 200,370,300,26);
addComponent(contentPane, scrollPane, 10,400,450,360);
addComponent(contentPane, graphPane, 475,400,305,360);
//add window listener to close window when user presses X
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
pack();
//method to add components
private void addComponent(Container container, Component c, int x, int y, int width, int height)
c.setBounds(x, y, width, height);
container.add(c);
//action performed method
public void actionPerformed(ActionEvent event)
Object source = event.getSource();
if (source == calcButton)
Calculate();
if (source == clearButton)
Clear();
if (source == quitButton)
Exit();
//defines active area based on user selection of mortgage calculation method
//if user chooses to enter the mortgage manually, combo box fields are inactive
if (source == enterRadioButton)
comboBox.setEnabled(false);
termField.setEnabled(true);
termField.setEditable(true);
rateField.setEnabled(true);
rateField.setEditable(true);
amountField.setText ("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText ("");
amortTextArea.setText("");
//if user chooses to select from a preset mortgage, rate and term fields are inactive
if (source == selectRadioButton)
comboBox.setEnabled(true);
termField.setEnabled(false);
termField.setEditable(false);
rateField.setEnabled (false);
rateField.setEditable(false);
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText ("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
}//end of action performed method
//combo box method
public void ComboBox()
String[] LoanArray = {" 7 years at 5.35 %", " 15 years at 5.50 %", " 30 years at 5.75 %"};
for (int i = 0; i < LoanArray.length; i++)
comboBox.addItem(LoanArray);
}//end combo box method
//calculation method
void Calculate()
//resets fields
paymentField.setText("");
amortTextArea.setText("");
//calculation variables
NumberFormat currency = NumberFormat.getCurrencyInstance();
//declare input stream object
InputStream istream;
//create a file object to refer to the outside file
File interestData = new File("InterestFile.dat");
//assign instream to the new file object
istream = new FileInputStream(interestData);
try
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(new FileReader(interestData));
String line = "";
while((line = in.readLine()) != null)
sb.append(line);
in.close();
String fileData = sb.toString();
String[] splitData = fileData.split(", ");
double [] yearlyInterestArray = new double[splitData.length()];
for(int j = 0; j < splitData.length(); j++)
yearlyInterestArray[j] = new Double(splitData[j]).doubleValue();
catch (IOException e)
JOptionPane.showMessageDialog(null, "File does not exist." + e.getMessage());
int [] termArray = {7, 15, 30}; //array of years
double [] yearlyInterestArray = { 5.35, 5.5, 5.75}; //array of interest
int totalMonths = 0; //total months
double Loan = 0.0; //amount of loan
double MonthlyInterest = 0.0; //monthly interest rate
double Payment = 0.0; //calculate payment
double monthlyPayment = 0.0; //calculate monthly payment
double Interest = 0.0; //variable for Interest Array input
int Term = 0; //variable for Term Array input
double NewMonthlyInterest = 0.0; //new interest amount
double NewLoan = 0.0; //new loan amount
double Reduction = 0.0; //principle reduction
//validate input
try
Loan = Double.parseDouble(amountField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid Entry. Please enter valid loan amount.", "Error", JOptionPane.WARNING_MESSAGE);
//resets input fields after error message
amountField.setText("");
amountField.requestFocusInWindow ();
//if select button is chosen
if (selectRadioButton.isSelected())
int index = comboBox.getSelectedIndex ();
Term = termArray[index];
Interest = yearlyInterestArray[index];
//if user chooses to enter mortgage information
else
if (enterRadioButton.isSelected())
//validates input
try
Term = Integer.parseInt(termField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid entry. Please enter valid term length in years.", "Error",JOptionPane.WARNING_MESSAGE);
//clears fields after error message
termField.setText("");
termField.requestFocusInWindow();
try
Interest = Double.parseDouble(rateField.getText());
catch (NumberFormatException e)
JOptionPane.showMessageDialog(null,"Invalid entry. Please enter valid rate (without percent symbol).","Error",JOptionPane.WARNING_MESSAGE);
//clears fields after error message
rateField.setText("");
rateField.requestFocusInWindow();
//perform calculations
if (Loan > 0)
Loan = Double.parseDouble(amountField.getText ());
MonthlyInterest = (Interest / 12)/100;
totalMonths = Term * 12;
monthlyPayment = Loan * MonthlyInterest *(Math.pow ((1 + MonthlyInterest), totalMonths)/(Math.pow((1 + MonthlyInterest), totalMonths)-1));
paymentField.setText("" + currency.format(monthlyPayment));
//send information to amortization text area
amortTextArea.append("Number\t");
amortTextArea.append(" Amount\t");
amortTextArea.append("Interest\t");
amortTextArea.append("Principle\t");
amortTextArea.append("Balance\n");
NewLoan = Loan;
for (int i = 1; i <= totalMonths; i++)
NewMonthlyInterest = MonthlyInterest * NewLoan;
Reduction = monthlyPayment - NewMonthlyInterest;
NewLoan = NewLoan - Reduction;
amortTextArea.append(" " + i +"\t");
amortTextArea.append (" " + currency.format(monthlyPayment) + "\t");
amortTextArea.append(" " + currency.format(NewMonthlyInterest)+ "\t");
amortTextArea.append(" " + currency.format(Reduction) + "\t");
amortTextArea.append(" " + currency.format(NewLoan) + "\n");
//resets fields if loan amount is less than zero
if((Loan <= 0 || Term <= 0 || Interest <= 0))
paymentField.setText("");
amortTextArea.setText("");
}//end calcualtion method
//clear method
void Clear()
amountField.setText("");
amountField.requestFocusInWindow();
termField.setText("");
rateField.setText("");
paymentField.setText("");
amortTextArea.setText("");
}//end of clear method
//main method
public static void main(String args[])
Workshop5 f = new Workshop5();
f.setTitle("Carol's Mortgage Calculator");
f.setBounds(200,100,800,800);
f.setResizable(false);
f.setVisible(true);
}//end of main method
//exit method
void Exit()
System.exit(0);
}//end of exit method
}//program end -
GUI array information cycler help please
I currently have a program that has 3 classes. Basically one class is the main and has some information hard coded that it submits to one of the other classes. The second class takes that information, formats it and sends it to the third class. The third class creates an array, takes the information from the second class and has a display method that the main can call to display the information.
The program basically spews out all the information in the array in a specific format. The array elements contain strings, ints and doubles. The third class also calculates some things that are displayed with the display method in main.
What I need to do is create a third class. This class needs to make a GUI to display the information. I currently have the programs display method display the information in a GUI but I need it to display each element one at a time with a NEXT and PREVIOUS button. The next button needs to go to the next array element and the previous button obviously needs to go back to the array element.
Here is the code.
// Inventory Program
// Created June 20, 2007
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Inventory4 {
public static void main(String[] args) {
CD cd;
Inventory inventory = new Inventory();
cd = new CDWithGenre(16, "Disney Hits", 11, 13.01f, "Soundtrack");
inventory.add(cd);
cd = new CDWithGenre(12, "The Clash", 10, 19.99f, "Classic Rock");
inventory.add(cd);
cd = new CDWithGenre(45, "Dixie Chiks", 18, 10.87f, "Country");
inventory.add(cd);
cd = new CDWithGenre(32, "The Cure", 62, 25.76f, "Alternative");
inventory.add(cd);
cd = new CDWithGenre(18, "MS Office", 27, 99.27f, "None");
inventory.add(cd);
inventory.display();
} //End main method
} //End Inventory4 class
/* Defines data from main as CD data and formats it. Calculates value of a title multiplied by its stock.
Creates compareTo method to be used by Arrays.sort when sorting in alphabetical order. */
class CD implements Comparable{
//Declares the variables as protected so only this class and subclasses can act on them
protected int cdSku;
protected String cdName;
protected int cdCopies;
protected double cdPrice;
protected String genre;
//Constructor
CD(int cdSku, String cdName, int cdCopies, double cdPrice, String genre) {
this.cdSku = cdSku;
this.cdName = cdName;
this.cdCopies = cdCopies;
this.cdPrice = cdPrice;
this.genre = genre;
// This method tells the sort method what is to be sorted
public int compareTo(Object o)
return cdName.compareTo(((CD) o).getName());
// Calculates the total value of the copies of a CD
public double totalValue() {
return cdCopies * cdPrice;
// Tells the caller the title
public String getName() {
return cdName;
//Displays the information stored by the constructor
public String toString() {
return String.format("SKU=%2d Name=%-20s Stock=%3d Price=$%6.2f Value=$%,8.2f",
cdSku, cdName, cdCopies, cdPrice, totalValue());
} // end CD class
//Class used to add items to the inventory, display output for the inventory and sort the inventory
class Inventory {
private CD[] cds;
private int nCount;
// Creates array cds[] with 10 element spaces
Inventory() {
cds = new CD[10];
nCount = 0;
// Used by main to input a CD object into the array cds[]
public void add(CD cd) {
cds[nCount] = cd;
++nCount;
sort();
//Displays the arrays contents element by element into a GUI pane
public void display() {
JTextArea textArea = new JTextArea();
textArea.append("\nThere are " + nCount + " CD titles in the collection\n\n");
for (int i = 0; i < nCount; i++)
textArea.append(cds[i]+"\n");
textArea.append("\nTotal value of the inventory is "+new java.text.DecimalFormat("$0.00").format(totalValue())+"\n\n");
JFrame invFrame = new JFrame();
invFrame.getContentPane().add(new JScrollPane(textArea));
invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
invFrame.pack();
invFrame.setLocationRelativeTo(null);
invFrame.setVisible(true);
// Steps through the array adding the totalValue for each CD to "total"
public double totalValue() {
double total = 0;
double restock = 0;
for (int i = 0; i < nCount; i++)
total += cds.totalValue();
return total;
//Method used to sort the array by the the name of the CD
private void sort() {
Arrays.sort(cds, 0, nCount);
} // end Inventory class
// Subclass of CD. Creates new output string to be used, adds a restocking fee calculation and genre catagory to be displayed.
class CDWithGenre extends CD {
String genre;
CDWithGenre(int cdSku, String cdName, int cdCopies, double cdPrice, String genre) {
super(cdSku, cdName, cdCopies, cdPrice, genre);
this.cdName = cdName;
this.cdCopies = cdCopies;
this.cdPrice = cdPrice;
this.genre = genre;
// Calculates restocking fee based on previous data.
public double restockFee() {
double total = 0;
double restock = 0;
total = cdCopies * cdPrice;
restock = total * .05;
return restock;
// New output method overrides superclass's output method with new data and format.
public String toString() {
return String.format("SKU: %2d Genre: %-12s Name: %-20s \nPrice: $%6.2f Value: $%,8.2f Stock: %3d Restocking Fee: $%6.2f\n",
cdSku, genre , cdName, cdPrice, totalValue(), cdCopies, restockFee());
}// Ends CDWithGenre classHey Michael,
I edited the code to add some more features but I am having some errors. Can you help again?
Here is the code
The additional buttons are for features I need to add. The commented part that says save need to save to a certain location.
But the problem I am having is with the previous and next buttons. I need them to loop so when Next reaches the end of the array it needs to go to the first element again and keep on rolling thru. The previous needs to roll back from element 0 to the end again.
This works when the program is not stopped on the last or first element. If I press the last button then press next, it errors. If I press the first button and press previous, it errors.
I also need to add an icon
Let me know what you think. Thanks a bunch
class InventoryGUI
Inventory inventory;
int displayElement = 0;
public InventoryGUI(Inventory inv)
inventory = inv;
public void buildGUI()
final JTextArea textArea = new JTextArea(inventory.display(displayElement));
final JButton prevBtn = new JButton("Previous");
final JButton nextBtn = new JButton("Next");
final JButton lastBtn = new JButton("Last");
final JButton firstBtn = new JButton("First");
final JButton addBtn = new JButton("Add");
final JButton modifyBtn = new JButton("Modify");
final JButton searchBtn = new JButton("Search");
final JButton deleteBtn = new JButton("Delete");
final JButton saveBtn = new JButton("Save");
ImageIcon icon = new ImageIcon("images/icon.jpg");
JLabel label1 = new JLabel(icon);
JPanel panel = new JPanel(new GridLayout(2,4));
panel.add(firstBtn); panel.add(nextBtn); panel.add(prevBtn); panel.add(lastBtn);
panel.add(addBtn); panel.add(modifyBtn); panel.add(searchBtn); panel.add(deleteBtn);
//panel.add(saveBtn);
JFrame invFrame = new JFrame();
invFrame.getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);
invFrame.getContentPane().add(panel,BorderLayout.SOUTH);
invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
invFrame.pack();
invFrame.setSize(500,200);
invFrame.setTitle("Inventory Manager");
invFrame.setLocationRelativeTo(null);
invFrame.setVisible(true);
prevBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
nextBtn.setEnabled(true);
displayElement--;
textArea.setText(inventory.display(displayElement));
if(displayElement <= 0) displayElement = 5;
nextBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
prevBtn.setEnabled(true);
displayElement++;
textArea.setText(inventory.display(displayElement));
if(displayElement >= inventory.nCount-1) displayElement = -1;
firstBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
firstBtn.setEnabled(true);
displayElement = 0;
textArea.setText(inventory.display(displayElement));
lastBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
lastBtn.setEnabled(true);
displayElement = inventory.nCount-1;
textArea.setText(inventory.display(displayElement));
} -
Modifying an element in an array of objects - HELP!
Hello - I would appreciate any help on this project I am working on for my beginning Java class.
One of the requirements of my project are to update a string that I have already populated with a new balance, through an update balance method. I'm confused on how to bring the element (string) back from my array so that I can repopulate the name, and phone so that I don't loose that information when updating the balance. I think it should be done in the AcctMaint class. Below is a copy of my code. I have a lot of garbage in there for testing and have not completed all of the requirements, as you will see. Don't laugh to much - I'm new at this! Thank you, JB
// Author: JB
// Bank.java
// Purpose: To create a customer account, make a deposit, make a withdrawl,
// Accure interest on all accounts when the method is invoked.
import javax.swing.JOptionPane;
public class Bank
// Creates an accout object. Adds, deposits, withdrawls. Prints
// reports on the bank customers
public static void main (String[] args)
Customer account = new Customer ();
String name, phone, numStr;
double deposit;
int option, acctnum;
// Display a menu through a dialog box
numStr = JOptionPane.showInputDialog ( "MAIN MENU" + "\n" + "-----------------" + "\n" +
"Create an account: 1" + "\n" + "Make a deposit: 2" + "\n" +
"Make a withdrawl: 3" + "\n" + "Search for a customer: 4" + "\n" +
"Customer report: 5" + "\n" + "Accru interest on accounts: 6");
option = Integer.parseInt(numStr);
if (option == 1)
numStr = JOptionPane.showInputDialog ("Enter a customer last name");
name = (numStr);
System.out.println (name);
numStr = JOptionPane.showInputDialog ("Enter a 10 digit phone number");
phone = (numStr);
System.out.println (phone);
numStr = JOptionPane.showInputDialog ("Enter your deposit");
deposit = Double.parseDouble(numStr);
System.out.println (deposit);
account.addAcct (0, name, phone, deposit, 0);
// Populate with data for testing
// account.addAcct (0,"George Bush", "3034727812", 140954.95, 0);
// account.addAcct (0,"Hillary Clinton", "7206666666", 0.01, 0);
// account.addAcct (0,"Barb Swayer", "3034724567", 17.95, 0);
// account.addAcct (0,"George Bush", "3034727812", 140954.95, 0);
if (option == 2)
// Get account information
account.addAcct (0,"Carol Lund", "3034716278", 124500.98, 0);
account.addAcct (0,"George Bush", "7204724415", 0.01, 0);
numStr = JOptionPane.showInputDialog ("Enter a customer account");
acctnum = Integer.parseInt(numStr);
System.out.println(acctnum);
numStr = JOptionPane.showInputDialog ("Enter your deposit");
deposit = Double.parseDouble(numStr);
System.out.println (deposit);
account.updAcct (acctnum, "Testing Update", "4544444444", 50.95, deposit);
// List the accounts
System.out.println (account);
// Author: JB
// Customer.java
// Purpose: Store the account number (using index for account number), name, phone and balance
import javax.swing.JOptionPane;
import java.text.NumberFormat;
import java.util.*;
public class Customer
private AcctMaint[] accounts;
private int count, answer;
// Creates an initially empty accounts.
public Customer ()
int Array_Size = 30;
accounts = new AcctMaint[Array_Size];
count = 0;
// Adds a AcctMaint to the accounts
public void addAcct (int account, String name, String phone, double balance, double trans)
accounts[count] = new AcctMaint (account, name, phone, balance, trans);
count++;
// Modifies account so that it increases the balance with a deposit
// accounts if necessary.
public void updAcct (int account, String name, String phone, double balance, double trans)
accounts[account] = new AcctMaint (account, name, phone, balance, trans);
System.out.println ("The customer you will be updating is: " + accounts[account]);
// Returns a report describing the AcctMaint accounts.
public String toString()
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String report = "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n";
report += "L&L Accounts\n\n";
report += "Number Accounts: " + count + "\n";
report += "\n\nAccount List:\n\n";
for (int cd = 0; cd < count; cd++)
report += accounts[cd].toString() + "\n";
return report;
// Author: JB
// AcctMaint.java
import java.text.NumberFormat;
public class AcctMaint
private String name, phone;
private double balance;
// Creates a new Account with the specified information.
public AcctMaint (int Acct, String Cname, String Pnumber, double Abalance, double trans)
name = Cname;
phone = Pnumber;
balance = Abalance + trans;
// I want to get the string and replace it with the new balance
// and old information prior to updating array.
// Returns a description of this account.
public String toString()
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String description;
description = fmt.format(balance) + "\t";
description += name + "\t" + phone;
return description;
Thank you again in advance.toString() is supposed to do nothing more than return a string representation of an object. If you call toString() in order to assign its return value to a temp variable prior to updating the state of the object, then this satisfies your "capture and store the data". But your original post was concerned with updating an object's fields. This should generally only be accomplished by get/set sorts of methods. But of course, the update method could be a wrapper around the set method, with the additional call to toString() prior to setting the fields, so that you can return the pre-update object data or use it in later calculations or whatever, and also update your fields, all in one method.
-
Relate to Array.sort(), urgent help~~
I am using a class for store the data
then I need to sort them
is it the vector which want to sort is needed in same class???
because I use other file to access them~~
The following code:
public Test()
Person person;
Vector v = new Vector();
v.add(new Person("Johnson","Fox");
v.add(new Person("Johnson","David");
Object[] a = v.toArray();
Arrays.sort(a);
public int compareTo(Object dd,Object ww)
if (dd instanceof Person && ww instanceof Person)
Person d = (Person) dd;
Person w = (Person) ww;
return w.lname.compareTo(d.lname);
else
return 0;
the code doesn't work btit can compile, can anyone help me to solve it??
thank you for your time~~In Person.java use the following:
class Person
public int compareTo(Object cmpPerson)
if (cmpPerson instanceof Person)
return this.lname.compareTo( ((Person)cmpPesron).lname );
else
return 0;
} -
2D array problem, need help
hi,
i have a txt file, with a bunch of lines in it that go like this:
CSF.434.001.LEC
CSF.434.101.TUT
MATH.348.001.LEC
MATH.448.101.TUT
and so on...
For example if there are 4 lines in this text, i want to create a 4x4 matrix and store each data seperately.
i want to extract CSF into matrix[1][1], 434 into matrix[1][2], 001 in matrix[1][3], and finally LEC in matrix[1][4],
and it follows, matrix[2][1] is CSF .....
so basically the period denotes seperation. I have been challenging this problem for 2 hrs now, but no success.
any help in regards to how to extract this file into pieces of data in a matrix would be greatly appeciated....thanks again
how i stated it:
try
BufferedReader inFile = new BufferedReader(new FileReader("schedule.txt"));
for(int t=0; t<size; t++)
String[] extractor = new String[t][4];
for(int i=0; i<4; i++)
extractor[t] = ?????
inFile.readToken();
inFile.close();
catch(IOException ioe)
System.out.println("Error reading from file!");First, create a program that can read the entire file a line at a time.
Here's an example:
http://javaalmanac.com/egs/java.io/ReadLinesFromFile.htmlThen once that's working, add the String.split() method to break a line into pieces at the periods. (It creates a String array with each piece of the string in a separate array element.)
This method is described in the API documentation for the java.lang.String class. -
Multidimensional Array/JavaScript Translation help
Hey =)
I have an assignment. The object is to translate whatever the user types into "pirate talk" using a multi-dimensional array. I'm not asking for someone to do the project.. I'm just stuck. He gave us a code in javascript. Our goal was to put this code into a java-applet and make it work. I can't seem to get this piece of javascript code to work to save my neck. =( Basically; I don't know what else I could do to it to get it to read and replace the selected words... I could do it by making a hashmap dictionary method.. I think... but not this array =( and he wants the array.
Here is the original java-script code that he gave us:
function Translate(text)
// Returns: a copy of text with English phrases replaced by piratey equivalents
for (var i = 0; i < PHRASES.length; i++) {
var toReplace = new RegExp("\\b"+PHRASES[0]+"\\b", "i");
var index = text.search(toReplace);
while (index != -1) {
text = text.replace(toReplace, PHRASES[i][1]);
index = text.search(toReplace);
return text;
}This is my java-applet.. my edited java-script code is under the "actionPerformed" method.import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class PirateTranslator3 implements ActionListener
private JTextArea pirateArea;
private JTextArea englishArea;
String [][] PHRASES = {{"hello", "ahoy"}, {"hi", "yo-ho-ho"}, {"pardon me", "avast"},
{"excuse me", "arrr"},
{"my", "me"}, {"friend", "me bucko"}, {"sir", "matey"},
{"madam", "proud beauty"}, {"miss", "comely wench"},
{"stranger", "scurvy dog"}, {"officer", "foul blaggart"},
{"where", "whar"}, {"is", "be"}, {"the", "th'"}, {"you", "ye"},
{"tell", "be tellin'"}, {"know", "be knowin'"},
{"how far", "how many leagues"}, {"old", "barnacle-covered"},
{"attractive", "comely"}, {"happy", "grog-filled"},
{"nearby", "broadside"}, {"restroom", "head"}, {"restaurant", "galley"},
{"hotel", "fleabag inn"}, {"pub", "Skull & Scuppers"},
{"bank", "buried treasure"}
private static void createAndShowGUI()
PirateTranslator translator = new PirateTranslator();
translator.launch();
public void launch()
JFrame applicationFrame = new JFrame("Talk like a Pirate!");
applicationFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
applicationFrame.getContentPane().setLayout(new BorderLayout());
englishArea = new JTextArea();
englishArea.setPreferredSize(new Dimension(200,200));
applicationFrame.getContentPane().add(englishArea, BorderLayout.NORTH);
JButton button = new JButton("Translate");
button.addActionListener(this);
applicationFrame.getContentPane().add(button, BorderLayout.CENTER);
pirateArea = new JTextArea();
pirateArea.setPreferredSize(new Dimension(200,200));
applicationFrame.getContentPane().add(pirateArea, BorderLayout.SOUTH);
applicationFrame.setSize(600,600);
applicationFrame.setVisible(true);
public void actionPerformed(ActionEvent e)
String english = englishArea.getText();
for (int i = 0; i < PHRASES.length; i++ )
String toReplace = new RegExp("\\b"+PHRASES[i][0]+"\\b", "i");
String index = english.search(toReplace);
while (index != -1){
if (english.charAt(index) >= "A" && english.charAt(index) <= "Z")
{ english = english.replace(toReplace, Capitalize(PHRASES[i][1])); }
else
{ english = english.replace(toReplace, PHRASES[i][1]); }
index = english.search(toReplace);
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable(){
public void run()
createAndShowGUI();
Any help, hint, or lead in the right direction would be appreciated.
I'm completely stuck.Here is the cmd prompt error information:
C:\>javac PirateTranslator3.java
PirateTranslator3.java:36: launch() has private access in PirateTranslator
translator.launch();
^
PirateTranslator3.java:76: cannot find symbol
symbol : class RegExp
location: class PirateTranslator3
String toReplace = new RegExp("\\b"+PHRASES[0]+"\\b", "i");
^
PirateTranslator3.java:77: cannot find symbol
symbol : method search(java.lang.String)
location: class java.lang.String
String index = english.search(toReplace);
^
PirateTranslator3.java:79: incomparable types: java.lang.String and int
while (index != -1){
^
PirateTranslator3.java:80: charAt(int) in java.lang.String cannot be applied to
(java.lang.String)
if (english.charAt(index) >= "A" && english.charAt(index) <= "Z"
^
PirateTranslator3.java:80: charAt(int) in java.lang.String cannot be applied to
(java.lang.String)
if (english.charAt(index) >= "A" && english.charAt(index) <= "Z"
^
PirateTranslator3.java:81: cannot find symbol
symbol : method Capitalize(java.lang.String)
location: class PirateTranslator3
{ english = english.replace(toReplace, Capitalize(PHRASES[
i][1])); }
^
PirateTranslator3.java:85: cannot find symbol
symbol : method search(java.lang.String)
location: class java.lang.String
index = english.search(toReplace);
^
8 errorsBasically what I'm getting from th is is that a bunch of those commands aren't in Java.. but I don't know what the equivalent words/phrases are in java =( -
Hi,I'm creating a calendar/diary program and i need help with the following:
I have 3 classes. One called Calendar_Notetaker.java. This one is the main applet class. The other called MonthDate.java. This class figures out the number of days in month, leap year ect. using the java.util.date. Then another class called CalendarPanel.java. This class creates the actual caladar.
I used a button array to print the days. However i'm having problems accessing the buttons. i need to put an actionlister on them so when a user clicks on them it opens a new window. i know how to open a new window from a button but i cant figure out how to do it from a button array. Do i need need to create an instance from the main applet or can i do it in the class that generates the buttons?
here are my classes..note these are all in sepearte files.
any suggestions would be appreciated
thanks
Kevin
PS. These were done in Borland Jbuilder 7 Enterprise
package calendar_notetaker;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Calendar_NoteTaker extends Applet {
private int currentYear;
private int currentMonth;
private MonthDate myMonth;
CalendarPanel monthPanel;
private boolean isStandalone = false;
//Get a parameter value
public String getParameter(String key, String def) {
return isStandalone ? System.getProperty(key, def) :
(getParameter(key) != null ? getParameter(key) : def);
//Construct the applet
public Calendar_NoteTaker() {
//Initialize the applet
public void init() {
try {
jbInit();
catch(Exception e) {
e.printStackTrace();
//Component initialization
private void jbInit() throws Exception {
setLayout(new BorderLayout());
myMonth = new MonthDate();
currentYear = myMonth.getYear();
currentMonth = myMonth.getMonth() + 1;
monthPanel = new CalendarPanel(myMonth);
add("Center", monthPanel);
Panel panel = new Panel();
panel.add(new Button("Previous Year"));
panel.add(new Button("Previous Month"));
panel.add(new Button("Next Month"));
panel.add(new Button("Next Year"));
add("South", panel);
show();
public void setNewMonth()
myMonth.setMonth(currentMonth - 1);
myMonth.setYear(currentYear);
monthPanel.showMonth();
public boolean action(Event event, Object obj)
if(event.target instanceof Button)
if("Previous Month".equals(obj))
if(--currentMonth < 1)//goes before january
currentYear--;
currentMonth = 12;
if(currentYear < 70)//year < 1970
currentYear = 70;
} else
if("Next Month".equals(obj))
if(++currentMonth > 12)//if you go past 12 months
currentYear++;//set to next year
currentMonth = 1;//set back to january
if(currentYear > 137)//137 years from current year.
currentYear = 137;
} else
if("Previous Year".equals(obj))
if(--currentYear < 70)
currentYear = 70;
} else
if("Next Year".equals(obj) && ++currentYear > 137)
currentYear = 137;
setNewMonth();
return true;
//Start the applet
public void start() {
//Stop the applet
public void stop() {
//Destroy the applet
public void destroy() {
//Get Applet information
public String getAppletInfo() {
return "Applet Information";
//Get parameter info
public String[][] getParameterInfo() {
return null;
package calendar_notetaker;
import java.awt.*;
import java.util.Date;
public class CalendarPanel extends Panel
private MonthDate myMonth;
Label lblMonth;//month label
Button MonthButtons[];//button arrary for month names
public CalendarPanel(MonthDate monthdate)
lblMonth = new Label("",1);//0 left 1 midele 2 right side
MonthButtons = new Button[42];//42 buttons 7x6 some wont be used
myMonth = monthdate;
setLayout(new BorderLayout());
add("North", lblMonth);
Panel panel = new Panel();
panel.setLayout(new GridLayout(7, 7));//7rows x 7cols
for(int i = 0; i < 7; i++)
panel.add(new Label(MonthDate.WEEK_LABEL));
//0 to 42 monthbuttons above is 42
for(int j = 0; j < MonthButtons.length; j++)
MonthButtons[j] = new Button(" ");
panel.add(MonthButtons[j]);//add the butttons to the panel
showMonth();
add("Center", panel);
show();
public void showMonth()
lblMonth.setText(myMonth.monthYear());//monthyear is built in util.date
int i = myMonth.getDay();//get current day
if(myMonth.weeksInMonth() < 5)//if month has less than 5 weeks
i += 7;//we still want to have a 7x7 grid
for(int j = 0; j < i; j++)
{//add the begging set of empty spaces
MonthButtons[j].setLabel(" ");
MonthButtons[j].disable();
// k<days in month user picks
for(int k = 0; k < myMonth.daysInMonth(); k++)
{//add days in month + empty spaces
MonthButtons[k+ i ].setLabel("" + (k + 1));
MonthButtons[k+ i ].enable();
for(int l = myMonth.daysInMonth() + i; l < MonthButtons.length; l++)
{//add ending number of empty spaces
MonthButtons[l].setLabel(" ");
MonthButtons[l].disable();
package calendar_notetaker;
import java.util.Date;
public class MonthDate extends Date
//week header
public static final String WEEK_LABEL[] = {
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
//days in month assuming feburary is not a leap year
final int MonthDays[] = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31
//label to print month names
public static final String MONTH_LABEL[] = {
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October",
"November", "December"
//create constructor
public MonthDate()
this(new Date());
public MonthDate(Date date)
{//get the current system date and month add one cause its off one
this(date.getYear(), date.getMonth()+1);
public MonthDate(int year, int monthName)
super(year,monthName-1,1);//year, monthname,start day posistion
public boolean isLeapYear()
int year;
Date date = new Date();
year=date.getYear();
return ( ((year % 4 == 0) && (year % 100 != 0))
|| (year % 400 == 0) );
public int daysInMonth()
int i = getMonth();
if(i == 1 && isLeapYear())
return 29;
} else
return MonthDays;//return the array declared above
public int weeksInMonth()
{ //finds howmany weeks are in a month
return (daysInMonth() + getDay() + 6) / 7;
public String monthLabel()
{ //method to return the month names for printing later
return MONTH_LABEL[getMonth()];
public String monthYear()
{//method to return the month and year for printing later
return monthLabel() + " " + (1900 + getYear());add a listener and do it from there.
-
Let me preface this post by saying that I am a novice programmer. I realize my code my be subpar ..to say the least :)
I wrote a small practice program that when run, prints 5 sets of random numbers (ex. A3KRM-QP4S7-5GMBR-OY68B-Q8GBZ).
That part works fine on the command line, however I wanted to incorporate swing and display the output on a form. This is where I'm running into a problem. I'm trying to place output from a character array into a string and then print that to a label. The result is its printing a bunch of squares (ASCII?).
Here is where I'm creating my sets of random numbers, in the method "myGenerator()".
class keygen
//initialize random number generator
Random rand = new Random();
//initialize arrays
char data[] = new char[36];
char key[] = new char[5];
//initialize integers and strings
char keys[] = new char[30];
int a = 0, n = 35, q = 65, z = 48;
//CONSTRUCTOR
keygen()
//main method
public char[] myGenerator()
//Populate charater array with numbers and letters
for (int x = 0; x <=25; x++)
data[x] = ((char)q);
q++;
for(int x = 26; x <=35; x++)
data[x] = ((char)z);
z++;
//Print 5 groups of random characters
do
for (int b = 0; b < 5; b++)
System.out.print(data[rand.nextInt(n+1)]);
f++;
System.out.print("-");
a++;
f++;
} while (a < 4);
do
System.out.print(data[rand.nextInt(n+1)]);
a++;
f++;
} while (a < 10);
return keys;
}Here is where I'm trying to add the output to the main form in a label (in the frmMain() constructor).
class frmMain extends JFrame
//add main menu bar to JFrame
private jmbMainMenu mmb;
private JFrame _mainFrame;
private JLabel mylabel = new JLabel();
void init()
setTitle("SandBox");
setJMenuBar(mmb = new jmbMainMenu() );
setSize (500,300);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
System.exit(0);
frmMain()
//Labels
setLayout(new FlowLayout(FlowLayout.CENTER, 50, 50));
String str1 = new String(new keygen().myGenerator());
mylabel.setText(str1);
this.add(mylabel);
}My next step is to add a "Generate" button that displays a new random code when clicked, but I need to find out and understand what I'm doing wrong here first. Feel free to rip apart the code, and I'll appreciate any feedback.
Thanks!I do have a main, I just didn't add it in my first post,
public class keyUtil
public static void main (String[] args)
new frmMain().init();
}I forgot to take out the "f" variable. I was using it earlier and forgot to remove it from the code. I can also see how my loop is confusing.
Mel,
Your absolutely right. Originally I tried doing something like this,
do
for (int b = 0; b < 5; b++)
keys[f] = (data[rand.nextInt(n+1)]);
f++;
keys[f] = ("-");
a++;
f++;
} while (a < 4);
do
keys[f] = (data[rand.nextInt(n+1)]);
a++;
f++;
} while (a < 10);
return keys;Thats where the "f" came from. "f" was originally initialized to 0. I thought this would put a new character into each element of the "keys" array, but it didn't seem to work. I will go back and try this again.
Edited by: jd3cker on Jun 14, 2009 3:40 PM
Edited by: jd3cker on Jun 14, 2009 3:45 PM -
How to read .txt file into a 2D array ? Pls help !
I have a .txt file with contents as shown :
1 0 1 0 1 0 1 0
1 0 1 1 1 0 0 1
1 0 1 0 1 0 1 0
1 0 1 1 1 0 0 1
1 0 1 1 1 0 0 1
1 0 1 1 1 0 0 1
1 0 1 1 1 0 0 1
1 0 1 1 1 0 0 1
1 0 1 1 1 0 0 1
1 0 1 1 1 0 0 1
and so on...until 10 samples in total.
How do I create a class which has a method (which I can call later) to put all those binary digits in a 2-D array ? The method should automatically extract data from the .txt file and put it into a 2-D array. How do I do that please ?
Please help someone ? It's pretty urgent....:-(This one takes the cake: essentially the same question, cross-posted 11 times:
http://forum.java.sun.com/thread.jsp?thread=560218&forum=57&message=2752602
http://forum.java.sun.com/thread.jsp?thread=560219&forum=426&message=2752600
http://forum.java.sun.com/thread.jsp?thread=560220&forum=31&message=2752599
http://forum.java.sun.com/thread.jsp?thread=560220&forum=31&message=2752583
http://forum.java.sun.com/thread.jsp?thread=560220&forum=31&message=2752519
http://forum.java.sun.com/thread.jsp?thread=560219&forum=426&message=2752518
http://forum.java.sun.com/thread.jsp?thread=560218&forum=57&message=2752517
http://forum.java.sun.com/thread.jsp?thread=559967&forum=31&message=2750787
http://forum.java.sun.com/thread.jsp?thread=559968&forum=57&message=2750767
http://forum.java.sun.com/thread.jsp?thread=559967&forum=31&message=2750751
http://forum.java.sun.com/thread.jsp?thread=559964&forum=426&message=2750734
DON'T CROSS-POST! Send your question to one forum. You waste people's time
doing anything else.
How To Ask Questions The Smart Way -
Creating a byte Array dynamically.Urgent Help needed.
Hi there,
I need to create a byte Array with the values
derived from the array and then am passing this byte array
to a method.
Example :
public static void main(String[] args) throws IOException {
char chars[] = {'a','j','a','y'};
byte[] b = {
(byte) chars[0],(byte) chars[1],(byte) chars[2],(byte) chars[3],
//** Send name to a server.
sendRequest(b);
This is all right.
But here I know the size of the character array chars.
If it had more than 4 characters or less than 4,
is there a way to create the byte array dynamically based on the values in the character array?
Please can some one help me with creating a byte array on the fly?
Has anyone understood my question please?
A response is much much appreciated.The actual problem is this.
The byte array already has some fixed values to it
and i need to append the values of the character array
to this byte array
ie
char chars[] = {'a','j','a','y'};
byte b[] = {
// Predefined values
(byte) 0x01, (byte) 0x7E, (byte)0x03
// I have to add the values from the array here
(byte) chars[0], (byte) chars[1]....
How can I add these values.? The size of the character array
can vary
Maybe you are looking for
-
Static credit check: credit limit exceeded for consignment issue delivery
Hi, We are encountering a credit limit exceeded error in delivery creation for a consignment issue. In SPRO config "Credit limit check for order types", no credit limit check is assigned to the order type. However, there is one assigned for the deliv
-
Letter of Credit usage for Cross Company Code - sales
Dear All, Is is possible that we can use L/C Letter of Credit document for cross company code sales processing. client have created LC document for Company A which can also be utilized for Company B. Thanks,
-
Hi, I tried to connect to local DB, which caches Oracle 10g DB. It is impossible to connect through web Cache Administrator, when I specify Type Mode 0 - Oracle. I get this exception (I get the same exception when trying to connect through simple jdb
-
Replication CRM contact person to R3 as contact person
Hi, I'm trying to replicate CRM contact person from CRM to R/3 via MW. First initial created from R/3 to CRM. In the daily business the agent will create a new contact person thru the Call center transaction in CRM. (web client) How I can be sure tha
-
I have windows 8 on my laptop and love it so much. I like using word, but sometimes don't want to have to save random files to email them. I go to the save and send option in word, then click send as attachment. An error box appears: 'There is no pro