Array of JPanel ??????
Hy,
Can anyone please tell me if the folowing exist
(Array of JPanel):
JPanel pane[];
pane = new JPanel[5];
for(int i=1;i<5;i++) {
pane.setBounds(10,y,100,50);
y= y + 20;
Sure, you can do this (with some modification), but you need to create each JPanel stored in the array (the array won't automatically be initialized with JPanels):// create an array to hold JPanels
JPanel[] panels = new JPanel[5];
// Loop through the array and create
// a new panel for each slot.
// Also add the new panel to a parent panel
// and set its size and location.
for (int i=0; i < panels.length; i++)
panels[ i ] = new JPanel();
otherPanel.add(panels[ i ]);
panels[ i ].setBounds(x, y, 100, 50);
}Notice that the array is zero-based (the first item is panels[0] and the last item is panels[4]). Good luck!
Similar Messages
-
Array of JPanel and Array of JTextField?
Hi,
I try to create array of jpanel and inizialize it in "for" , but when run it give me this error message:
"Exception in thread "main" java.lang.NullPointerException"
at the row: "panInsCantante.add(panInsNCC);"
why?
(ps. i tried in another code to create array of jtextfield and it give me same error message..)
here part of code :
JPanel [] panInsCantante = new JPanel[3];
for(int i=0;i<=N;i++){
JPanel panInsNCC= new JPanel();
panInsNCC.setLayout( new GridLayout(3,1) );
panInsNCC.add(campoTesto1);
panInsNCC.add(campoTesto2);
panInsNCC.add(campoTesto3);
//panInsCantante[i] = new JPanel();
//panInsCantante.setLayout( new GridLayout(1,1) );
panInsCantante[i].add(panInsNCC);a question (theoric...)A VERY important question I may add.
what's the difference between ..
this instance :
JPanel [] panInsCantante = new
JPanel[3];This declares and initializes the array itself, nothing more. No JPanels have been initialized as yet, just the array. It's as if you have now built the shelves to hold the books, but you have no books up there yet...
and this instance of panInsCantante? :
panInsCantante[i] = new JPanel();and this initializes each JPanel in the array as you loop through the array. .... and now you have filled the shelves with the books and can use the books.
You will need them both.
In all likelihood, the reason for your confusion is that all of your previous arrays were arrays of primative types: int, double, float, and char. In this situation, you don't need to go through the step of initializing the variable.
But now you are faced for the first time with an array of reference type, an array of Objects. This is a different situation and requires the steps that we have gone through.
Message was edited by:
petes1234 -
Okay... not sure what I'm doing wrong but I'm trying to create an array of JPanels, and using a loop to add them to a main panel... It compiles fine, but theres a runtime error "nullPointerException" every time I try to run it and I'm not quite comprehending why...
JPanel[] Cell_Array = new JPanel[100];
JLabel[] Label_Array = new JLabel[100];
for (int i=0;i<100;i++) {
Cell_Array.setBackground(Color.black);
Label_Array[i].setText(" ");
Cell_Array[i].add(Label_Array[i]);
Main_Panel.add(Cell_Array[i]);You created the array but you have not put any panels into the array, so there is a null at every spot in the array.
-
How do i put an array of panels into a frame with a flow layout?
I just want to have my array of Jpanels displayed in a Jframe with a flow layout, how do i do this?
thankssaru88 wrote:
The problem is:
cards.setBackground(Color.red);
No, the real problem was before that. I saw SD before the stack trace in your original code, but the code 'ignored' that and continued on to the second exception you saw.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MemoryFrame extends JFrame{
private CardPanel[] cards;
final int noCards = 24;
public MemoryFrame(){
setTitle("Apple");
Toolkit tk = Toolkit.getDefaultToolkit();
int screenWidth = tk.getScreenSize().width;
int screenHeight = tk.getScreenSize().height;
int halfWidth = screenWidth/2;
int halfHeight = screenHeight/2;
setBounds(halfWidth/2,halfHeight/2,halfWidth-45, halfHeight+50);
Container c = getContentPane();
c.setLayout(new FlowLayout());
addWindowListener(new WindowAdapter () {
public void windowClosing(WindowEvent e) {
System.exit(0);
// this creates an array for 10 CardPanels, but they all start out as 'null'
cards = new CardPanel[noCards];
for(int i=0; i<noCards; i++){
try{
// this creates each individual CardPanel
cards[i] = new CardPanel();
cards.setBackground(Color.red);
// if there is an exception, it is pointless continuing
c.add(cards[i]);
}catch(Exception e){
System.out.println("SD");
e.printStackTrace();
public static void main(String[] args) {
// very hackish
new MemoryFrame().setVisible(true);
class CardPanel extends JPanel { -
Adding JComboBox[ ] at run time
Hi All
I am using jdk 1.5. I am trying to add JComboBox array to JPanel
But whenever I create its object it gives me
NULL POINTER Exception
My code is as below
JComboBox comboarray[]=new JComboBox[ls.getItemCount()];
System.out.println(""+comboarray[0].getName());
JOptionPane.showMessageDialog(null, ls.getItemCount());
for(int i=0;i<ls.getItemCount();i++)
comboarray.addItem(ls.getItems());
panel.add(comboarray[i]);
comboarray[i] = new JComboBox(ls.getItems());
What should be the problem ??
Thanking You
Regards
SGouravCreating an array of objects (such as JComboBoxes) is not the same as creating an array of primitives, such as an int array. When you create an array of comboboxes (or other objects), you're really creating an array of references to comboboxes, and not the comboboxes themselves. To use the comboboxes in the array, you first have to create them. Think of it as if you were creating a parking lot. Even if you create the parking lot, you can't use any of the cars in the lot until you first fill the lot with cars.
So for an array of comboboxes, you'd do....
JPanel comboPanel = new JPanel();
JComboBox[] comboArray = new JComboBox[20];
for (int i = 0; i < comboArray.length; i++) {
comboArray[i] = new JComboBox(); // first create the object
comboArray.addItem("foo " + i); // then and only then can you use it
comboPanel.add(comboArray[i]); -
Hi there,
Ive created an applet in Java which is basically a square with a boucing ball in it. The problem is i want to put this into a JFrame so i can add other controls. How would i go about this?? I initialise the image in the intialisation... i.e.
Buffer=createImage(600,600);
gBuffer=Buffer.getGraphics();
then i have my paint method as so.
public void paint(Graphics g)
gBuffer.setColor(Color.blue);
gBuffer.fillRect(0,0,size().width,size().height);
gBuffer.setColor(Color.yellow);
gBuffer.fillOval(0,0,600,600);
//Loop through Crabs
for (int i=0; i<=iNumberofCrabs; i++){
//Get Home
if(iCrab.getHasHome()){
Home phome = iCrab[i].getHome();
//Paint Home and Crab
phome.paint(gBuffer);
iCrab[i].paint(gBuffer);
g.drawImage (Buffer,20,10, this);
Any help would be great....
Regards Jamesi would probably do like this....................
* ImageClass.java
* Created on February 16, 2006, 1:20 AM
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
* @author hussain
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
public class ImageClass extends JFrame
jpanel j;
public ImageClass()
super("Image Application");
Container cpane = getContentPane();
j = new jpanel();
cpane.add(j);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public static void main(String args[])
final JFrame f = new ImageClass();
f.setBounds(100, 100, 300, 300);
f.setVisible(true);
class jpanel extends JPanel
Image image;
int i = 0;
short array[]= null;
jpanel()
setBackground(Color.WHITE);
public void paintComponent(Graphics g)
super.paintComponent(g);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
BufferedImage aImage = gc.createCompatibleImage(200, 200, Transparency.BITMASK);
image = Toolkit.getDefaultToolkit().getImage("c:\\fatwa.jpg");
g.drawImage(image, 0,0,this);
} -
Imovie os- multiple images put in cutaway
when i drag and cutaway 1 photo, several get dropped in and crazy fast images play when it is supposed to be one photo in cutaway. any ideas?
That's a good idea, but it isn't quite right for what I'm doing. What i'm doing is making a JList that contains in each cell: a string, another string, and 5 small images. Each should have some space between them.
|"A string" "Another string" XXXXX|
+-+
I've tried this with a JPanel, but when it creates the JList of my array of JPanels, i get the actual JPanel data used by java:
javax.swing.JPanel[,0,0,0x0,invalic,layout=java.awt.FlowLayout,alignmentX=0.0.....etc]I've also searched the API and all the tutorials before I came here, but everyone used setIcon(). -
Trying to setText on random JPanels via a String array?
My assignment is to create a bunch of JButtons, and randomly have an "X" appear on one, until it is clicked, and then it goes away and reappears on another random one. It does this ten times and displays the time it took to do so.
I've created all the JButtons, named b01 to b48 and put them in a gridLayout. That part works fine.
I created a String[] array with the 48 names of the JButtons in it, then I was thinking I could go this route...
Random r = new Random();
String random = panels[r.nextInt(panels.length)];
random.setText("X"); //This is where the program hangs up.I can replace the setText statement with a System.out.println statement, and it shows up on the console correctly...Brandon,
Have a chook at my minesweeper game at http://forum.java.sun.com/thread.jspa?forumID=54&threadID=5248903 ... it uses a matrix of cells[rows][cols]... each Cell is a JPanel which contains a Button.
I think you'll end up with something like ...
// create an array of Buttons
Button buttons[] = Button[NUM_BUTTONS];
for (int i=0; i<NUM_BUTTONS; i++) {
buttons[] = new Button(i);
// Xify a random button for a random time
buttons[random.nextInt(NUM_BUTTONS)].xify()I'd create a:
class Button extends JButton
* provides a constructor(int index) which sizes and places the button according to it's index
* provides an "xify" method, which setText("X"), then sets-up a SwingTimer to setText(null) after a random time.
Cheers. Keith. -
Displaying the value of an array in swing? Almost like a chess baord
Hi all.
After a long time from coding I thought I'd have a bash.
Here's a short outline of what I'm trying code.
I have a robot, a simple robot, does nothing but move around, pick up objects and drop them.
This robot lives in a world that is a square 1000x1000 for example.
The world is populated with objects, the robot goes around, if the robot is not holding an object and comes across one it will pick it up.
Then the robot moves around and if it comes across another object of the same type it will then drop the object.
These are the class names that I've created, the names give it away what they are for:
RobotProject (main class, not much in here apart from the starting parameters, such as starting position, how big the world is, number of objects in the world etc)
SandBox (is the class that the world object will be created from)
Robot (is the class the robot will be created from, I did it this way just in case I wanted more then one robot in the world)
GridCheck (this is a static class as it's only a set of instructions to carry out depending where in the world it the robot is and what is around it)
Movement (this class is not built yet, but all it does is check the current location of the robot, give options of where to move, then randomly picks a move)
Gui (this is going to be used to display the world, not built yet)
The object I create of SandBox is called world1, the only thing need to be known about this world is that it has an array, this array is what keeps track of each of the grid in the world and there state.
So let?s imagine a chess board, top left grid is 0 going from left to right/ top to bottom we end up with 63 (or 64 arrays).
What would be the best way to display this "chess board"?
At the moment I have a method in the SandBox class that will return all the grids states and a string.
This was put in there "just in case" but I think this is the wrong way to go.
Really what I'm after is a few pointers to make this work, maybe my way of doing this is incorrect?
I know I've been thinking that maybe I should have created an array of objects (SandBox, but with only an int rather than the array) rather than an object with an array var.
Anyways, I hope that makes sense, if not feel free to "bust my chops"
If you would like to see some of the mode feel free to ask, I'm not a student or anything, to be frank the last time I coded anything was over 4 years ago, so as you can guess the code is simply.
Jon.
Thanks in advance.
Edited by: jontelling on Jan 12, 2009 9:47 AMI agree with BDLH that Swing would work well here. There are a million and one way to create your "grid" one option include using a 2D grid of JLabels, another being a single JPanel with a grid BufferedImage as its background image (which is probably how I'd do it), etc... which one to choose will depend on the rest of the program, so it may be very early to say. Perhaps at this point you just want to create an interface of invariant behaviors to represent the Grid and thus allowing you flexibility with its implementation.
-
A question about how to change a button in a JPanel during runtime
I am a beginner of GUI. Now I am trying to change a specific component, a button, when the application is running. For example, I have 3 buttons in a JPanel. Each button has its onw icon. If I click one of them, it will change its icon, but the other two don't change. I don't know if there is any method for changing a specific component during runtime. If any one knows please let me know, I will appreciate that very much!!!
What you're going to have to do is loop inside the actionlistener but still have accessability to click while its looping. I don't know much about it, but I think you're going to need a thread. Try something like this... (it doesn't work yet, but I have to take off)
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class buttonxdemo extends JFrame implements ActionListener{
Buttonx mybutton;
//set it all up, make it look pretty =]
public buttonxdemo()
mybutton = new Buttonx("default");
getContentPane().add(mybutton.thebutton);
mybutton.thebutton.addActionListener(this);
this.setDefaultCloseOperation(3);
this.setSize(200,200);
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == mybutton.thebutton)
if (mybutton.keepGoing)
mybutton.keepGoing = false;
else if (!mybutton.keepGoing)
mybutton.keepGoing = true;
mybutton = new Buttonx(/*Icon,*/"My Button");
//getContentPane().remove(mybutton);
//getContentPane().add(mybutton.thebutton);
mybutton.startstop();
}//actionperformed
static void main(String args[])
new buttonxdemo().show();
} //movingicondemo
class Buttonx extends Thread{
public boolean keepGoing;
//public Icon ICx; //perhaps an array, so you can loop through?
public String strbuttonx;
public JButton thebutton; //may have to extend JFrame?
public Buttonx(/*Icon IC,*/ String strbutton){
//ICx = IC;
strbuttonx = strbutton;
thebutton = new JButton(strbuttonx);
public void startstop()
int i = 0;
while (keepGoing)
thebutton.setLabel(strbuttonx.substring(0,i));
//if an array of Icons ICx
//thebutton.setIcon(ICx);
i++;
if (i > strbuttonx.length() - 1)
i = 0;
try
Thread.sleep(1000);
catch (InterruptedException ie)
System.out.println("sleep caught: " + ie);
}//startstop()
}//buttonx
kev -
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);
} -
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();
} -
Display image in JPanel without saving any file to disk
Hi,
I am fetching images from database. I am saving this image, display in JPanel and delete it. But this is not actually I want.
I wish to fetch this image as stream , store in memory and display in JPanel without saving any fiel in disk.
I wonder if it is Possible or any used implementation that I can use in my project. Any idea or experienced knowledge is enough.
ThanksIn what format is the image coming to you from the database? If it's an InputStream subclass, just use javax.imageio.ImageIO:
InputStream in = getImageInputStream();
BufferedImage image = null;
try {
image = ImageIO.read(in);
} finally {
in.close();
// ... Display image in your JPanel as you have beenIf you receive the image as an array of bytes, use the same method as above, but with a ByteArrayInputStream:
byte[] imageData = getImageData();
ByteArrayInputStream in = new ByteArrayInputStream(imageData);
BufferedImage image = null;
try {
image = ImageIO.read(in);
} finally {
in.close();
// ... Display image in your JPanel as you have been -
Importing text file into 2D char array
Hey folks. I've aged a few years trying to figure this project out. Im trying to make a crossword puzzle and am having problems importing the answer letters into a 2D array of 15*15. The text file would look something like this:
LAPSE TAP RAH
AVAIL OLE ODE
BARGE PARADOX
etc
I have JTextFields that the user will answer and a button the user can press to see if the answers are right by comparing the 2D array answer with what the user inputted.-the user input would be scanned and put into a 2D array also.
How should i go about inserting each letter into an array? The spaces i would later need to make code to grey out the text field. This is what i have so far. Forgive me if its sloppy.
class gridPanel extends JPanel
//----Setting Grid variables
private static final int ROWS = 15;
private static final int COLS = 15;
String[] letters = { "A", "B", "C", "D", "E" };// To test entering strings into array
gridPanel()
this.setBackground(Color.BLUE);
//.......Making my JTextField grid for user input
JTextField[][] grid = new JTextField[ROWS][COLS];
for(int ROWS = 0; ROWS<grid.length; ROWS++)
for(int COLS = 0; COLS<grid.length; COLS++)
grid[ROWS][COLS] = new JTextField(1);
add(grid[ROWS][COLS]);
//grid[ROWS][COLS].setText("" + letters[0]);
String an = null;
StringTokenizer tokenizer = null;
Character[][] answer = new Character[ROWS][COLS];
try{
BufferedReader bufAns = new BufferedReader( new FileReader("C:\\xwordanswers.txt"));
for (int rowCurrent = 0; rowCurrent < ROWS; rowCurrent++)
an = bufAns.readLine();
tokenizer = new StringTokenizer(an);
for (int colCurrent = 0; colCurrent < COLS; colCurrent++) {
char currentValue = tokenizer.nextToken().charAt(0);//Needs to be changed to reflect each letter
answer[rowCurrent][colCurrent] = currentValue;
System.out.println(currentValue);
}catch (IOException ioex)
System.err.println(ioex);
System.exit(1);
}//xword graphics end
This obviously prints the first char of each word, it also gives me an "Exception in thread "main" java.util.NoSuchElementException" error for some reason.
Any help is greatly appreciated.
JohnIf the file format is stored as follows:
APPLE
L A
PARSE
N E
PEAR then we can parse this into a 2D char array:
char[][] readMap(String fileName) {
char[][] ret = new char[ROWS][COLS];
FileInputStream FIS = new FIleInputStream(fileName);
int i, j;
for(i = 0; i < ROWS; i++)
for(j = 0; j < COLS; j++)
ret[i][j] = FIS.read();
FIS.close();
return ret;
}Then you can use the resulting 2D char array in your answer checking mechanism.
Hope this helps~
Alex Lam S.L. -
Repaint() in JPanel doesn't align correctly
Hey all,
I'm running into this problem with a program I'm writing for work. It's basically a dispatch board which connects to our SQL server via ODBC. When the user presses a "Next" or "Prev" button, the dates will change and show the dispatching for the next or previous week respectively. However, the refreshed components go where they are supposed to, but the old screen is underneath, and shifted slightly so that nothing aligns. In turn, you can make heads or tails as to what's happening. However, if you select File -> Refresh from my menubar (calls repaint() the same way) everything is repainted correctly. Any ideas?
package dispatchBoard.DispatchBoard;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.sql.*;
import javax.swing.JPanel;
import sun.misc.Queue;
public class DB_MainWindow extends JPanel implements MouseListener{
private static final long serialVersionUID = 1L;
private int _xRes, _yRes;
private int _techs;
private String _dayOption, _monday, _tuesday, _wednesday, _thursday, _friday, _odbcName, _databaseName, _currYear;
private String[] _months;
private Tech _myTechList;
private Font _defaultFont;
DB_Frame _mainFrame;
private Calendar cal = new GregorianCalendar();
public DB_MainWindow(String _resolution, String optionString, String ofTechs, DB_Frame frame, String _odbc, String _database, String _year)
_xRes = Integer.valueOf(_resolution.substring(0, findCharPosition(_resolution, 'x'))).intValue() - 5;
_yRes = Integer.valueOf(_resolution.substring(findCharPosition(_resolution, 'x')+1)).intValue() - 30;
_techs = Integer.valueOf(ofTechs).intValue();
_dayOption = optionString;
_mainFrame = frame;
_odbcName = _odbc;
_databaseName = _database;
_currYear = _year;
setDaysFiveStraight();
System.out.println(_xRes + " " + _yRes);
this.setBackground(Color.GRAY);
this.setPreferredSize(new Dimension(_xRes,_yRes));
this.addMouseListener(this);
public void paint(Graphics g)
_myTechList = null;
int _spacing = 0;
int _spacing2 = 0;
g.setColor(Color.BLACK);
g.drawLine(60,0,60,_yRes);
_defaultFont =g.getFont();
//draw tech barriers
for (int i = 1; i < _techs+1; i ++)
_spacing = _yRes / (_techs+1);
g.drawLine(0, _spacing*i, 1366, _spacing*i);
//draw day barriers
for (int j = 1; j < 5; j++)
_spacing2 = (_xRes-60) / 5;
g.drawLine(_spacing2*j + 60, 0, _spacing2*j + 60, 768);
int _curPos = 60, _timePos = 0;
int _time[] = {8,9,10,11,12,1,2,3,4,5};
for (int k = 0; k < 5; k++)
_curPos = 60+(k*_spacing2);
for (int l = 0; l < 9; l++)
g.drawLine( _curPos + (l*(_spacing2/9)), 0+_spacing, _curPos + (l*(_spacing2/9)), _yRes);
String _tempString = ""+_time[_timePos];
g.drawString(_tempString, _curPos + (l*(_spacing2/9)), _spacing);
_timePos++;
_timePos = 0;
//draw graph labels
System.out.println(_dayOption);
g.drawString("TECHS", 10, _spacing);
g.drawString("Monday "+_monday, 60+(_spacing2/2) - 23, _spacing/2);
g.drawString("Tuesday "+_tuesday, 60+_spacing2+(_spacing2/2) - 26, _spacing/2);
g.drawString("Wednesday "+_wednesday, 60+2*_spacing2+(_spacing2/2) - 33, _spacing/2);
g.drawString("Thursday "+_thursday, 60+3*_spacing2+(_spacing2/2) - 28, _spacing/2);
g.drawString("Friday "+_friday, 60+4*_spacing2+(_spacing2/2) - 25, _spacing/2);
* At this point the default grid, including all labels, have been drawn on
* the dispatch board. Now, we have to fetch the data from the SQL server,
* place it into some sort of form (possibly 2d array?!) and then print it out
* on the board....
* Here goes!
// this.addMouseMotionListener(this);
// g.drawRect(_mousePosition.x, _mousePosition.y, 10, 10);
fillInTimes(g, _spacing, _spacing2);
public void setDaysFiveStraight()
if (_dayOption.equals(new String("work_week")))
_monday = new String("");
_tuesday = new String("");
_wednesday = new String("");
_thursday = new String("");
_friday = new String("");
String[] _months2 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
_months = _months2;
* Sunday = 1
* Monday = 2
System.out.println("DAY OF THE WEEK = "+cal.get(Calendar.DAY_OF_WEEK));
if (cal.get(Calendar.DAY_OF_WEEK) == 2)
_monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
else if (cal.get(Calendar.DAY_OF_WEEK) == 3)
{ //tuesday
_tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
System.out.println("TUESDAY = "+_tuesday);
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
_monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
else if (cal.get(Calendar.DAY_OF_WEEK) == 4)
_wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
_monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
//System.out.println("TUESDAY = "+_tuesday);
else if (cal.get(Calendar.DAY_OF_WEEK) == 5)
{ //thursday
_thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
_monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
else if (cal.get(Calendar.DAY_OF_WEEK) == 6)
{ //friday
_friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
_monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
_thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
private void fillInTimes(Graphics g, int _spacing, int _spacing2) {
// need to get the data first, building pre-defined array for test data...
//****START REAL DATA LOAD****\\
// Calendar cal = new GregorianCalendar();
try {
// Load the JDBC-ODBC bridge
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
// specify the ODBC data source's URL
String url = "jdbc:odbc:"+_odbcName;
// connect
Connection con = DriverManager.getConnection(url,"sa",_currYear);
// create and execute a SELECT
Statement stmt = con.createStatement();
Statement stmt2 = con.createStatement();
ResultSet techList = stmt2.executeQuery("USE "+_databaseName+" SELECT Distinct(SV00301.Technician) from SV00301 join SV00115 on SV00301.Technician = SV00115.Technician where SV00115.SV_Inactive<>1");
// traverse through results
Tech temp;
int counter = 0;
while(techList.next())
if (_myTechList == null)
_myTechList = new Tech(techList.getString(1).trim());
System.out.println(_myTechList.getName());
counter++;
else if (!_myTechList.hasNext())
_myTechList.setNext(new Tech(techList.getString(1).trim()));
System.out.println(_myTechList.getNext().getName());
counter++;
else
temp = _myTechList.getNext();
while(temp.hasNext())
temp = temp.getNext();
temp.setNext(new Tech(techList.getString(1).trim()));
System.out.println(temp.getNext().getName());
counter++;
// printTechList();
String nextMonth, prevMonth;
if(cal.get(Calendar.MONTH)==11)
nextMonth=_months[0];
else
nextMonth = _months[cal.get(Calendar.MONTH)+1];
if(cal.get(Calendar.MONTH) == 0)
prevMonth = _months[11];
else
prevMonth = _months[cal.get(Calendar.MONTH)-1];
ResultSet rs = stmt.executeQuery
("USE "+_databaseName+" SELECT * from SV00301 JOIN SV00300 on SV00300.Service_Call_ID = SV00301.Service_Call_ID JOIN SV00115 on SV00300.Technician = SV00115.Technician JOIN SV000805 on SV000805.Service_Call_ID = SV00301.Service_Call_ID and SV000805.Note_Service_Index='Description' where (Month(SV00301.Task_Date)="+_months[cal.get(Calendar.MONTH)]+" or Month(SV00301.Task_Date)="+prevMonth+" or Month(SV00301.Task_Date)="+nextMonth+") and SV00300.Status_of_Call='OPEN' and SV00115.SV_Inactive<>1");
System.out.println("USE "+_databaseName+" SELECT * from SV00301 JOIN SV00300 on SV00300.Service_Call_ID = SV00301.Service_Call_ID JOIN SV00115 on SV00300.Technician = SV00115.Technician JOIN SV000805 on SV000805.Service_Call_ID = SV00301.Service_Call_ID and SV000805.Note_Service_Index='Description' where (Month(SV00300.Date_of_Service_Call)="+_months[cal.get(Calendar.MONTH)]+" or Month(SV00300.Date_of_Service_Call)="+prevMonth+" or Month(SV00300.Date_of_Service_Call)="+nextMonth+") and SV00300.Status_of_Call='OPEN' and SV00115.SV_Inactive<>1");
while (rs.next()) {
// get current row values
String servicecallid = rs.getString(1).trim(),
tech = rs.getString(4).trim(),
rawDate = rs.getString(6).trim(),
startTime = rs.getString(7).trim(),
_length = rs.getString(9).trim(),
description = rs.getString(33).trim(),
customernumber = rs.getString(35).trim(),
custname = rs.getString(45).trim(),
location = rs.getString(46).trim(),
calltype = rs.getString(54).trim(),
notes = rs.getString(268).trim();
// String formattedDate = month+"/"+day+"/"+year;
// System.out.println(formattedDate);
// String tech = rs.getString(142).trim();
// String rawDate = rs.getString(144);
System.out.println(rawDate);
String day = rawDate.substring(8,10);
String month = rawDate.substring(5,7);
String year = rawDate.substring(0,4);
formatNumber(day);
formatNumber(month);
// startTime = rs.getString(145);
// String _length = rs.getString(147);
int hour = Integer.valueOf(startTime.substring(11,13)).intValue();
String minute = startTime.substring(14,16);
int minutes = Integer.valueOf(minute).intValue();
minutes = minutes / 60;
double length = (Integer.valueOf(_length).intValue())/100;
// print values
//System.out.println ("Service_Call_ID = " + Surname);
if (hour!=0)
sortJob(new Job(servicecallid, custname, new MyDate(month,day,year), hour+minutes,length, description, customernumber, location, calltype, notes), _myTechList, tech);
// close statement and connection
stmt.close();
con.close();
catch (java.lang.Exception ex) {
ex.printStackTrace();
//draw techs and blocks of jobs!!!!!
//***TECHS***\\
Tech _tempTech = new Tech("DOOKIE");
int multiplier = 2;
if (_myTechList.hasNext())
g.setColor(Color.BLACK);
_tempTech = _myTechList.getNext();
g.drawString(_myTechList.getName(),5,(_spacing)*multiplier);
System.out.println("printJobs(g, "+_myTechList.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
printJobs(g,_myTechList,multiplier, _spacing,_spacing2);
multiplier++;
while(_tempTech.hasNext())
g.setColor(Color.BLACK);
g.drawString(_tempTech.getName(),5,(_spacing)*multiplier);
System.out.println("printJobs(g, "+_tempTech.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
printJobs(g,_tempTech,multiplier, _spacing,_spacing2);
multiplier++;
_tempTech = _tempTech.getNext();
g.setColor(Color.BLACK);
g.drawString(_tempTech.getName(),5,(_spacing)*multiplier);
System.out.println("printJobs(g, "+_tempTech.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
printJobs(g,_tempTech,multiplier, _spacing,_spacing2);
//***TIME BLOCKS***\\\
private void printTechList() {
// TODO Auto-generated method stub
boolean temp = !_myTechList.hasNext();
Tech tempTech = _myTechList;
System.out.println("BEGINNING TECH LIST PRINTOUT!!!!");
while (tempTech.hasNext() || temp)
System.out.println(tempTech.getName());
if (temp)
temp = !temp;
else
tempTech = tempTech.getNext();
System.out.println(tempTech.getName());
System.out.println("END TECH LIST PRINTOUT!!!");
private void formatNumber(String month) {
// TODO Auto-generated method stub
if (month.equals(new String("01")))
month = new String("1");
else if (month.equals(new String("02")))
month = new String("2");
else if (month.equals(new String("03")))
month = new String("3");
else if (month.equals(new String("04")))
month = new String("4");
else if (month.equals(new String("05")))
month = new String("5");
else if (month.equals(new String("06")))
month = new String("6");
else if (month.equals(new String("07")))
month = new String("7");
else if (month.equals(new String("08")))
month = new String("8");
else if (month.equals(new String("09")))
month = new String("9");
private void printJobs(Graphics g, Tech techList, int multiplier, int _spacing, int _spacing2) {
Job tempJob = techList.getJobs();
boolean temp = false;
if (tempJob != null)
{ temp = !tempJob.hasNext();
while (tempJob.hasNext() || temp)
g.setColor(Color.RED);
String _tempDate = new String(tempJob.getDate().toString());
// System.out.println("This job has date of: "+_tempDate);
int horizontalMultiplier = 0;
if (_tempDate.equals(_monday))
horizontalMultiplier = 0;
else if (_tempDate.equals(_tuesday))
horizontalMultiplier = 1;
else if (_tempDate.equals(_wednesday))
horizontalMultiplier = 2;
else if (_tempDate.equals(_thursday))
horizontalMultiplier = 3;
else if (_tempDate.equals(_friday))
horizontalMultiplier = 4;
else
horizontalMultiplier = 5;
// System.out.println("HorizontalMultiplier = "+horizontalMultiplier);
if (horizontalMultiplier !=5)
if (tempJob.getJobCallType().equals(new String("TM"))) g.setColor(new Color(0,255,0));
else if (tempJob.getJobCallType().equals(new String("SU"))) g.setColor(new Color(0,255,255));
else if (tempJob.getJobCallType().equals(new String("SPD"))) g.setColor(new Color(44,148,67));
else if (tempJob.getJobCallType().equals(new String("QUO"))) g.setColor(new Color(0,255,255));
else if (tempJob.getJobCallType().equals(new String("MCC"))) g.setColor(new Color(255,0,255));
else if (tempJob.getJobCallType().equals(new String("MC"))) g.setColor(new Color(128,0,255));
else if (tempJob.getJobCallType().equals(new String("CBS"))) g.setColor(new Color(0,0,255));
else if (tempJob.getJobCallType().equals(new String("AS"))) g.setColor(new Color(255,255,255));
else g.setColor(Color.red);
g.fillRect(/*START X*/(int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1),/*START Y*/_spacing*(multiplier-1)+1,/*LENGTH*/(int)(tempJob.getJobLength()*(_spacing2/9)-1),/*WIDTH*/_spacing-1);
System.out.println("g.fillRect("+((int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1))+","+(_spacing*(multiplier-1)+1)+","+((int)(tempJob.getJobLength()*(_spacing2/9)-1))+","+(_spacing-1)+") :: Multiplier = "+multiplier+" :: JOB NAME = "+tempJob.getJobName()+" :: JOB NUMBER = "+tempJob.getJobNumber());
g.setColor(Color.BLACK);
g.setFont(new Font("Monofonto", Font.PLAIN, 22));
if ((int)(tempJob.getJobLength()*(_spacing2/9)-1) >0)
g.drawString(formatStringLength(tempJob.getJobName().toUpperCase(), tempJob.getJobLength()), (int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1), (_spacing*(multiplier)+1)-_spacing/2+5);
g.setFont(_defaultFont);
if (!temp)
tempJob = tempJob.getNext();
if (tempJob.hasNext() == false)
temp = true;
else
temp = !temp;
else
System.out.println("*g.fillRect("+((int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1))+","+(_spacing*(multiplier-1)+1)+","+((int)(tempJob.getJobLength()*(_spacing2/9)-1))+","+(_spacing-1)+") :: Multiplier = "+multiplier+" :: JOB NAME = "+tempJob.getJobName()+" :: JOB NUMBER = "+tempJob.getJobNumber());
if (!temp)
tempJob = tempJob.getNext();
if (tempJob.hasNext() == false)
temp = true;
else
temp = !temp;
// g.fillRect((int)(60+(tempJob.getStarTime()-8)*(_spacing2/9)+1),_spacing*(multiplier-1)+1,(int)(tempJob.getJobLength()*(_spacing2/9)-1),_spacing-1);
private String formatStringLength(String string, double jobLength) {
// TODO Auto-generated method stub
if (jobLength*3>string.length())
return string;
return string.substring(0, new Double(jobLength*3).intValue());
private void sortJob(Job job, Tech techList, String techName) {
Tech _tempTech2;
if (techName.equals(techList.getName()))
techList.insertJob(job);
System.out.println("ADDED " + job.getJobName() +" TO " + techName);
else
_tempTech2 = techList.getNext();
while (!_tempTech2.getName().equals(techName) && _tempTech2.hasNext())
_tempTech2 = _tempTech2.getNext();
// System.out.println(_tempTech2.getName()+" vs. " + techName);
if (_tempTech2.getName().equals(techName))
_tempTech2.insertJob(job);
System.out.println("ADDED " + job.getJobName() +" TO " + techName);
else
System.out.println("TECH NAME: "+_tempTech2.getName()+" NOT FOUND :: COULD NOT INSERT JOB");
private int findCharPosition(String _resolution2, char c) {
// TODO Auto-generated method stub
for (int i = 0; i < _resolution2.length(); i++)
if (_resolution2.charAt(i) == c)
return i;
return 0;
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Mouse clicked at coordinates: "+arg0.getX()+", "+arg0.getY()+"\nAttempting to intelligently find the job number");
* Find the tech
int techNum = arg0.getY()/(_yRes / (_techs+1));
String techName= new String("");
int counter = 0;
Tech temp = _myTechList;
boolean found = true;
while(temp.hasNext() && found)
counter++;
if (counter == techNum)
techName = temp.getName();
found = false;
else
temp = temp.getNext();
System.out.println("The "+techNum+"th tech was selected... which means you clicked "+techName);
* Find the day
int day = (arg0.getX()-60)/(0 + ((_xRes-60)/5));
String days[] = {_monday, _tuesday, _wednesday, _thursday, _friday};
System.out.println("The day you chose was "+days[day]);
* Find the time
int blocksIn = ((arg0.getX()-60)/(((_xRes-60)/5)/9))%9;
System.out.println(blocksIn+" blocks inward!!!!");
* Find the job
* - temp is already initialized to the current tech!!
System.out.println(temp.getName()+" has "+temp.getNumberOfJobs()+" jobs");
Job current = temp.getJobs();
Queue jobQueue = new Queue();
boolean first = true;
while(current.hasNext() || first)
if(current.getDate().toString().equals(days[day]))
jobQueue.enqueue(current);
System.out.println("Queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
if (first)
first = false;
current = current.getNext();
else
current = current.getNext();
else
System.out.println("Did not queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
if (first)
first = false;
current = current.getNext();
else
current = current.getNext();
if(current.getDate().toString().equals(days[day]))
jobQueue.enqueue(current);
System.out.println("Queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
else
System.out.println("Did not queue the job on "+current.getDate().toString()+"::"+current.getJobNumber());
blocksIn+=8;
while(!jobQueue.isEmpty())
try {
* Get a job off the queue... now check the times
Job dqJob = (Job)jobQueue.dequeue();
System.out.println(dqJob.getStarTime()+"<="+blocksIn +" && "+(dqJob.getStarTime()+dqJob.getJobLength()-1)+">="+blocksIn+" :: "+dqJob.getJobName());
if (dqJob.getStarTime()<=blocksIn && dqJob.getStarTime()+dqJob.getJobLength()-1>=blocksIn)
System.out.println("MONEY!!!! Found job: "+dqJob.getJobName());
new JobDisplayer(dqJob, _xRes, _yRes);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
public void nextDay() {
// TODO Auto-generated method stub
if (_dayOption.equals(new String("work_week")))
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+7);
setDaysFiveStraight();
this.repaint();
public void prevDay() {
// TODO Auto-generated method stub
if (_dayOption.equals(new String("work_week")))
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-7);
setDaysFiveStraight();
this.repaint();
this.repaint();
}Sorry for the huge chunk of code.
Thanks in advance,
JeffSorry for the huge chunk of code.
Mm, yes, I'm far too lazy to read all that.
But you should be overriding paintComponent(), not paint().
http://www.google.co.uk/search?hl=en&q=java+swing+painting&btnG=Google+Search&meta=
I've not bothered to work out from that pile of magic numbers exactly what you're tring to draw but is it not something that JTable would happily do?
Maybe you are looking for
-
I was in a conversation with a colleague and a text (identical) came to both of our phones, when he researched it, it said it was blocked and I thought I might see where it came from through my phone. Is it possible to get a spam like that to our pho
-
Yellowish tinge on the bottom part of my SD card 15" MacBook Pro
I just got my new 15" SD card MacBook Pro and it looks to me like there is a yellowish tinge to the lower part of the screen. Doing a quick search I see that this was a problem with some of the older MBP models. Has Apple fixed this with the new sd c
-
Adding timezone metadata that Aperture will recognize on import
I have 3,200 scanned photos, and a spreadsheet with the time, date and timezone of each one on it (my APS photos, 1997~2004), and I have been making exiftool scripts to write the time and date into each file. However, I have been unable to make the t
-
I spent hours working on a project in Logic. I saved the project and quit Logic. I came back an hour later, and the settings of every one of my instruments were completely messed up. I've tried reverting to other saved versions, but they are all mess
-
I am building a site in Dreamweaver for a client who wants to be able to maintain it themselves once it is up and running. Do they need to purchase the Contribute program and if so, is there a version for the PC? And is it a stand-alone program? Or,