JFrame array
I'd like to know if it's possible to get the position of a component stored in an array of JFrames.
For example:
JFrame jframe[] = new JFrame [5];
if i add a mouse listener to each of the components of the array, can i get the position in which the current jframe selected by the click of the mouse is stored?
example:
JFrame jframe[] = new JFrame [5];
MyMouseListener ml = new MyMouseListener();
for (int i=0; i<5; i++)
jframe.addMouseListener(ml);
then, inside the class MyMouseListener:
public void mouseReleased (MouseEvent e){
e.getSource() //and i get panel that was clicked but which position does it occupy in the array?
is there a way to get also the position in which the panel was stored in the array?
thanks a lot
Um. When I said Windows only, I should have said WinXP only. Does Vista even have Minesweeper? The install I've used doesn't have any games. And the program depends on image matching, so it won't work on Win98/95 unless the images are changed.
Vista is a pain. The company gave us Vista laptops, mine has been booted up about 10 times in the 3-4 months I've had it. And I still use my own XP laptop for my VFP development.
A tip that may some day come in handy: a freeware program I've had from Win98 days which runs perfectly ok on XP was crashing in Vista even after setting compatibility mode to XP, but did run ok when I setting the compatibility mode to Win2k.
XP SP3 isn't so hot either, after installing it my Intel motherboard CD can't run its autoinstaller. When I put in a new HD recently, I had to reformat and start over to be sure my chipset drivers were correctly installed.
Darryl
Similar Messages
-
New frames vs. resetting documents
Hi everybody,
I'm fairly certain this is a conceptual thing I'm not getting--if I'm wrong, I'd be glad to post a SSCCE with my problem in it. But anyway, here goes, hopefully, I'm right about it being a conceptual thing. I have a JTextPane inside a JScrollPane, and when I hit a button, the JTextPane refreshes with new text. The only way I can get the JScrollPane to work with the current text, and not the text the pane was initialized to, is to make a new JFrame every time I hit that button. Now, what it seems is happening to me is that calling a new JFrame wipes out all the memory and allows the new data to work, and there must be some sort of memory that stays around if I don't do that. Am I right, conceptually, that creating the new JFrame is the only way to completely erase the JTextPane, and resetting documents doesn't actually erase it?
Thanks,
Jezzica85Hi everybody,
Thanks for trying to help so far; here's my SSCCE. I know that there are problems with incrementing in the page buttons; that's just a function of the test program--it works fine in my real program, but the real issue, how the text pane doesn't stay right at scrolling, is still intact. If anyone could help me figure this out with the SSCCE, I'd really appreciate it.
Thanks again,
Jezzica85
PS-- Oh, I forgot to say, I know it looks like my second argument to "display" doesn't do anything; it does something in my real program, and it just isn't necessary for the test. I didn't want to change the method signature, just in case.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.StyledDocument;
public class Test {
// need a 2D String array for input; usually I have it from an input file
// but for the test this should be OK
private static String[][] array = {
{ "test1", "test1b", "test1c", "test1d", "test1", "test1b", "test1c", "test1d", "test1", "test1b", "test1c", "test1d", "test1", "test1b", "test1c", "test1d", },
{ "test2", "test2b", "test2c", "test2d", "test2", "test2b", "test2c", "test2d", "test2", "test2b", "test2c", "test2d", "test2", "test2b", "test2c", "test2d", },
{ "test3", "test3b", "test3c", "test3d", "test3", "test3b", "test3c", "test3d", "test3", "test3b", "test3c", "test3d", "test3", "test3b", "test3c", "test3d", }
private static int previous, next;
public static void main(String[] args) {
display( new JFrame(), "", array[0], 1 );
private static void display( JFrame frame, String type, String[] lines, Integer page ) {
try {
final JFrame frameCopy = frame;
JPanel panel = new JPanel( new GridLayout( 0, 2 ) );
String[] buttons = { "Previous Page", "Next Page" };
for( int i = 0; i < 2; i++ ) {
JButton button = new JButton( buttons[i] );
if( i == 0 ) {
previous = page - 1;
button.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
display( frameCopy, "", array[previous], previous );
} else {
next = page + 1;
button.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
display( frameCopy, "", array[next], next );
panel.add( button );
frame.add( panel, BorderLayout.NORTH );
// Populate document
JTextPane pane = new JTextPane();
StyledDocument doc = pane.getStyledDocument();
for( String element: lines ) {
doc.insertString( doc.getLength(), element + "\n", null );
doc.remove( doc.getLength() - 1, 1 );
pane.setDocument( doc );
pane.setCaretPosition( 0 );
JScrollPane scroller = new JScrollPane( pane );
scroller.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
frame.add( scroller );
frame.setSize( 770, 150 );
frame.setLocationRelativeTo( null );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setVisible( true );
} catch( Exception e ) {
e.printStackTrace();
System.exit( -1 );
} -
How to Create the array of JFrames? So i can create multiple JFrames which I have to access in for loop.
How should I initialise it, in which I can add different contents in each frames like label,button,etc..?
Need help and some tutorial which will helpful for it?994334 wrote:
Need help and some tutorial which will helpful for it?http://lmgtfy.com/?q=jframe+tutorial
If you finnished working on this (first hit) than we can talk on the question why you usually should not need more than one frame.
bye
TPD -
Creating an array of buttons in a jframe
hi, i need help im trying to create a simple button game where there are 5x3 buttons in a jframe where the user can click on one to find the button with the prize on it, i know how to create the jframe but im trying to approch this in a object orientated way, with classes not a procedural way, and having no luck, any suggestions?
Ok, here what you want, but don't forget dukes:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class MyGame extends JPanel{
private Random rand ;
private int rows;
private int cols;
private int prizeX;
private int prizeY;
public MyGame(int rows, int cols){
//super(new GridLayout(rows, cols));
super(new BorderLayout());
this.rows = rows;
this.cols = cols;
JPanel p = new JPanel(new GridLayout(rows, cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
JButton b = new JButton(" Button [x="+i+", y="+j+"]");
b.addActionListener(new MyActionListener(i, j));
p.add(b);
this.add(p, BorderLayout.CENTER);
this.add(new MyReStartButton(), BorderLayout.SOUTH);
rand = new Random(System.currentTimeMillis());
prizeX = rand.nextInt(rows);
prizeY = rand.nextInt(cols);
System.out.println(prizeX+", "+prizeY);
class MyActionListener implements ActionListener{
private int x;
private int y;
public MyActionListener(int x, int y){
this.x=x;
this.y=y;
public void actionPerformed(ActionEvent e) {
if(x==prizeX&&y==prizeY){
JOptionPane.showMessageDialog(MyGame.this, " Winner !! ");
}else{
JOptionPane.showMessageDialog(MyGame.this, " Try again ");
class MyReStartButton extends JButton{
public MyReStartButton(){
super("Start new Game");
addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
MyGame.this.prizeX = rand.nextInt(rows);
MyGame.this.prizeY = rand.nextInt(cols);
System.out.println(prizeX+", "+prizeY);
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("MyGame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new MyGame(3, 5);
newContentPane.setOpaque(true); //content panes must be opaque
frame.setLayout(new BorderLayout());
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
} -
I am facing a programming issue here;
I am supposed to create an array of circle objects of random dimensions.
Next, I am supposed to check each circle and make sure it does not intersect with any other circle in the array. If it does, I am expected to remove the circles that intersect with it from the array. I have found this technique more feasible, but in the question, it is suggested to check for intersection before the circle is added to the array. To quote "Check that the new circle does not intersect a previous one. You will need to iterate through the array list and verify that the current circle does not intersect with a circle in the array list. Add the circle to the array list if it does not intersect with another one." For some reason, I think my approach is more feasible. But feel free to differ.
Then, I am supposed to draw the circles.
The program compiles but when it is run, only one circle is drawn.
Any advice would be appreciated, and as before thank you in advance.
import java.util.Random;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
import java.util.ArrayList;
import java.awt.Graphics2D;
import java.awt.Graphics;
public class CirclesComponent extends JComponent
public CirclesComponent(int numberCircles)
NCIRCLES = numberCircles;
circles = new ArrayList<Ellipse2D.Double>();
final int XRANGE = 292;
final int YRANGE = 392;
final int RRANGE = 20;
generator = new Random();
double x = generator.nextInt(XRANGE) + 1;
double y = generator.nextInt(YRANGE) + 1;
double r = generator.nextInt(RRANGE) + 1;
double w = 2 * r;
double h = 2 * r;
for (int i = 1; i <= NCIRCLES; i++)
Ellipse2D anEllipse = new Ellipse2D.Double(x, y, w, h);
circles.add(anEllipse);
Test if two circles intersect.
(distance between centers is less than sum of radii)
public void circlesIntersect()
Ellipse2D zeroEllipse = (Ellipse2D)circles.get(0);
for (int v = 1; v <= circles.size(); v++)
Ellipse2D anotherEllipse = (Ellipse2D)circles.get(v);
double radius1 = zeroEllipse.getWidth() / 2;
double radius2 = anotherEllipse.getWidth() / 2;
double dx = zeroEllipse.getX() + radius1 - anotherEllipse.getX() - radius2;
double dy = zeroEllipse.getY() + radius1 - anotherEllipse.getY() - radius2;
double distance = Math.sqrt(dx * dx + dy * dy);
if (distance < radius1 + radius2)
circles.remove(v);
public void paintComponent(Graphics g)
Graphics2D g2 = (Graphics2D) g;
for (int z = 0; z < circles.size(); z++) // iterate through every circle in the list
g2.draw((Ellipse2D)circles.get(z)); // draw the circle
public void getRejection()
System.out.println("The percentage of rejected circles is " + ((circles.size() / NCIRCLES ) * 100));
System.out.println("The size of the array is " + (circles.size()));
private int NCIRCLES;
private ArrayList circles;
private Random generator;
import java.util.Scanner;
import java.awt.Graphics2D;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class CirclesTester
public static void main(String[] args)
Scanner thescanner = new Scanner(System.in);
System.out.print("How many circles do you want? ");
int totalCircles = thescanner.nextInt();
CirclesComponent theCircle = new CirclesComponent(totalCircles);
theCircle.getRejection();
JFrame frame = new JFrame();
frame.setSize(300, 400);
frame.setTitle("Non-Intersecting Circles");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(theCircle);
frame.setVisible(true);
}homebrewed wrote:
I am supposed to create an array of circle objects of random dimensions.
Next, I am supposed to check each circle and make sure it does not intersect with any other circle in the array. If it does, I am expected to remove the circles that intersect with it from the array. I have found this technique more feasible, but in the question, it is suggested to check for intersection before the circle is added to the array. To quote "Check that the new circle does not intersect a previous one. You will need to iterate through the array list and verify that the current circle does not intersect with a circle in the array list. Add the circle to the array list if it does not intersect with another one." For some reason, I think my approach is more feasible. But feel free to differ.Gladly. It is much simpler to iterate over a List and check if the new circle is valid than to iterate over a List and remove those circles that make the new circle invalid. Note that the code you have now will skip items in the list when a circle is removed.
Then, I am supposed to draw the circles.
The program compiles but when it is run, only one circle is drawn. And why is that? Is it only drawing one of the circles? Is it drawing all the circles but they're all the same circle? Does your list only contain one circle?
You need to run your program in a debugger or add println() statements to output your program state at important points along the execution path.
Once you figure out why you're only getting one circle, it becomes much simpler to figure out how it happened. -
Java Graphics -- Drawing Strings on JFrame
Hello and thank you. I'm relatively young and I apologize for asking noob questions. The problem I am having is that I realized after 3 hours of research and then writing this code that when multiple JPanels are added to a JFrame, they overlap (I think) over each other. As a result, the output of this program below is at the bottom right of the frame, the number 841 appears (the last number in my array) and everything else is blank.
And I could not at all understand how to create graphics objects. It kept giving me an error of not being able to be instantiated. And to be honest, I don't even really understand whats going on when I add the text to my JPanel. I never call paintComponents. And definately I could never even make a graphics object to provide it the parameter required. Anyway, I resolved to use Jpanels because they can be removed using the remove function of the JFrame. And It is vitally important that I can delete the strings off my frame. Here is my code:
package main;
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class VisualFrame extends JFrame{
ArrayList<JPanel> numbers = new ArrayList<JPanel>();
public VisualFrame(){
setSize(1000, 500);
setTitle("Binary Search");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
public void createPanels(int[] array){
int x = 10;
int y = 20;
int xOffset = 50;
int yOffset = 50;
for(int i=0; i<array.length; i++){
String num = Integer.toString(array);
numPanel panel = new numPanel(num, x, y);
numbers.add(panel);
add(panel);
x = x+xOffset;
if(x>this.getWidth()){
x = 10;
y = y+yOffset;
class numPanel extends JPanel{
String num;
int x;
int y;
public numPanel(String str, int x, int y){
num = str;
this.x = x;
this.y = y;
public void paintComponent(Graphics g){
g.setColor(Color.black);
g.setFont(new Font("Times", Font.BOLD, 12));
g.drawString(num, x, y);
My main method is inside of a different class:
public static void main(String[] args){
VisualFrame frame = new VisualFrame();
frame.createPanels(array);
}Firstly, do I even have the problem I'm having right? If so,
Is there a way to restrict the size of the panels to the length and width of what it contains?
Or can someone give me a good, very detailed link to how to use Graphics? Or perhaps someone could prove to me a good method.
Edited by: 989946 on Mar 8, 2013 6:45 PMWhy don't you start by learning from the experts?
The Java Tutorial has sections that show how to use Java functionality.
http://docs.oracle.com/javase/tutorial/
The Graphiics section covers GUI and Swing
http://docs.oracle.com/javase/tutorial/uiswing/index.html
>
Creating Graphical User Interfaces
Creating a GUI with Swing — A comprehensive introduction to GUI creation on the Java platform.
>
And that section has links for trails such as how to use ALL of the different swing components including frames and panels
http://docs.oracle.com/javase/tutorial/uiswing/components/index.html
>
Using Swing Components tells you how to use each of the Swing components — buttons, tables, text components, and all the rest. It also tells you how to use borders and icons. -
Reading from file into an array
Hello, new to Java and we need to modify a mortgage calculator to read interest rate from a file into an array and not have them hard coded in the program. I have read many post on how to perform this but am lost on where to put the new code and format. Here is my code and I hope I posted this right.
import javax.swing.*; // Imports the Main Swing Package
import javax.swing.event.*;
import javax.swing.text.*; // Used for Text Box Caret Position
import java.awt.*; // Imports the main AWT Package
import java.awt.event.*; // Event handling class are defined here
import java.text.NumberFormat;
import java.text.*; // Imports the Main Text Package
import java.util.*; // Imports the Main Utility Package
public class mortgageCalculator1 extends JFrame implements ActionListener // Creates class mortgageCalculator
JLabel AmountLabel = new JLabel(" Enter Mortgage Amount:$ "); // Declares Mortgage Amount Label
JTextField mortgageAmount = new JTextField(10); // Declares Mortgage Amount Text Field
JButton IntandTerm1B = new JButton("7 years at 5.35%"); // Declares 1st Mortgage Term and Interest Rate
JButton IntandTerm2B = new JButton("15 years at 5.50%"); // Declares 2nd Mortgage Term and Interest Rate
JButton IntandTerm3B = new JButton("30 years at 5.75%"); // Declares 3rd Mortgage Term and Interest Rate
JLabel PaymentLabel = new JLabel(" Monthly Payment: "); // Declares Monthly Payment Label
JTextField monthlyPayment = new JTextField(10); // Declares Monthly Payment Text Field
JButton exitButton = new JButton("Exit"); // Declares Exit Button
JButton newcalcButton = new JButton("New Calculation"); // Declares New Calculation Button
JTextArea mortgageTable = new JTextArea(35,65); // Declares Mortgage Table Area
JScrollPane scroll = new JScrollPane(mortgageTable); // Declares ScrollPane and puts the Mortgage Table inside
public mortgageCalculator1() // Creates Method
super("MORTGAGE CALCULATOR"); // Title of Frame
JMenuBar mb = new JMenuBar(); // Cretes Menu Bar
JMenu fileMenu = new JMenu("File"); // Creates File Menu
fileMenu.setMnemonic('F'); // Enables alt + f to Access File Menu
JMenuItem exitItem = new JMenuItem("Exit"); // Creates Exit in File Menu
fileMenu.add(exitItem); // Adds Exit to File Menu
exitItem.addActionListener(new ActionListener() // Adds Action Listener to the Exit Item
public void actionPerformed(ActionEvent e) // Tests to Verify if File->Exit is Pressed
System.exit(0); // Exits the Programs when File->Exit is Pressed
mb.add(fileMenu); // Adds the File Menu
setJMenuBar(mb);
setSize(600, 400); // Sets Size of Frame
setLocation(200,200); // Sets the Location of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Command on how to close frame
JPanel pane = new JPanel(); // Declares the JPanel
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); // Sets Panel Layout to BoxLayout
Container grid = getContentPane(); // Declares a Container called grid
grid.setLayout(new GridLayout(4,3,5,5)); // Sets grid Layout to GridLayout
pane.add(grid); // Adds the grid to the Panel
pane.add(scroll); // Addes the scrollPane to the Panel
grid.setBackground(Color.yellow); // Set grid color to Yellow
setCursor(new Cursor(Cursor.HAND_CURSOR)); // Makes the cursor look like a hand
mortgageAmount.setBackground(Color.black); // Sets mortgageAmount JPanel JTextField Background Color
mortgageAmount.setForeground(Color.white); // Sets mortgageAmount JPanel JTextField Foreground Color
mortgageAmount.setCaretColor(Color.white); // Sets mortgageAmount JPanel JTextField Caret Color
mortgageAmount.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18)); // Sets mortgageAmount JPanel JTextField Font
monthlyPayment.setBackground(Color.black); // Sets monthlyPayment JPanel JTextField Background Color
monthlyPayment.setForeground(Color.white); // Sets monthlyPayment JPanel JTextField Foreground Color
monthlyPayment.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18)); // Sets monthlyPayment JPanel JTextField Font
mortgageTable.setBackground(Color.yellow); // Sets mortgageTable JTextArea Background Color
mortgageTable.setForeground(Color.black); // Sets mortgageTable JTextArea Foreground Color
mortgageTable.setFont(new Font("Arial", Font.PLAIN, 18)); // Sets JTextArea Font
grid.add(AmountLabel); // Adds the Mortgage Amount Label
grid.add(mortgageAmount); // Adds the Mortgage Amount Text Field
grid.add(IntandTerm1B); // Adds 1st Loan and Rate Button
grid.add(PaymentLabel); // Adds the Payment Label
grid.add(monthlyPayment); // Adds the Monthly Payment Text Field
monthlyPayment.setEditable(false); // Disables editing in this Text Field
grid.add(IntandTerm2B); // Adds 2nd Loan and Rate Button
grid.add(exitButton);
grid.add(newcalcButton); // Adds the New Calc Button
grid.add(IntandTerm3B); // Adds the Exit Button
setContentPane(pane); // Enables the Content Pane
setVisible(true); // Sets JPanel to be Visable
exitButton.addActionListener(this); // Adds Action Listener to the Exit Button
newcalcButton.addActionListener(this); // Adds Action Listener to the New Calc Button
IntandTerm1B.addActionListener(this); // Adds Action Listener to the 1st loan Button
IntandTerm2B.addActionListener(this); // Adds Action Listener to the 2nd loan Button
IntandTerm3B.addActionListener(this); // Adds Action Listener to the 3rd loan Button
mortgageAmount.addActionListener(this); // Adds Action Listener to the Mortgage Amount Text Field
monthlyPayment.addActionListener(this); // Adds Action Listener to the Monthly payment Text Field
public void actionPerformed(ActionEvent e) // Tests to Verify Which Button is Pressed
Object command = e.getSource(); // Enables command to get data
if (command == exitButton) //sets exitButton // Activates the Exit Button
System.exit(0); // Exits from exit button // Exits from exit button
int loanTerm = 0; // Declares loanTerm
if (command == IntandTerm1B) // Activates the 1st Loan Button
loanTerm = 0; // Sets 1st value of Array
if (command == IntandTerm2B) // Activates the 2nd Loan Button
loanTerm = 1; // Sets 2nd value of Array
if (command == IntandTerm3B) // Activates the 3rd Loan Button
loanTerm = 2; // Sets 3rd value of Array
double mortgage = 0; // Declares and Initializes mortgage
double rate = 0; // Declares and Initializes rate
double [][] loans = {{7, 5.35}, {15, 5.50}, {30, 5.75},}; // Array Data for Calculation
try
mortgage = Double.parseDouble(mortgageAmount.getText()); // Gets user input from mortgageAmount Text Field
catch (NumberFormatException nfe) // Checks for correct number fformatting of user input
JOptionPane.showMessageDialog (this, "Error! Invalid input!"); // Outputs error if number is wrong format or nothing is entered
return;
double interestRate = loans [loanTerm][1]; // Sets interestRate amount
double intRate = (interestRate / 100) / 12; // Calculates Interst Rate
double loanTermMonths = loans [loanTerm] [0]; // Calculates Loan Term in Months
int months = (int)loanTermMonths * 12; // Converts Loan Term to Months
double interestRateMonthly = (intRate / 12); // monthly interst rate
double payment = mortgage * intRate / (1 - (Math.pow(1/(1 + intRate), months))); // Calculation for Monthly payment
double remainingLoanBalance = mortgage; // Sets Reamaining Balance
double monthlyPaymentInterest = 0; // holds current interest payment
double monthlyPaymentPrincipal = 0; // holds current principal payment
NumberFormat myCurrencyFormatter = NumberFormat.getCurrencyInstance(Locale.US); // Number formatter to format output in table
monthlyPayment.setText(myCurrencyFormatter.format(payment));
mortgageTable.setText("Month\tPrincipal\tInterest\tEnding Balance\n" + // Formats morgageTable Header
"---------\t----------\t------------\t---------------------\n");
for (;months > 0 ; months -- )
monthlyPaymentInterest = (remainingLoanBalance * intRate); // Calculation for Monthly Payment Toward Interest
//Calculate H = R x I
monthlyPaymentPrincipal = (payment - monthlyPaymentInterest); // Calculation for Monthly Payment Toward Principal
//Calculate C = P - H
remainingLoanBalance = (remainingLoanBalance - monthlyPaymentPrincipal); // Calculation for Reamining loan Balance
// Calculate R = R - C
// H = monthlyPaymentInterest
// R = remainingLoanBalance
// P = payment
// C = monthlyPaymentPrincipal
// I = interestRateMonthly
mortgageTable.setCaret (new DefaultCaret()); // Sets Scroll position to the top left corner
mortgageTable.append(String.valueOf(months) + "\t" + // Pulls in data and formats MortgageTable
myCurrencyFormatter.format(monthlyPaymentPrincipal) + "\t" +
myCurrencyFormatter.format(monthlyPaymentInterest) + "\t" +
myCurrencyFormatter.format(remainingLoanBalance) + "\n");
if(command == newcalcButton) // Activates the new calculation Button
mortgageAmount.setText(null); //clears mortgage amount fields
monthlyPayment.setText(null); //clears monthly payment fields
mortgageTable.setText(null); //clears mortgage table
public static void main(String[] args) //This is the signature of the entry point of all the desktop apps
new mortgageCalculator1();
}OK, making a little progress but am still very confused.
What I have is a file (int&term.dat) with three lines;
5.75, 30
5.5, 15
5.35 ,7
I have three JButtom that I what to read a seperate line and place the term in a term TextField and a rate in a Rate TextField
I have added the following code and all it does now is output a black space to the screen; I am working with one Button and Just the rate for now to try and get it to work. I have been looking at the forums, reading the internet and several books to try and figure this out. I think I may be getting closer.
public static void read()
String line;
StringTokenizer tokenizer;
String rate;
String term;
try
FileReader fr = new FileReader ("int&term.dat");
BufferedReader inFile = new BufferedReader (fr);
line = inFile.readLine();
while (line != null)
tokenizer = new StringTokenizer(line);
rate = tokenizer.nextToken();
line = inFile.readLine();
inFile.close();
System.out.println(new String());
catch (FileNotFoundException exception)
System.out.println ("The file was not found.");
catch (IOException exception)
System.out.println (exception);
} -
Java code to get integer values from a gridLayout to put into an array?
I am writing a tictactoe game for a programming class. I made a grid of 3x3 layout and it alternates between putting an X when clicked and an O. I need to know how to retrieve what button off the grid was picked so I can create an array to check for win conditions...Or how to access the rowIndex and columnIndex of a selected button on the grid
Thanks in advance
Edited by: ryAnOnFire on May 23, 2010 6:10 PMimport java.awt.*;
import java.awt.Container;
import javax.swing.*;
import java.awt.event.*;
public class TicTacToe
JFrame theWindow;
JButton theButton;
Container thePane;
JTextField theText;
MyListener theListener;
public JButton[][] grid = new JButton[3][3];
public TicTacToe()
theWindow = new JFrame("Tic Tac Toe");
theWindow.setSize(250, 250);
String empty = " ";
theListener = new MyListener();
JFrame frame = new JFrame("TicTacToe");
Container thePane = theWindow.getContentPane();
thePane.setLayout(new GridLayout (3,3,5,5));
for(int i = 0; i < 3; i++)
for(int j =0; j < 3; j++)
grid[i][j] = new JButton(empty);
thePane.add(grid[i][j]);
grid[i][j].addActionListener(theListener);
JButton blankSpot = new JButton(empty);
blankSpot.setFont(new Font("Papyrus", Font.BOLD, 35));
theWindow.setVisible(true);
public static void main(String[] args)
new TicTacToe();
class MyListener implements ActionListener
String[][] spots1 = new String[3][3];
String[][] spots2 = new String[3][3];
static int playerTurnCounter = 0;
JButton[][] grid; // !! added
// !! added
public MyListener(JButton[][] grid)
this.grid = grid;
public void actionPerformed(ActionEvent e)
JButton jb = (JButton)e.getSource();
if(playerTurnCounter % 2 == 0)
jb.setText("X");
for(int i = 0; i < grid.length; i++)
for(int j = 0; j < grid.length; j++)
spots1[i][j] = grid[i][j].getText();
if((spots1[0][0].equals("X")))
JOptionPane.showMessageDialog(null, "TICTACTOE", "WIN", JOptionPane.PLAIN_MESSAGE);
//The problem seems to be occuring in the above block commented area
else
jb.setText("O");
jb.setEnabled(false);
playerTurnCounter ++;
Compiler Error:
C:\Documents and Settings\HP_Administrator\My Documents\TicTacToe.java:24: cannot find symbol
symbol : constructor MyListener()
location: class MyListener
theListener = new MyListener();
^
1 error
Tool completed with exit code 1
I'm just going to let you ponder over this as I do too...
I have no idea...my minimal experience with ActionListeners is doing me nothing for this one.
Edited by: ryAnOnFire on May 23, 2010 8:12 PM -
ActionListener not working with JFrame
Hi,
I've just rehashed an old bit of code to work with a new application but for some reason the JButton ActionListeners aren't working. However if I extend JDialog they work ok. The current code for JDialog is:-
* File: GUI.java
* @author ODL 3xx Distributed Systems - Team x
* @description This class provides a means for the user to
* interact with file server.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class GUI extends JDialog implements ActionListener, ApplicationConstants {
private JLabel label1, label2, label3, label4, label5;
private JTextField field1, field2, field3, field4, field5;
private JButton button1, button2, button3, button4, button5;
private Container container;
private Message sendFile;
private String id;
private String defaultText = "Enter file name here";
private ClientForGUI client;
private long timeStart, timeEnd;
public GUI(JFrame frame) {
super(frame, "File Server Actions", true);
client = new ClientForGUI(this);
try{
InetAddress addr = InetAddress.getLocalHost();
id = addr.getHostName() + Long.toString((new java.util.Date()).getTime());
if(client.connectToServer())
initGUI();
else{
JOptionPane.showMessageDialog(this, "Unable to connect to server", "Error", JOptionPane.WARNING_MESSAGE);
System.exit(0);
catch(UnknownHostException uhe){
System.out.println("Unknown Host Exception");
initGUI();
* Create the GUI
private void initGUI() {
container = this.getContentPane();
container.setLayout(null);
label1 = new JLabel("Upload File");
label2 = new JLabel("Rename File");
label3 = new JLabel("Delete File");
label4 = new JLabel("Create File");
label5 = new JLabel("Download File");
field1 = new JTextField();
field2 = new JTextField();
field3 = new JTextField();
field4 = new JTextField();
field5 = new JTextField();
button1 = new JButton("Upload");
button2 = new JButton("Rename");
button3 = new JButton("Delete");
button4 = new JButton("Create");
button5 = new JButton("Download");
label1.setBounds(10,10,80,20);
label2.setBounds(10,40,80,20);
label3.setBounds(10,70,80,20);
label4.setBounds(10,100,80,20);
label5.setBounds(10,130,80,20);
field1.setBounds(100,40,200,20);
field1.setText("Old name");
field2.setBounds(310,40,200,20);
field2.setText("New name");
field3.setBounds(100,70,410,20);
field3.setText(defaultText);
field4.setBounds(100,100,410,20);
field4.setText(defaultText);
field5.setBounds(100,130,410,20);
field5.setText(defaultText);
button1.setBounds(100,10,100,20);
button1.addActionListener(this);
button2.setBounds(520,40,100,20);
button2.addActionListener(this);
button3.setBounds(520,70,100,20);
button3.addActionListener(this);
button4.setBounds(520,100,100,20);
button4.addActionListener(this);
button5.setBounds(520,130,100,20);
button5.addActionListener(this);
container.add(label1);
container.add(button1);
container.add(label2);
container.add(field1);
container.add(field2);
container.add(button2);
container.add(label3);
container.add(field3);
container.add(button3);
container.add(label4);
container.add(field4);
container.add(button4);
container.add(label5);
container.add(field5);
container.add(button5);
setSize(640,200);
setResizable(false);
//Centre on the screen
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((d.getWidth() - getWidth()) / 2);
int y = (int) ((d.getHeight() - getHeight()) / 2);
setLocation(x,y);
setVisible(true);
private void sendMessageToServer(Message message){
message.setId(id);
timeStart = new java.util.Date().getTime();
try{
client.sendMessageToServer(message);
catch(IOException ioe){
System.out.println("Unable to send message to server");
* Perform some action based on user interaction
* @param ae - ActionEvent
public void actionPerformed(ActionEvent e){
Object o = e.getSource();
String name;
if(o == button1){
try{
JFileChooser fc = new JFileChooser();
fc.setVisible(true);
//return value is what the user presses in the open File dialog
int returnVal = fc.showOpenDialog(null);
//if they choose OK
if (returnVal == JFileChooser.APPROVE_OPTION) {
//file now references the selected
File file = fc.getSelectedFile();
//create a FileInputStream from file location
FileInputStream fis = new FileInputStream(file);
// Create the byte array to hold the data, the same size as the file
byte [] fileBytes = new byte[(int)file.length()];
// Read in the bytes from the file into the byte array
int offset = 0;
int numRead = 0;
while (offset < fileBytes.length &&
(numRead=fis.read(fileBytes, offset, fileBytes.length-offset)) >=
0) {
offset += numRead;
// Ensure all the bytes have been read in
if (offset < fileBytes.length) {
throw new IOException("Could not completely read file "+file.getName());
fis.close();
sendFile = new Message(SEND_FILE, fileBytes);
sendFile.setId(id);
sendFile.setFileName(file.getName());
byte [] myarray = ConvertData.messageToBytes(sendFile);
Message sendWarning = new Message(SEND_FILE_WARNING);
sendWarning.setFileName(file.getName());
sendWarning.setFileSize(myarray.length);
try{
sendMessageToServer(sendWarning);
catch(Exception excep){
System.out.println(excep);
catch(FileNotFoundException fnfe){
System.out.println("File Not Found Exception");
catch(java.io.IOException ioe){
System.out.println("IO Exception");
else if(o == button2){
name = field1.getText();
String name2 = field2.getText();
Message renameMessage = new Message(RENAME_FILE);
renameMessage.setFileName(name);
renameMessage.setFileRename(name2);
sendMessageToServer(renameMessage);
field1.setText("Old name");
field2.setText("New name");
else if(o == button3){
name = field3.getText();
Message deleteMessage = new Message(DELETE_FILE);
deleteMessage.setFileName(name);
sendMessageToServer(deleteMessage);
field3.setText(defaultText);
else if(o == button4){
name = field4.getText();
Message createMessage = new Message(CREATE_FILE);
createMessage.setFileName(name);
sendMessageToServer(createMessage);
field4.setText(defaultText);
else if(o == button5){
name = field5.getText();
Message downloadMessage = new Message(REQUEST_FILE);
downloadMessage.setFileName(name);
sendMessageToServer(downloadMessage);
field5.setText(defaultText);
public void processServerMessage(Message message){
switch(message.getMessageHeader()){
case SEND_FILE_WARNING:
//change the download size to file size plus max message size
client.setDownload((int)message.getFileSize(),true);
//turn message back around with acknowledgement header
message.setMessageHeader(SEND_FILE_ACK);
//send the message
try{
sendMessageToServer(message);
catch(Exception e){
System.out.println(e);
break;
//server has acknowledged that the client wishes to send a message
//so send the message
case SEND_FILE_ACK:
//send the message
try{
sendMessageToServer(sendFile);
catch(Exception e){
System.out.println(e);
break;
//server is sending the file to the client.
case SEND_FILE:
//reset the download size to default
client.setDownload(DEFAULT_MESSAGE_SIZE,false);
//get the file name
File f = new File(message.getFileName());
//create the file chooser
JFileChooser fc = new JFileChooser();
//set selected file as thoe one downloaded
fc.setSelectedFile(f);
//get the button hit by the user
int returnVal = fc.showSaveDialog(null);
//if button is OK
if (returnVal == JFileChooser.APPROVE_OPTION){
File temp = fc.getCurrentDirectory();
String [] files = temp.list();
java.util.List alist = java.util.Arrays.asList(files);
f = fc.getSelectedFile();
if(alist.contains(message.getFileName())){
if(JOptionPane.showConfirmDialog(null,
message.getFileName() + " already exists. Are you sure you want to overwrite this file?",
"Instant Messenger: Quit Program",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null) == JOptionPane.YES_OPTION) {
//f = fc.getSelectedFile();
System.out.println(f.toString());
//this is where the file is copied
try{
FileOutputStream fs = new FileOutputStream(f);
fs.write(message.getFile());
fs.close();
catch(IOException e){
System.out.println(e);
else fc.hide();
else{
System.out.println("Here " + f.toString());
try{
FileOutputStream fs = new FileOutputStream(f);
fs.write(message.getFile());
fs.close();
catch(IOException e){
System.out.println(e);
else fc.hide();
break;
case INFORMATION:
timeEnd = new java.util.Date().getTime();
Long rtrip = timeEnd - timeStart;
String str = Long.toString(rtrip);
double d = Double.valueOf(str).doubleValue();
String fullMessage = message.getMessage();
fullMessage += " The total time taken for the last request was " +
rtrip + " milliseconds" + " or roughly " + d/1000 + " seconds";
JOptionPane.showMessageDialog(null,fullMessage,"Information",JOptionPane.INFORMATION_MESSAGE);
break;
class TestGUI{
public static void main(String [] args){
JFrame frame = new JFrame();
GUI myGUI = new GUI(frame);
} If I change the GUI constructor to empty and extend JFrame instead of JDialog and change the call to super the ActionListener stops working. I've never known this problem before (i.e. I always use e.getSource()). I've even cast the object to a JButton to ensure that the right button is pressed and it is all ok.
Is there something fundamentally wrong when I make those simple changes to JFrame?
Regards,
ChrisI think rather the approach is your action handling in terms of the buttons. The giant actionPerformed method is difficult to read and maintain.
I would recommend the following things:
1. Split your ActionListener into multiple smaller listeners. There's not really even a reason for the GUI class to be an action listener. Instead of having GUI implement ActionListener and trying to keep all of the functionality in one place, use anonymous classes:
button3.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
name = field3.getText();
Message deleteMessage = new Message(DELETE_FILE);
deleteMessage.setFileName(name);
sendMessageToServer(deleteMessage);
field3.setText(defaultText);
button4.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
name = field4.getText();
Message createMessage = new Message(CREATE_FILE);
createMessage.setFileName(name);
sendMessageToServer(createMessage);
field4.setText(defaultText);
2. Only use the == operator on primitives. There are very few cases in which you can properly use the == operator on objects and, in every one of those cases I have experienced, the equals(Object) method produces the same result.
3. Name your variables more descriptively. There is really very little reason for your buttons to be named button1, button2, and so on. Give them names that mean something. For example, button1 should be named something like uploadFileButton or buttonUpload. That will give us significant information about what it is expected to do, whereas button1 does not. You may be able to remember what button1 does, but you wrote the code. I keep having to refer back to the instantiation of the button to get a hint as to what it does and, in a few months' time, so will you. :) The same goes for your labels and fields, as well.
I'm not sure why you aren't getting the behavior you want. However, have you checked to determine that the event source of the button click is actually the button when the whole thing is inside of a JFrame? I would expect it to be, but you never know. This is why I recommend using different ActionListeners for each button. That way, you can be sure of what caused the event.
Just my 2c. Good luck to you. :) -
Painting Graphics from an Array
I have a GUI that displays the Towers of Hanoi solution in a JPanel. Everything actually works except for a slight repainting issue.
Currently I am overriding the paint() function, I know that for my purpose using paintComponent() would probably be the better route, however that's not my issue...
The images (disks) in my JPanel are not redrawing properly, and I have no idea why...
Basically:
- I call setup() to set the number of disks and the co ordinates they should be drawn. (store them in an array)
- I call moveDisk() to change the co ordinates of each disk as they are being moved.
- then drawDisk() is called to go through the array of disks and print them.
currently paint() calls drawDisk() in order to display the current position of all the disks.
It seems to work fine for the first 2 moves, then disks start disappearing until there is one (the last disk) left...BUT if I print the co ordinates of the disks they seem to be correct, just not drawing.
could someone take a look at my code and see what is wrong?
below is the meat of the code, minus the GUI:
public class HanoiFrame extends javax.swing.JFrame {
private static final int STATE_SETUP = 0;
private static final int STATE_ANIMATE = 1;
private static final int POLE_AREA_HEIGHT = 356;
private static final int POLE_AREA_WIDTH = 205;
private static final int DISK_ARC_HEIGHT = 15;
private static final int DISK_ARC_WIDTH = 15;
private static final int DISK_HEIGHT = 23;
private static final int MAX_DISKS = 10;
private static final int MAX_ANIMATION_DELAY = 30000;
private static final int MAX_PHYSICAL_DELAY = 100000;
private static final int MIN_DISKS = 1;
private static final int MIN_ANIMATION_DELAY = 1;
private static final int MIN_PHYSICAL_DELAY = 1;
private static final int EMPTY_CELL_VALUE = -1;
private static final int CELL_HEIGHT = 25;
private static final int COLUMNS = 3;
private static final int ROW = 11;
private static final int MILLISECONDS_PER_SECOND = 1000;
private final static String newline = "\n";
private static Disk[] disks;
private static Disk newDisk;
private static int[][] diskCells;
public static int startX = 2;
public static int startY = 340;
public static int setDiskAmount = 0;
public static int setAnimationDelay = 0;
public static int setPhysicalDelay = 0;
public static int moveNumber = 0;
public static int intMovesLeft = 0;
private boolean buttonPressed = false;
private double movesLeft = 0;
private int windowState = 0;
/** Creates new form HanoiFrame */
public HanoiFrame() {
initComponents();
/* initialize the "poles" to hold a certain number of "cells */
this.diskCells = new int[ROW][COLUMNS];
for (int row = ROW - 1;row >= 0; row--) {
for (int col = 0;col < COLUMNS ; col++) {
diskCells[row][col] = EMPTY_CELL_VALUE;
private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {
/* reset all the variable to original state */
setDiskAmount = 0;
setAnimationDelay = 0;
setPhysicalDelay = 0;
moveNumber = 0;
movesLeft = 0;
intMovesLeft = 0;
buttonPressed = false;
windowState = 0;
this.startButton.setEnabled(true);
this.diskAmount.setEditable(true);
this.animationDelay.setEditable(true);
this.physicalDelay.setEditable(true);
/* reset all the cell vales to empty (this could be its own function) */
for (int row = ROW - 1;row >= 0; row--) {
for (int col = 0;col < COLUMNS ; col++) {
diskCells[row][col] = EMPTY_CELL_VALUE;
/* reset the content of the TextFields and Area */
this.diskAmount.setText("");
this.animationDelay.setText("");
this.physicalDelay.setText("");
this.outTextArea.setText("");
/* repaint the display panel */
this.hanoiPanel.repaint();
/* i have no idea why this is here...It was generated by Netbeans when I
*made the reset button. As you can see it made 2. The one above it the same
*except it contains code. Since it was automatically generated
*I cannot delete it.
private void resetButtonMouseReleased(java.awt.event.MouseEvent evt) {
/* is executed when the start button is pressed.
*also executes a field check and intializes key variables. Finally,
*it executes the solution and generates the solve time
private void startButtonMouseReleased(java.awt.event.MouseEvent evt) {
/* check if the program has already been run (without being reset) */
if (!buttonPressed){
/* check the fields to ensure the input is correct and useable */
if (checkFields()){
/* give button a pressed status if all info valid */
buttonPressed = true;
windowState = 1;
/* disable the button */
this.startButton.setEnabled(false);
/* disable the fields */
this.diskAmount.setEditable(false);
this.animationDelay.setEditable(false);
this.physicalDelay.setEditable(false);
/* setup the disks on the starting pole */
setup();
/* initialize the number of moves required. 2 to the power of n minus 1 */
movesLeft = Math.pow(2, setDiskAmount) - 1;
/* convert the number to an integer */
intMovesLeft = (int)movesLeft;
/* set the physical delay */
setPhysicalDelay = Integer.parseInt(this.physicalDelay.getText());
/* create and start a new thread. This is EXTREMELY important
*as it allows for GUI to be repainted while the soulution
*is animated */
SolveEngine s = new SolveEngine();
s.start();
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new HanoiFrame().setVisible(true);
/*returns the Animation panel area graphics
*@return Animation area graphics
public static Graphics getAnimationArea(){
/* get the usable area of poleA */
Container clientArea = hanoiPanel;
//Container clientArea = this.getContentPane();
/* get the graphics to the display panel*/
Graphics gfx = clientArea.getGraphics();
return gfx;
*set up the requested amount of disks on the first pole
*@param diskAmount the amount of disks entered by the user
public void setup(){
int numberOfDisks = setDiskAmount;
this.disks = new Disk[numberOfDisks];
int diskNumber = 0;
int diskWidth = POLE_AREA_WIDTH - 4;
int arcH = DISK_ARC_HEIGHT;
int arcW = DISK_ARC_WIDTH;
int x = startX;
int y = startY;
int row = 0;
int col = 0;
/* get the graphics to the display panel*/
//Graphics gfx = getAnimationArea();
/* set the color of the disks */
//gfx.setColor(Color.MAGENTA);
/* draw the specified number of disks */
while (diskNumber < numberOfDisks){
/* reduce the y position */
y = startY - diskNumber * CELL_HEIGHT;
/* draw the disk */
//gfx.fillRoundRect(x, y, diskWidth, DISK_HEIGHT, arcH, arcW);
/* create a new instance of disk */
newDisk = new Disk(x, y, diskWidth);
/* give the new disk an id */
this.disks[diskNumber] = newDisk;
/* add the id to the cell array of poleA */
this.diskCells[row][col] = diskNumber;
/* make the disk smaller and center */
x = x + 8;
diskWidth = diskWidth - 16;
/* increase disk number */
diskNumber++;
/* move to the next row */
row++;
repaint();
*move the disk from a source pole to the destination pole.
*this should take the source col and destination col to determine where to draw the
*disk. It will also need to know to draw the disk in the first available cell
*in a col
*@param source the starting pole of the next move
*@param destination the end pole of the next move
public void moveDisk(int src, int dest){
/* the lines below would not be necessary if I were to pass the Graphics
*gfx object as a parameter. I may have to use this option in order
*to work around the current repainting issue */
/* get the graphics to the display panel*/
Graphics gfx = getAnimationArea();
/* get the id of the disk to be moved */
int disk = getDiskId(src);
/* get the to and from rows */
int sourceRow = getRow(src);
int destinationRow = getRow(dest);
/* set the co ordintates of the destination */
int col = dest * POLE_AREA_WIDTH;
int x = disks[disk].getStartX() + col;
int y = startY - (destinationRow * CELL_HEIGHT);
int width = disks[disk].getDiskWidth();
disks[disk].setStartX(x);
disks[disk].setStartY(y);
disks[disk].setDiskWidth(width);
//System.out.println("startX " + x);
//System.out.println("startY " + y);
//System.out.println("destination row " + destinationRow);
//System.out.println("disk " + disk);
//System.out.println("Width " + width);
diskCells[sourceRow - 1][src] = EMPTY_CELL_VALUE;
/* set the destination row to the disk id */
diskCells[destinationRow][dest] = disk;
drawDisk();
repaint();
public void drawDisk(){
int diskNum = setDiskAmount -1;
int i = 0;
Graphics gfx = getAnimationArea();
gfx.setColor(Color.MAGENTA);
while(diskNum >= 0){
//System.out.println("here is the disk IDs " + diskNum);
//System.out.println("the startY during draw " + disks[diskNum].getStartY());
gfx.fillRoundRect(disks[diskNum].getStartX(), disks[diskNum].getStartY(), disks[diskNum].getDiskWidth(), DISK_HEIGHT, DISK_ARC_WIDTH, DISK_ARC_HEIGHT);
diskNum--;
public void paint(Graphics gfx){
if(windowState == 0){
super.paint(gfx);
setup();
} else if (windowState == 1){
super.paint(gfx);
drawDisk();
*returns the id of the disk
*@param col the the designated column
*@return the disk identification number
public static int getDiskId(int col){
int diskIdent = 0;
/* initialize the row number to max -1, because the array start at 0 */
int row = MAX_DISKS - 1;
/* do a cell check while row is greater than 0
*this is done so that is starts at the top row
*and moves down
while (row > EMPTY_CELL_VALUE){
/* when the first cell that is not -1 is reached get the disk number
*that disk will be the smallest in the stack */
if(diskCells[row][col] != -1){
//diskIdent = this.diskCells[row][col];
diskIdent =diskCells[row][col];
break;
row--;
return diskIdent;
*returns the first available row
*@param col the designated col
*@return the first available row number
public static int getRow(int col){
int rowNumber = 0;
/* cycle through the cells until it finds an empty one */
while (diskCells[rowNumber][col] != -1){
rowNumber++;
return rowNumber;
*calculate the total time it takes for the tower of hanoi game to be
*solved, given the amount of disk and the amount of time it takes
*to physically move a disk from one pole to the other.
public static void totalTime(){
int timeInSeconds = setPhysicalDelay * intMovesLeft;
int i = 0;
int seconds = 0;
int minute = 0;
int hour = 0;
int day = 0;
int month = 0;
int year = 0;
while (i < timeInSeconds){
if(seconds > 60){
minute++;
seconds = 0;
if(minute > 60){
hour++;
minute = 0;
if(hour > 24){
day++;
hour = 0;
if(day > 30){
month++;
day = 0;
if(month > 12){
year++;
month = 0;
seconds++;
i++;
updateMessageCenter("It would take:" + year + " years " + month + " months " + day +
" days " + hour + " hours " + minute + " minutes and " + seconds + " seconds, to move " + setDiskAmount +
" disks at " + setPhysicalDelay + " seconds per move");
Sorry if my post was a little too cryptic...
"How do you know? You have a problem you can't solve. Anything could be your issue." Agreed. However, using the process of elimination and debug statments I have been able to narrow the scope of the issue.
"If you can't solve it by executing the code and adding debug statements how to you expect us to help."If I could solve but "executing code and adding debug statements" there would be no need to post the problem here.
"We don't know exactly what you are attempting to do."Trying to paint my graphics to a JPanel based on a set of co ordinates.
"We don't know why you are passing the Graphics object around."Why not? is it impossible to do it this way?
"The big problem is in the alogorithm you use to determine the location of each component."Who said you couldn't read minds?
"If you are using some kind of animation then I would use a Timer to schedule the moving of components. I don't even see how you are doing this in your code."Sorry I guess stating that I didn't post my entire code may have threw things off...I do use a timer in a seperate class. I will include it in the next post.
"I can't tell if you are using Threads of not."guess you overlooked these lines of code:
/* create and start a new thread. This is EXTREMELY important
*as it allows for GUI to be repainted while the soulution
*is animated */
SolveEngine s = new SolveEngine();
s.start(); Here is the code once again:
public class HanoiFrame extends javax.swing.JFrame {
private static final int STATE_SETUP = 0;
private static final int STATE_ANIMATE = 1;
private static final int POLE_AREA_HEIGHT = 356;
private static final int POLE_AREA_WIDTH = 205;
private static final int DISK_ARC_HEIGHT = 15;
private static final int DISK_ARC_WIDTH = 15;
private static final int DISK_HEIGHT = 23;
private static final int MAX_DISKS = 10;
private static final int MAX_ANIMATION_DELAY = 30000;
private static final int MAX_PHYSICAL_DELAY = 100000;
private static final int MIN_DISKS = 1;
private static final int MIN_ANIMATION_DELAY = 1;
private static final int MIN_PHYSICAL_DELAY = 1;
private static final int EMPTY_CELL_VALUE = -1;
private static final int CELL_HEIGHT = 25;
private static final int COLUMNS = 3;
private static final int ROW = 11;
private static final int MILLISECONDS_PER_SECOND = 1000;
private final static String newline = "\n";
private static Disk[] disks;
private static Disk newDisk;
private static int[][] diskCells;
public static int startX = 2;
public static int startY = 340;
public static int setDiskAmount = 0;
public static int setAnimationDelay = 0;
public static int setPhysicalDelay = 0;
public static int moveNumber = 0;
public static int intMovesLeft = 0;
private boolean buttonPressed = false;
private double movesLeft = 0;
private int windowState = 0;
/** Creates new form HanoiFrame */
public HanoiFrame() {
initComponents();
/* initialize the "poles" to hold a certain number of "cells */
this.diskCells = new int[ROW][COLUMNS];
for (int row = ROW - 1;row >= 0; row--) {
for (int col = 0;col < COLUMNS ; col++) {
diskCells[row][col] = EMPTY_CELL_VALUE;
private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {
/* reset all the variable to original state */
setDiskAmount = 0;
setAnimationDelay = 0;
setPhysicalDelay = 0;
moveNumber = 0;
movesLeft = 0;
intMovesLeft = 0;
buttonPressed = false;
windowState = 0;
this.startButton.setEnabled(true);
this.diskAmount.setEditable(true);
this.animationDelay.setEditable(true);
this.physicalDelay.setEditable(true);
/* reset all the cell vales to empty (this could be its own function) */
for (int row = ROW - 1;row >= 0; row--) {
for (int col = 0;col < COLUMNS ; col++) {
diskCells[row][col] = EMPTY_CELL_VALUE;
/* reset the content of the TextFields and Area */
this.diskAmount.setText("");
this.animationDelay.setText("");
this.physicalDelay.setText("");
this.outTextArea.setText("");
/* repaint the display panel */
this.hanoiPanel.repaint();
/* i have no idea why this is here...It was generated by Netbeans when I
*made the reset button. As you can see it made 2. The one above it the same
*except it contains code. Since it was automatically generated
*I cannot delete it.
private void resetButtonMouseReleased(java.awt.event.MouseEvent evt) {
/* is executed when the start button is pressed.
*also executes a field check and intializes key variables. Finally,
*it executes the solution and generates the solve time
private void startButtonMouseReleased(java.awt.event.MouseEvent evt) {
/* check if the program has already been run (without being reset) */
if (!buttonPressed){
/* check the fields to ensure the input is correct and useable */
if (checkFields()){
/* give button a pressed status if all info valid */
buttonPressed = true;
windowState = 1;
/* disable the button */
this.startButton.setEnabled(false);
/* disable the fields */
this.diskAmount.setEditable(false);
this.animationDelay.setEditable(false);
this.physicalDelay.setEditable(false);
/* setup the disks on the starting pole */
setup();
/* initialize the number of moves required. 2 to the power of n minus 1 */
movesLeft = Math.pow(2, setDiskAmount) - 1;
/* convert the number to an integer */
intMovesLeft = (int)movesLeft;
/* set the physical delay */
setPhysicalDelay = Integer.parseInt(this.physicalDelay.getText());
/* create and start a new thread. This is EXTREMELY important
*as it allows for GUI to be repainted while the soulution
*is animated */
SolveEngine s = new SolveEngine();
s.start();
*Check all the fields at once to ensure that they are valid
private boolean checkFields(){
String numberOfDisks = null;
String animationDelay = null;
String physicalDelay = null;
numberOfDisks = this.diskAmount.getText();
animationDelay = this.animationDelay.getText();
physicalDelay = this.physicalDelay.getText();
/* initiate my array of error messages */
ArrayList errMsg = new ArrayList(0);
/* check if the number of disks was left blank */
if (numberOfDisks.equals("")){
errMsg.add("Please enter the Number of Disks (MAX " + MAX_DISKS + ")");
}else{
/* check if the input given is valid */
try {
/* parse the disk amount entered into an integer */
setDiskAmount = Integer.parseInt(numberOfDisks);
/* check the # of disks entered is greater than 0 and less than 10 */
if (setDiskAmount < MIN_DISKS){
errMsg.add("Number of Disks must be greater than " + MIN_DISKS);
} else if (setDiskAmount > MAX_DISKS){
errMsg.add("Number of Disks must be less than" + MAX_DISKS);
} catch (NumberFormatException ex) {
errMsg.add("Number of Disks must be a Number");
/* check if animation delay was left blank */
if (animationDelay.equals("")){
errMsg.add("Please enter disk Animation Delay");
} else {
/* check if the input given is valid */
try {
/* parse the animation delay entered into an integer */
setAnimationDelay = Integer.parseInt(animationDelay);
/* check range of animation delay */
if (setAnimationDelay < MIN_ANIMATION_DELAY){
errMsg.add("Animation Delay must be greater than 0");
} else if (setAnimationDelay > MAX_ANIMATION_DELAY){
errMsg.add("Animation Delay must be less than " + MAX_ANIMATION_DELAY);
} catch (NumberFormatException ex) {
errMsg.add("Animation Delay must be a Number");
/* check if physical delay was left blank */
if (physicalDelay.equals("")){
errMsg.add("Please enter the Physical disk delay");
} else {
/* check if the input given is valid */
try {
/* parse the physical delay entered into an integer */
setPhysicalDelay = Integer.parseInt(physicalDelay);
/* check check the range of the physical delay */
if (setPhysicalDelay < MIN_PHYSICAL_DELAY){
errMsg.add("Physical Delay must be greater than 0");
} else if (setPhysicalDelay > MAX_PHYSICAL_DELAY){
errMsg.add("Physical Delay must be less than " + MAX_PHYSICAL_DELAY);
} catch (NumberFormatException ex) {
errMsg.add("Physical Delay must be a Number");
/* if there is any problem, add the message to the popup and display */
if (!errMsg.isEmpty()){
JOptionPane.showMessageDialog(this, errMsg.toArray());
return false;
return true;
* @param args the command line arguments
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new HanoiFrame().setVisible(true);
/*returns the Animation panel area graphics
*@return Animation area graphics
public static Graphics getAnimationArea(){
/* get the usable area of poleA */
Container clientArea = hanoiPanel;
//Container clientArea = this.getContentPane();
/* get the graphics to the display panel*/
Graphics gfx = clientArea.getGraphics();
return gfx;
*set up the requested amount of disks on the first pole
*@param diskAmount the amount of disks entered by the user
public void setup(){
int numberOfDisks = setDiskAmount;
this.disks = new Disk[numberOfDisks];
int diskNumber = 0;
int diskWidth = POLE_AREA_WIDTH - 4;
int arcH = DISK_ARC_HEIGHT;
int arcW = DISK_ARC_WIDTH;
int x = startX;
int y = startY;
int row = 0;
int col = 0;
/* get the graphics to the display panel*/
//Graphics gfx = getAnimationArea();
/* set the color of the disks */
//gfx.setColor(Color.MAGENTA);
/* draw the specified number of disks */
while (diskNumber < numberOfDisks){
/* reduce the y position */
y = startY - diskNumber * CELL_HEIGHT;
/* draw the disk */
//gfx.fillRoundRect(x, y, diskWidth, DISK_HEIGHT, arcH, arcW);
/* create a new instance of disk */
newDisk = new Disk(x, y, diskWidth);
/* give the new disk an id */
this.disks[diskNumber] = newDisk;
/* add the id to the cell array of poleA */
this.diskCells[row][col] = diskNumber;
/* make the disk smaller and center */
x = x + 8;
diskWidth = diskWidth - 16;
/* increase disk number */
diskNumber++;
/* move to the next row */
row++;
repaint();
*move the disk from a source pole to the destination pole.
*this should take the source col and destination col to determine where to draw the
*disk. It will also need to know to draw the disk in the first available cell
*in a col
*@param source the starting pole of the next move
*@param destination the end pole of the next move
public void moveDisk(int src, int dest){
/* the lines below would not be necessary if I were to pass the Graphics
*gfx object as a parameter. I may have to use this option in order
*to work around the current repainting issue */
/* get the graphics to the display panel*/
Graphics gfx = getAnimationArea();
/* get the id of the disk to be moved */
int disk = getDiskId(src);
/* get the to and from rows */
int sourceRow = getRow(src);
int destinationRow = getRow(dest);
/* set the co ordintates of the destination */
int col = dest * POLE_AREA_WIDTH;
int x = disks[disk].getStartX() + col;
int y = startY - (destinationRow * CELL_HEIGHT);
int width = disks[disk].getDiskWidth();
disks[disk].setStartX(x);
disks[disk].setStartY(y);
disks[disk].setDiskWidth(width);
//System.out.println("startX " + x);
//System.out.println("startY " + y);
//System.out.println("destination row " + destinationRow);
//System.out.println("disk " + disk);
//System.out.println("Width " + width);
diskCells[sourceRow - 1][src] = EMPTY_CELL_VALUE;
/* set the destination row to the disk id */
diskCells[destinationRow][dest] = disk;
drawDisk();
repaint();
String output = "";
//must initialize row to max - 1 and increment 'til = 0
//since the array position starts at 0
//this will print the array from the top down
for (int row = ROW - 1;row >= 0; row--) {
for (int colm = 0;colm < COLUMNS ; colm++) {
output = output + diskCells[row][colm];
output = output + "\n";
System.out.println(output);
System.out.println(newline);
public void drawDisk(){
int diskNum = setDiskAmount -1;
int i = 0;
Graphics gfx = getAnimationArea();
gfx.setColor(Color.MAGENTA);
while(diskNum >= 0){
//System.out.println("here is the disk IDs " + diskNum);
//System.out.println("the startY during draw " + disks[diskNum].getStartY());
gfx.fillRoundRect(disks[diskNum].getStartX(), disks[diskNum].getStartY(), disks[diskNum].getDiskWidth(), DISK_HEIGHT, DISK_ARC_WIDTH, DISK_ARC_HEIGHT);
diskNum--;
public void paint(Graphics gfx){
if(windowState == 0){
super.paint(gfx);
setup();
} else if (windowState == 1){
super.paint(gfx);
drawDisk();
*returns the id of the disk
*@param col the the designated column
*@return the disk identification number
public static int getDiskId(int col){
int diskIdent = 0;
/* initialize the row number to max -1, because the array start at 0 */
int row = MAX_DISKS - 1;
/* do a cell check while row is greater than 0
*this is done so that is starts at the top row
*and moves down
while (row > EMPTY_CELL_VALUE){
/* when the first cell that is not -1 is reached get the disk number
*that disk will be the smallest in the stack */
if(diskCells[row][col] != -1){
//diskIdent = this.diskCells[row][col];
diskIdent =diskCells[row][col];
break;
row--;
return diskIdent;
*returns the first available row
*@param col the designated col
*@return the first available row number
public static int getRow(int col){
int rowNumber = 0;
/* cycle through the cells until it finds an empty one */
while (diskCells[rowNumber][col] != -1){
rowNumber++;
return rowNumber;
*calculate the total time it takes for the tower of hanoi game to be
*solved, given the amount of disk and the amount of time it takes
*to physically move a disk from one pole to the other.
public static void totalTime(){
int timeInSeconds = setPhysicalDelay * intMovesLeft;
int i = 0;
int seconds = 0;
int minute = 0;
int hour = 0;
int day = 0;
int month = 0;
int year = 0;
while (i < timeInSeconds){
if(seconds > 60){
minute++;
seconds = 0;
if(minute > 60){
hour++;
minute = 0;
if(hour > 24){
day++;
hour = 0;
if(day > 30){
month++;
day = 0;
if(month > 12){
year++;
month = 0;
seconds++;
i++;
updateMessageCenter("It would take:" + year + " years " + month + " months " + day +
" days " + hour + " hours " + minute + " minutes and " + seconds + " seconds, to move " + setDiskAmount +
" disks at " + setPhysicalDelay + " seconds per move");
*add the message to the diplay window
*currently this is not necessary, but may be required to
*dynamically display the contents of message into the text area
*@param message the message to be added/appended the the text area
public static void updateMessageCenter(String message){
/* append text to the message */
outTextArea.append(message + newline);
/* ensure the the most recent line is viewable - auto scroll */
outTextArea.setCaretPosition(outTextArea.getDocument().getLength());
public class SolveEngine extends Thread {
/** Creates a new instance of SolveEngine */
public SolveEngine() {
public void run(){
/* start the engine/animation */
solutionEngine(HanoiFrame.setDiskAmount,0, 2, 1);
/* calculate and print the total time after the solution is complete */
HanoiFrame.totalTime();
*the recursive solution to the Towers of Hanoi problem
*@param diskAmount the number of disks that need to be moved
*@param start the identity of the starting column
*@param end the identity of the ending column
*@param temp the identity of the temporary column
public void solutionEngine(int diskAmount,int start, int end, int temp){
int disks = diskAmount;
int startPole = start;
int endPole = end;
int tempPole = temp;
try {
if ( disks == 1 ) {
HanoiFrame.moveNumber++;
HanoiFrame.updateMessageCenter("Moving disk from "+ startPole + " to "+ endPole + " Move #: " + HanoiFrame.moveNumber + " of " + HanoiFrame.intMovesLeft);
/* delay the movement of the disk */
Thread.sleep(HanoiFrame.setAnimationDelay);
/* move the disk */
moveDisk(startPole, endPole);
} else {
solutionEngine( disks - 1, startPole, tempPole, endPole);
HanoiFrame.moveNumber++;
HanoiFrame.updateMessageCenter("Moving disk from "+ startPole + " to "+ endPole + " Move #: " + HanoiFrame.moveNumber + " of " + HanoiFrame.intMovesLeft);
/* delay the movement of the disk */
Thread.sleep(HanoiFrame.setAnimationDelay);
moveDisk(startPole, endPole);
solutionEngine( disks - 1, tempPole, endPole, startPole);
} catch (InterruptedException ex) {
ex.printStackTrace();
} -
Compare a String Array to get Higher value
Hi, I'm trying to figure out how can I create a method in which I can compare my array of String by getting the higher value. For example I have an array called faces[]. What I would like to say is that if 2 is less than 5, and so forth print "blahhhh". I would appreciate some ideas on which is the best way to do this. Thanks a lot. Here is the code so far. I'm working on checkWinner() method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WarCard extends JFrame implements ActionListener {
private Card deck[];
private int currentCard, value, winner;
private JPanel buttonPanel, labelPanel, textFieldPanel;
private JButton buttons[];
private JLabel labels[];
private JTextField textFields[];
public WarCard()
super( "War! " );
String faces[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" };
deck = new Card[ 52 ];
currentCard = -1;
//populate deck
for ( int count = 0 ; count < deck.length; count++ )
deck[ count ] = new Card( faces[ count % 13], suits[ count / 13 ] );
// get content pane and create layout
Container container = getContentPane();
// create label grid
labels = new JLabel[3];
labels[ 0 ] = new JLabel( "Player 1: ");
labels[ 1 ] = new JLabel( "Player 2: ");
labels[ 2 ] = new JLabel( "Shuffle cards to begin" );
labelPanel = new JPanel();
labelPanel.setLayout( new GridLayout( 3, labels.length ) );
for ( int count = 0; count < labels.length; count++) {
labelPanel.add( labels[ count ] );
}// end for loop
container.add( labelPanel, BorderLayout.WEST );
// create text field grid
textFields = new JTextField[ 3 ];
textFields[ 0 ] = new JTextField( 20 );
textFields[ 1 ] = new JTextField( 20 );
textFields[ 2 ] = new JTextField( 20 );
textFieldPanel = new JPanel();
textFieldPanel.setLayout( new GridLayout( 3, textFields.length ) );
for ( int count = 0; count < textFields.length; count++) {
textFields[ count ].setEditable( false );
textFieldPanel.add( textFields[ count ] );
}// end for loop
container.add( textFieldPanel, BorderLayout.EAST );
// create button grid
buttons = new JButton[ 3 ];
buttons[ 0 ] = new JButton( "Deal" );
buttons[ 1 ] = new JButton( "Shuffle" );
buttons[ 2 ] = new JButton( "Exit" );
buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout( 1, buttons.length ) );
for ( int count = 0; count < buttons.length; count++) {
buttons[ count ].addActionListener( this );
buttons[ 0 ].setEnabled( false );
buttonPanel.add( buttons[ count ] );
}// end for loop
container.add( buttonPanel, BorderLayout.SOUTH );
setSize( 425, 150 );
setVisible( true );
private void checkWinner()
int i = 0;
for( i=0; i < 13; i++ ){
if ( s[ 0 ].equals("2 of Spades") & s[ 1 ]!="2 of Spades" ){
txtGame[ 2 ].setText( " You Win " );
else{
txtGame[ 2 ].setText( " Compuer Win" );
public static void main( String agrs[] )
WarCard application = new WarCard();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
public void actionPerformed( ActionEvent event)
String testString = "";
for ( int count = 0; count < buttons.length; count++) {
if ( event.getSource() == buttons[ 0 ] ) {
Card dealt1 = dealPlayer1();
Card dealt2 = dealPlayer1();
if ( dealt1 != null || dealt2 != null ) {
textFields[ 0 ].setText( dealt1.toString() );
textFields[ 1 ].setText( dealt2.toString() );
labels[ 2 ].setText( "# of Cards : " + currentCard);
else {
textFields[ 2 ].setText( "All Cards Dealt" );
labels[ 2 ].setText( "Shuffle Cards to continue" );
else if ( event.getSource() == buttons[ 1 ] ) {
shuffle();
textFields[ 0 ].setText( " " );
textFields[ 1 ].setText( " " );
labels[ 2 ].setText( "Shuffled!");
else if ( event.getSource() == buttons[ 2 ] ) {
System.exit( 0 );
}// end for loop
}// end method actionPerformed
private void shuffle()
currentCard = -1;
for ( int first = 0; first < deck.length; first++ ) {
int second = ( int ) ( Math.random() * 52 );
Card temp = deck[ first ];
deck[ first ] = deck[ second ];
deck[ second ]= temp;
buttons[ 0 ].setEnabled( true );
private Card dealPlayer1()
if ( ++currentCard < deck.length )
return deck[ currentCard ];
else {
buttons[ 0 ].setEnabled( false );
return null;
}// end of WarCard
class Card{
private String face;
private String suit;
public Card( String cardFace, String cardSuit )
face = cardFace;
suit = cardSuit;
public String toString()
return face + " of " + suit;
}// end toString
}// end class WarCardassign an int value to the card and use < == >
-
Help with adding a JPanel with multiple images to a JFrame
I'm trying to make a program that reads a "maze" and displays a series of graphics depending on the character readed. The input is made from a file and the output must be placed in a JFrame from another class, but i can't get anything displayed. I have tried a lot of things, and i am a bit lost now, so i would thank any help. The input is something like this:
20
SXXXXXXXXXXXXXXXXXXX
XXXX XXXXXXXXXXX
X XXXXX
X X XX XXXXXXXXXXXX
X XXXXXXXXX XXX
X X XXXXXXXXX XXXXX
X XXXXX XXXXX XXXXX
XX XXXXX XX XXXX
XX XXXXX XXXXXXXX
XX XX XXXX XXXXXXXX
XX XX XXXXXXXX
XX XXX XXXXXXXXXXXXX
X XXXXXXXXXXXXX
XX XXXXXXX !
XX XXXXXX XXXXXXXXX
XX XXXXXXX XXXXXXXXX
XX XXXXXXXX
XX XXXX XXXXXXXXXXXX
XX XXXX XXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
Generated by the Random Maze Generator
And the code for the "translator" is this:
package project;
import java.io.*;
import java.awt.*;
import javax.swing.*;
public class Translator extends JFrame {
private FileReader Reader;
private int size;
Image wall,blank,exit,start,step1,step2;
public Translator(){}
public Translator(File F){
try {
Reader=new FileReader(F);}
catch (IOException e){
JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
try {
size=Reader.read();
System.out.write(size);}
catch (IOException e){
JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
Toolkit theKit=Toolkit.getDefaultToolkit();
wall=theKit.getImage("wall.gif");
blank=theKit.getImage("blanktile.jpg");
exit=theKit.getImage("exit.jpg");
start=theKit.getImage("start.jpg");
step1=theKit.getImage("start.jpg");
step2=theKit.getImage("step1.jpg");
JPanel panel=new JPanel(){
public void paintComponent(Graphics g) {
super.paintComponents(g);
int ch=0;
System.out.print("a1 ");
int currentx=0;
int currenty=0;
try {ch=Reader.read();
System.out.write(ch);}
catch (IOException e){}
System.out.print("b1 ");
while(ch!=-1){
try {ch=Reader.read();}
catch (IOException e){}
System.out.write(ch);
switch (ch){
case '\n':{currenty++;
break;}
case 'X':{System.out.print(">x<");
g.drawImage(wall,(currentx++)*20,currenty*20,this);
break;}
case ' ':{
g.drawImage(blank,(currentx++)*20,currenty*20,this);
break;}
case '!':{
g.drawImage(exit,(currentx++)*20,currenty*20,this);
break;}
case 'S':{
g.drawImage(start,(currentx++)*20,currenty*20,this);
break;}
case '-':{
g.drawImage(step1,(currentx++)*20,currenty*20,this);
break;}
case 'o':{
g.drawImage(step2,(currentx++)*20,currenty*20,this);
break;}
case 'G':{ch=-1;
break;}
}//Swith
}//While
}//paintComponent
};//Panel
panel.setOpaque(true);
setContentPane(panel);
}//Constructor
}//Classforget all those systems.out and that stuff, that is just for the testing
i call it in another class in this way:
public Maze(){
firstFrame=new JFrame("Random Maze Generator");
firstFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
(...)//more constructor code here
Translator T=new Translator(savefile);
firstFrame.add(T);
firstFrame.getContentPane().add(c);
firstFrame.setBounds(d.width/3,d.height/3,d.width/2,d.height/4);
firstFrame.setVisible(true);
c.setSize(d.width/2,d.height/4);
c.show();
}i know it may be a very basic or concept problem, but i can't get it solved
thanks for any helpTry this. It's trivial to convert it to use your images.
If you insist on storing the maze in a file, just read one line at a
time into an ArrayList than convert to an array and pass that to the
MazePanel constructor.
Any questions, just ask.
import java.awt.*;
import javax.swing.*;
public class CFreman1
static class MazePanel
extends JPanel
private final static int DIM= 20;
private String[] mMaze;
public MazePanel(String[] maze) { mMaze= maze; }
public Dimension getPreferredSize() {
return new Dimension(mMaze[0].length()*DIM, mMaze.length*DIM);
public void paint(Graphics g)
g.setColor(Color.BLACK);
g.fillRect(0, 0, getSize().width, getSize().height);
for (int y= 0; y< mMaze.length; y++) {
String row= mMaze[y];
for (int x= 0; x< row.length(); x++) {
Color color= null;
switch (row.charAt(x)) {
case 'S':
color= Color.YELLOW;
break;
case 'X':
color= Color.BLUE;
break;
case '!':
color= Color.RED;
break;
if (color != null) {
g.setColor(color);
g.fillOval(x*DIM, y*DIM, DIM, DIM);
public static void main(String[] argv)
String[] maze= {
"SXXXXXXXXXXXXXXXXXXX",
" XXXX XXXXXXXXXXX",
"X XXXXX",
"X X XX XXXXXXXXXXXX",
"X XXXXXXXXX XXX",
"X X XXXXXXXXX XXXXX",
"X XXXXX XXXXX XXXXX",
"XX XXXXX XX XXXX",
"XX XXXXX XXXXXXXX",
"XX XX XXXX XXXXXXXX",
"XX XX XXXXXXXX",
"XX XXX XXXXXXXXXXXXX",
"X XXXXXXXXXXXXX",
"XX XXXXXXX !",
"XX XXXXXX XXXXXXXXX",
"XX XXXXXXX XXXXXXXXX",
"XX XXXXXXXX",
"XX XXXX XXXXXXXXXXXX",
"XX XXXX XXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXX"
JFrame frame= new JFrame("CFreman1");
frame.getContentPane().add(new MazePanel(maze));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
} -
Calling an array from another class
Ok I have this little program that I created to display values stored in an array. Well, I want my array to automatically be populated with the same values that are in another array that resides in a different class. Here is my code for the class that I want the values to be displayed:
import javax.swing.*;
import java.awt.*;
public class GUIRead extends JFrame
double[] interest = new double[3];
MemicCSVReader[] interestObjectArray = new MemicCSVReader[3];
interestObjectArray[0] = new MemicCSVReader();
interestObjectArray[1] = new MemicCSVReader();
interestObjectArray[2] = new MemicCSVReader():
for(int x = 0; x < 3; x++)
JPanel display = new JPanel();
JTextField interestText = new JTextField(10);
JPanel display2 = new JPanel();
JTextField interestText2 = new JTextField(10);
JPanel display3 = new JPanel();
JTextField interestText3 = new JTextField(10);
public GUIRead()
super("Test");
setSize(160,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
GridLayout config = new GridLayout(3,1);
FlowLayout config2 = new FlowLayout(FlowLayout.LEFT,10,10);
Container pane = getContentPane();
pane.setLayout(config2);
display.setLayout(config2);
display.add(interestText);
interestText.setText(interest[0]);
interestText.setEditable(false);
pane.add(display);
display2.setLayout(config2);
display2.add(interestText2);
interestText2.setText(interest[1]);
interestText2.setEditable(false);
pane.add(display2);
display3.setLayout(config2);
display3.add(interestText3);
interestText3.setText(interest[2]);
interestText3.setEditable(false);
pane.add(display3);
setContentPane(pane);
public static void main(String[] args)
GUIRead run = new GUIRead();
Here is my code that I want the double[] interest array to pull it's data from:
public class MemicCSVReader
double interestArray[];
MemicCSVReader()
String[] interestString = {"5.5","5.35","5.75"};
for(int x = 0; x < 3; x++)
interestArray[x] = Double.parseDouble(interestString[x]);
}Ok, thanks for your help. Now I have another problem. I can't get the values to display. Here is my code:
This is the program that runs the application:
import javax.swing.*;
import java.awt.*;
public class GUIRead extends JFrame
MemicCSVReader readCSV = new MemicCSVReader();
double[] interestDouble = readCSV.getInterestArray();
String[] interest;
JPanel display = new JPanel();
JTextField interestText = new JTextField(10);
JPanel display2 = new JPanel();
JTextField interestText2 = new JTextField(10);
JPanel display3 = new JPanel();
JTextField interestText3 = new JTextField(10);
public GUIRead()
super("Test");
setSize(160,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
GridLayout config = new GridLayout(3,1);
FlowLayout config2 = new FlowLayout(FlowLayout.LEFT,10,10);
Container pane = getContentPane();
pane.setLayout(config2);
display.setLayout(config2);
display.add(interestText);
interestText.setEditable(false);
pane.add(display);
display2.setLayout(config2);
display2.add(interestText2);
interestText2.setEditable(false);
pane.add(display2);
display3.setLayout(config2);
display3.add(interestText3);
interestText3.setEditable(false);
pane.add(display3);
setContentPane(pane);
public void actionPerformed()
for(int x = 0; x < 3; x++)
interest[x] = Double.toString(interestDouble[x]);
interestText.setText(interest[0]);
interestText2.setText(interest[1]);
interestText3.setText(interest[2]);
public static void main(String[] args)
GUIRead run = new GUIRead();
This is the file that it pulls the array from:
public class MemicCSVReader
private double[] InterestArray = new double[3];
MemicCSVReader()
double[] InterestArray = {5.5,5.35,5.75};
public double[] getInterestArray()
return InterestArray;
} -
Help needed in refreshing a panel in a JFrame.
I have some problem in refreshing a panel of a window.
Here I am writting the sample code bellow.
My program contains 2 classes, one is "Test" other is "Testwindow".
class Test contains main(),displays the buttons reading from the string array obtained by listing a directory in my local file system through the panel p2 .If I click "Add" button in Test, class Testwindow's constructor is called & "Testwindow" is visible, which has a textfield. If you enter a string in the textfield, that string will be stored as a file in the same directory that the 1st window use. here I choose "C:\\temp" of my filesystem as the directory.
My requirement is:
when I enter a string in the textfield of Testwindow, then after clicking "Finish" button, that inputted string should be added to the panel p2 of 1st window(Test)during runtime.It means the panel p2 should be refreshed reading from the "C:\\temp" as soon as a new button is added to temp directory during runtime.
If any of you have idea over this,please help sending me the updated version of the code given below.
Regards.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class Test extends JFrame
JPanel p1,p2;
JButton b1,bdir[];
File f;
String s[];
int n,nmax;
public Test()
super("Test");
JPanel con=(JPanel)getContentPane();
con.setLayout(new BorderLayout());
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
System.exit(0);
p1=new JPanel();
p2=new JPanel();
p2.setLayout(new GridLayout(nmax,1));
b1=new JButton("Add");
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
if(e.getActionCommand()=="Add")
new Testwindow();
p1.add(b1);
f=new File("c:\\temp");
s=f.list();
n=s.length;
nmax=n+20;
bdir=new JButton[n];
for(int i=0; i<n; i++)
bdir=new JButton(s);
bdir.setHorizontalAlignment(AbstractButton.LEADING);
p2.add(bdir);
int hor=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int ver=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(p2,hor,ver);
con.add(p1,"North");
con.add(jsp,"Center");
setSize(250,300);
public static void main(String arg[])
Test frame=new Test();
frame.setVisible(true);
class Testwindow extends JFrame implements ActionListener
JPanel p1,p2,p3;
JLabel l1;
JTextField tf1;
JButton b1,b2;
String s1, sdir[];
public Testwindow()
setTitle("Testwindow");
Container con=getContentPane();
con.setLayout(new BorderLayout());
p1=new JPanel();
p1.setLayout(new GridLayout(1,2));
p2=new JPanel();
l1=new JLabel("Enter a string: ");
tf1=new JTextField();
b1=new JButton("Finish");
b1.addActionListener(this);
p1.add(l1);
p1.add(tf1);
p2.add(b1);
con.add(p1,"North");
con.add(p2, "South");
setSize(300,150);
show();
public void actionPerformed(ActionEvent e)
if(e.getActionCommand()=="Finish"){
try{
s1=tf1.getText();
File id_name=new File("C:\\temp\\"+s1+".txt");
FileOutputStream out=new FileOutputStream(id_name);
out.close();
catch(IOException x)
System.out.println("Exception caught"+x);
this.setVisible(false);import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class test extends JFrame {
JPanel p1, p2;
JButton b1, bdir[];
File f;
String[] s;
int n, nmax;
public test() {
super("Test");
p1 = new JPanel();
p2 = new JPanel();
p2.setLayout(new GridLayout(nmax ,1));
b1 = new JButton("Add");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Testwindow(test.this);
p1.add(b1);
f = new File("c:\\temp");
s = f.list();
n = s.length;
nmax = n + 20;
bdir = new JButton[n];
for(int j = 0; j < n; j++) {
bdir[j] = new JButton(s[j]);
bdir[j].setHorizontalAlignment(AbstractButton.LEADING);
p2.add(bdir[j]);
JScrollPane jsp = new JScrollPane(p2);
getContentPane().add(p1, "North");
getContentPane().add(jsp, "Center");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(250,300);
setLocation(100,100);
setVisible(true);
* Called by actionPerformed method in Testwindow
public void addButton(String title) {
JButton button = new JButton(title);
button.setHorizontalAlignment(AbstractButton.LEADING);
p2.add(button);
p2.revalidate();
public static void main(String[] args) {
new test();
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
class Testwindow extends JFrame implements ActionListener {
JPanel p1,p2,p3;
JLabel label1;
JTextField tf1;
JButton b1,b2;
String s1, sdir[];
test client;
public Testwindow(test client) {
setTitle("Testwindow");
this.client = client;
p1=new JPanel();
p1.setLayout(new GridLayout(1,2));
p2=new JPanel();
label1=new JLabel("Enter a string: ");
tf1=new JTextField();
b1=new JButton("Finish");
b1.addActionListener(this);
p1.add(label1);
p1.add(tf1);
p2.add(b1);
getContentPane().add(p1, "North");
getContentPane().add(p2, "South");
setSize(300,150);
setLocation(360,100);
setVisible(true);
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource();
if(button == b1) {
try {
s1=tf1.getText();
File id_name=new File("C:\\temp\\"+s1+".txt");
FileOutputStream out=new FileOutputStream(id_name);
out.close();
catch(IOException x) {
System.out.println("Exception caught"+x);
s1 = tf1.getText();
client.addButton(s1);
this.setVisible(false);
} -
How do you make an array of image icons and then call them?
How do you make an array of image icons and then call them, i have searched all over the internet for making an array of icons, but i have
found nothing. Below is my attempt at making an array of icons, but i cant seem to make it work. Basically, i want the image to match the value of the roll of the dice (rollVal)
Any help would be greatly appreciated, some code or link to tuturial, ect.
/** DiceRoller.java
* Roll, print, Gui
import javax.swing.*;
public class DiceRoller extends JFrame
private ImageIcon[] image ;
public String[] images = { "empty", "dice1.jpg",
"dice2.jpg", "dice3.jpg", "dice4.jpg",
"dice5.jpg", "dice6.jpg" };
public Dice die;
private int rollVal;
public int rollNum;
private JLabel j1;
public DiceRoller(){
j1= new JLabel("");
die =new Dice();
int rollVal;
rollVal = die.roll();
image = new ImageIcon[images.length];
for(int i = 0; i < images.length; i++){
image[i] = new ImageIcon(images);
if (image!=null){
j1.setIcon(image[rollVal]);
System.out.println("Roll = "+die.roll());Demo:
import java.awt.*;
import java.net.*;
import javax.swing.*;
public class IconExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run() {
launch();
static void launch() {
try {
Icon[] icons = new Icon[6];
for(int i=0; i<icons.length; ++i) {
String url = "http://www.eureka-puzzle.be/cast/images/dice" + (i + 1) + ".jpg";
icons[i] = new ImageIcon(new URL(url));
display(icons);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
static void display(Icon[] icons) {
JPanel cp = new JPanel();
for(Icon icon : icons) {
cp.add(new JLabel(icon));
JFrame f = new JFrame();
f.setContentPane(cp);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
Maybe you are looking for
-
i use an usb yamaha audiogram6 interface on my MacBook Pro it works good, but i have the problem that if i plugged my guitar it sound everytime and i keep listen it even if im using guitar amps on logic pro i listen the clean sound from the guitar an
-
'SUBSTRING_INDEX' is not a recognized built-in function name.
actually iam modifing the servlet code to connect with MSSQL.previously it was MYSQL.now compiling is ok. while running it shows error at the top of the linked page as... error [Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]'SUBSTRING_INDEX' i
-
HELP! CANNOT SAVE PAGE PROBLEM!
Hi, can anybody tell me how to save a html page generated by document.write? Because when I click on IE's save button it save the page containing the script, instead of the generated page. Pls tell how, thanks.
-
I am trying to renew and download my WSJ apple. The iPad tells me I must sync to my computer...I do not have a computer..Any ideas?
-
About application server and database sever
where does apllication server and database server located in a us client project Edited by: madhu sudhan on Feb 21, 2008 11:02 AM