Help needed on clearing concept regarding javax.swing.Timer.
Hello,
I am not able to understand the concept of Timer. Say suppose
1) i extend JFrame and create my own frame object
2) i extend JPanel and create my own panel object
3) in frame object's constructor i create a panel's object
4) in panel object's constructor i create a Timer class's object and perform slideshow
5) after some time ( say when index reaches to 5 i stop timer using timerObj.kill() )
6) when this timer stops i want the panel object to be removed from frame. This means i need
to write some code in frame object's constructor that will wait till the timer is running and when it is stopped i would say remove(panelObject). But how to do this??
Thanks in advance ! :)
no i don't want to remove the panel within the statement that cancels the timer because basically i want to lot more things also like performing some other kind of animation etc. How can i remove from withing frame's constructor only?i tried the following things :-
try{
Thread.currentThread().join();
catch(InterruptedException ex){
while(panelObj.tmObj.isRunning()){
try{
Thread.currentThread().sleep(1000);
catch(InterruptedException ex){
}but none of them seems to work. When i write either of the above code nothing happens. Even the window does not appear :(
Edited by: Salman4u on Mar 31, 2009 9:07 PM
Similar Messages
-
Frnds help needed in clearing concept!!
Frnds,
My program requirement is.. to run external tool taking some inputs.. and for that I have start and stop button.. to pause it taking inputs for next time.. !!
Since i dont know how long my external process takes place.. so am using SwingWorker for the same.. Below is my piece of code.. for my startButton..
For continous taking inputs.. am using a while loop.. and stopping it on Stop Button.. I have problem in placing that while loop!!.. Should I place it ouside SwingWorker class or inside it ?? And am making close = false; in StopButton.. is this right way of doing.. what am trying to achieve??
public void actionPerformed(ActionEvent e) {
progressBar.setIndeterminate(true);
startButton.setEnabled(false);
new SwingWorker() {
public Object construct() {
while(close) // Problem.. whether this while loop will be outside SwingWorker or here ??
LongTask(value); // This function takes time.. run external tool
value++;
return null;
public void finished() {
progressBar.setIndeterminate(false);
startButton.setEnabled(true);
}.start();
}Thanks in advance!!
gerviniSwingWorker is not part of the standard API.well i know that.. its just used to run.. long task.. as separate thread..
U can treat is same as a
new Thread() {
public void run() {
}but still am unclear.. about my while loop.. where to put it!!
Inside thread.. or put thread in while loop?? -
Help ! inaccurate time recorded using javax.swing.timer
Hi All,
I am currently trying to write a stopwatch for timing application events such as loggon, save, exit ... for this I have created a simple Swing GUI and I am using the javax.swing.timer and updating a the time on a Jlabel. The trouble that I am having is that the time is out by up to 20 seconds over a 10 mins. Is there any way to get a more accruate time ?? The code that I am using is attached below.
private Timer run = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
timeTaken.setText("<html><font size = 5><b>" + (df.format(timeHours)) + ":" + (df.format(timeMins)) + ":"
+ (df.format(timeSeconds++)) + "</b></font><html>");
receordedTimeValue = ((df.format(timeHours)) + ":" + (df.format(timeMins)) + ":"
+ (df.format(timeSeconds)));
if (timeSeconds == 60) {
timeMins++;
timeSeconds = 0;
if (timeMins == 60) {
timeHours++;
timeMins = 0;To get more accurate time you should use the System.currentTimeMillis() method.
Try this code :
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CountUpLabel extends JLabel{
javax.swing.Timer timer;
long startTime, count;
public CountUpLabel() {
super(" ", SwingConstants.CENTER);
timer = new javax.swing.Timer(500, new ActionListener() { // less than or equal to 1000 (1000, 500, 250,200,100)
public void actionPerformed(ActionEvent event) {
if (startTime == -1) {
count = 0;
startTime = System.currentTimeMillis();
else {
count = System.currentTimeMillis()-startTime;
setText(getStringTime(count));
private static final String getStringTime(long millis) {
int seconds = (int)(millis/1000);
int minutes = (int)(seconds/60);
int hours = (int)(minutes/60);
minutes -= hours*60;
seconds -= (hours*3600)+(minutes*60);
return(((hours<10)?"0"+hours:""+hours)+":"+((minutes<10)?"0"+minutes:""+minutes)+":"+((seconds<10)?"0"+seconds:""+seconds));
public void start() {
startTime = -1;
timer.setInitialDelay(0);
timer.start();
public long stop() {
timer.stop();
return(count);
public static void main(String[] args) {
JFrame frame = new JFrame("Countdown");
CountUpLabel countUp = new CountUpLabel();
frame.getContentPane().add(countUp, BorderLayout.CENTER);
frame.setBounds(200,200,200,100);
frame.setVisible(true);
countUp.start();
Denis -
Help needed in printing a JPanel in Swing..
Hi,
I'm working on a Printing task using Swing. I'm trying to print a JPanel. All i'm doing is by creating a "java.awt.print.Book" object and adding (append) some content to it. And these pages are in the form of JPanel. I've created a separate class for this which extends the JPanel. I've overridden the print() method. I have tried many things that i found on the web and it simply doesn't work. At the end it just renders an empty page, when i try to print it. I'm just pasting a sample code of the my custom JPanel's print method here:
public int print(Graphics g, PageFormat pageformat, int pagenb)
throws PrinterException {
//if(pagenb != this.pagenb) return Printable.NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D)g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setClip(0, 0, this.getWidth(), this.getHeight());
g2d.setColor(Color.BLACK);
//disable double buffering before printing
RepaintManager rp = RepaintManager.currentManager(this);
rp.setDoubleBufferingEnabled(false);
this.paint(g2d);
rp.setDoubleBufferingEnabled(true);
return Printable.PAGE_EXISTS;
}Please help me where i'm going wrong. I'm just trying to print the JPanel with their contents.
Thanks in advance.Hi,
Try this
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.AbstractAction;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
public class PrintablePanel extends JPanel implements Printable {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final PrintablePanel target = new PrintablePanel(
new BorderLayout());
target.add(new JColorChooser());
frame.add(target, BorderLayout.CENTER);
JToolBar toolBar = new JToolBar();
frame.add(toolBar, BorderLayout.PAGE_START);
toolBar.add(new AbstractAction("Print") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent event) {
PrinterJob printerJob = PrinterJob.getPrinterJob();
printerJob.setPrintable(target);
try {
printerJob.print();
} catch (PrinterException e) {
e.printStackTrace();
frame.pack();
frame.setVisible(true);
public PrintablePanel() {
super();
public PrintablePanel(LayoutManager layout) {
super(layout);
@Override
public int print(Graphics g, PageFormat format, int page)
throws PrinterException {
if (page == 0) {
Graphics2D g2 = (Graphics2D) g;
g2.translate(format.getImageableX(), format.getImageableY());
print(g2);
g2.translate(-format.getImageableX(), -format.getImageableY());
return Printable.PAGE_EXISTS;
} else {
return Printable.NO_SUCH_PAGE;
}Piet
Edit: Sorry. Just now I see that you want to use the Swing print mechanism. But I guess the implementation of the Printable interface remains the same.
Edited by: pietblok on 14-nov-2008 17:23 -
Help needed:Printing HTML file using javax.print
Hi
I am using the following code which i got form the forum for rpinting an HTML file.
The folllowing code is working fine, but the problem is the content of HTML file is not getting printed. I am geeting a blank page with no content. What is the change that is required in the code? ALso is there any simpler way to implement this. Help needed ASAP.
public boolean printHTMLFile(String filename) {
try {
JEditorPane editorPane = new JEditorPane();
editorPane.setEditorKit(new HTMLEditorKit());
//editorPane.setContentType("text/html");
editorPane.setSize(500,500);
String text = getFileContents(filename);
if (text != null) {
editorPane.setText(text);
} else {
return false;
printEditorPane(editorPane);
return true;
} catch (Exception tce) {
tce.printStackTrace();
return false;
public String getFileContents(String filename) {
try {
File file = new File(filename);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
br.close();
return sb.toString();
} catch (Exception tce) {
tce.printStackTrace();
return null;
public void printEditorPane(JEditorPane editorPane) {
try {
HTMLPrinter htmlPrinter = new HTMLPrinter();
htmlPrinter.printJEditorPane(editorPane, htmlPrinter.showPrintDialog());
} catch (Exception tce) {
tce.printStackTrace();
* Sets up to easily print HTML documents. It is not necessary to call any of the setter
* methods as they all have default values, they are provided should you wish to change
* any of the default values.
public class HTMLPrinter {
public int DEFAULT_DPI = 72;
public float DEFAULT_PAGE_WIDTH_INCH = 8.5f;
public float DEFAULT_PAGE_HEIGHT_INCH = 11f;
int x = 100;
int y = 80;
GraphicsConfiguration gc;
PrintService[] services;
PrintService defaultService;
DocFlavor flavor;
PrintRequestAttributeSet attributes;
Vector pjlListeners = new Vector();
Vector pjalListeners = new Vector();
Vector psalListeners = new Vector();
public HTMLPrinter() {
gc = null;
attributes = new HashPrintRequestAttributeSet();
flavor = null;
defaultService = PrintServiceLookup.lookupDefaultPrintService();
services = PrintServiceLookup.lookupPrintServices(flavor, attributes);
// do something with the supported docflavors
DocFlavor[] df = defaultService.getSupportedDocFlavors();
for (int i = 0; i < df.length; i++)
System.out.println(df.getMimeType() + " " + df[i].getRepresentationClassName());
// if there is a default service, but no other services
if (defaultService != null && (services == null || services.length == 0)) {
services = new PrintService[1];
services[0] = defaultService;
* Set the GraphicsConfiguration to display the print dialog on.
* @param gc a GraphicsConfiguration object
public void setGraphicsConfiguration(GraphicsConfiguration gc) {
this.gc = gc;
public void setServices(PrintService[] services) {
this.services = services;
public void setDefaultService(PrintService service) {
this.defaultService = service;
public void setDocFlavor(DocFlavor flavor) {
this.flavor = flavor;
public void setPrintRequestAttributes(PrintRequestAttributeSet attributes) {
this.attributes = attributes;
public void setPrintDialogLocation(int x, int y) {
this.x = x;
this.y = y;
public void addPrintJobListener(PrintJobListener pjl) {
pjlListeners.addElement(pjl);
public void removePrintJobListener(PrintJobListener pjl) {
pjlListeners.removeElement(pjl);
public void addPrintServiceAttributeListener(PrintServiceAttributeListener psal) {
psalListeners.addElement(psal);
public void removePrintServiceAttributeListener(PrintServiceAttributeListener psal) {
psalListeners.removeElement(psal);
public boolean printJEditorPane(JEditorPane jep, PrintService ps) {
if (ps == null || jep == null) {
System.out.println("printJEditorPane: jep or ps is NULL, aborting...");
return false;
// get the root view of the preview pane
View rv = jep.getUI().getRootView(jep);
// get the size of the view (hopefully the total size of the page to be printed
int x = (int) rv.getPreferredSpan(View.X_AXIS);
int y = (int) rv.getPreferredSpan(View.Y_AXIS);
// find out if the print has been set to colour mode
DocPrintJob dpj = ps.createPrintJob();
PrintJobAttributeSet pjas = dpj.getAttributes();
// get the DPI and printable area of the page. use default values if not available
// use this to get the maximum number of pixels on the vertical axis
PrinterResolution pr = (PrinterResolution) pjas.get(PrinterResolution.class);
int dpi;
float pageX, pageY;
if (pr != null)
dpi = pr.getFeedResolution(PrinterResolution.DPI);
else
dpi = DEFAULT_DPI;
MediaPrintableArea mpa = (MediaPrintableArea) pjas.get(MediaPrintableArea.class);
if (mpa != null) {
pageX = mpa.getX(MediaPrintableArea.INCH);
pageY = mpa.getX(MediaPrintableArea.INCH);
} else {
pageX = DEFAULT_PAGE_WIDTH_INCH;
pageY = DEFAULT_PAGE_HEIGHT_INCH;
int pixelsPerPageY = (int) (dpi * pageY);
int pixelsPerPageX = (int) (dpi * pageX);
int minY = Math.max(pixelsPerPageY, y);
// make colour true if the user has selected colour, and the PrintService can support colour
boolean colour = pjas.containsValue(Chromaticity.COLOR);
colour = colour & (ps.getAttribute(ColorSupported.class) == ColorSupported.SUPPORTED);
// create a BufferedImage to draw on
int imgMode;
if (colour)
imgMode = BufferedImage.TYPE_3BYTE_BGR;
else
imgMode = BufferedImage.TYPE_BYTE_GRAY;
BufferedImage img = new BufferedImage(pixelsPerPageX, minY, imgMode);
Graphics myGraphics = img.getGraphics();
myGraphics.setClip(0, 0, pixelsPerPageX, minY);
myGraphics.setColor(Color.WHITE);
myGraphics.fillRect(0, 0, pixelsPerPageX, minY);
java.awt.Rectangle rectangle=new java.awt.Rectangle(0,0,pixelsPerPageX, minY);
// call rootView.paint( myGraphics, rect ) to paint the whole image on myGraphics
rv.paint(myGraphics, rectangle);
try {
// write the image as a JPEG to the ByteArray so it can be printed
Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter) writers.next();
// mod: Added the iwparam to create the highest quality image possible
ImageWriteParam iwparam = writer.getDefaultWriteParam();
iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
iwparam.setCompressionQuality(1.0f); // highest quality
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(out);
writer.setOutput(ios);
// get the number of pages we need to print this image
int imageHeight = img.getHeight();
int numberOfPages = (int) Math.ceil(minY / (double) pixelsPerPageY);
// print each page
for (int i = 0; i < numberOfPages; i++) {
int startY = i * pixelsPerPageY;
// get a subimage which is exactly the size of one page
BufferedImage subImg = img.getSubimage(0, startY, pixelsPerPageX, Math.min(y - startY, pixelsPerPageY));
// mod: different .write() method to use the iwparam parameter with highest quality compression
writer.write(null, new IIOImage(subImg, null, null), iwparam);
SimpleDoc sd = new SimpleDoc(out.toByteArray(), DocFlavor.BYTE_ARRAY.JPEG, null);
printDocument(sd, ps);
// reset the ByteArray so we can start the next page
out.reset();
} catch (PrintException e) {
System.out.println("Error printing document.");
e.printStackTrace();
return false;
} catch (IOException e) {
System.out.println("Error creating ImageOutputStream or writing to it.");
e.printStackTrace();
return false;
// uncomment this code and comment out the 'try-catch' block above
// to print to a JFrame instead of to the printer
/* JFrame jf = new JFrame();
PaintableJPanel jp = new PaintableJPanel();
jp.setImage( img );
JScrollPane jsp = new JScrollPane( jp );
jf.getContentPane().add( jsp );
Insets i = jf.getInsets();
jf.setBounds( 0, 0, newX, y );
jf.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
jf.setVisible( true );*/
return true;
* Print the document to the specified PrintService.
* This method cannot tell if the printing was successful. You must register
* a PrintJobListener
* @return false if no PrintService is selected in the dialog, true otherwise
public boolean printDocument(Doc doc, PrintService ps) throws PrintException {
if (ps == null)
return false;
addAllPrintServiceAttributeListeners(ps);
DocPrintJob dpj = ps.createPrintJob();
addAllPrintJobListeners(dpj);
dpj.print(doc, attributes);
return true;
public PrintService showPrintDialog() {
return ServiceUI.printDialog(gc, x, y, services, defaultService, flavor, attributes);
private void addAllPrintServiceAttributeListeners(PrintService ps) {
// add all listeners that are currently added to this object
for (int i = 0; i < psalListeners.size(); i++) {
PrintServiceAttributeListener p = (PrintServiceAttributeListener) psalListeners.get(i);
ps.addPrintServiceAttributeListener(p);
private void addAllPrintJobListeners(DocPrintJob dpj) {
// add all listeners that are currently added to this object
for (int i = 0; i < pjlListeners.size(); i++) {
PrintJobListener p = (PrintJobListener) pjlListeners.get(i);
dpj.addPrintJobListener(p);
// uncomment this also to print to a JFrame instead of a printer
/* protected class PaintableJPanel extends JPanel {
Image img;
protected PaintableJPanel() {
super();
public void setImage( Image i ) {
img = i;
public void paint( Graphics g ) {
g.drawImage( img, 0, 0, this );
Thanks
RamRam,
I have had printing problems too a year and a half ago. I used all printing apis of java and I still find that it is something java lacks. Now basically you can try autosense. To check whether your printer is capable of printing the docflavor use this PrintServiceLookup.lookupPrintServices(flavor, aset); . If it lists the printer then he can print the document otherwise he can't. I guess that is why you get the error.
Regards,
Kevin -
Javax.swing.Timer not working or event not being captured by actionPerfrmd
Here is the code:
public class nQueensEst extends JApplet implements ActionListener {
public Timer t = new Timer(1, this);
//...the actionPerformed:
if(e.getSource() == jButton1){
nRainhas=Integer.parseInt(javax.swing.JOptionPane.showInputDialog("Quantas rainhas voc? deseja?"));
t.start();
int contadorTentativas=1;
for(int i=0; i<=100; i++){
sol=new int[nRainhas];
while(!rainhas()){
jLabel1.setText(contadorTentativas +" tentativas!!!");
contadorTentativas++;
jLabel2.setText("Solu??es: "+Integer.toString(i));
t.stop();
}else if(e.getSource() == t){
System.out.println("timer");
rodadas++;
Any clue?
ThanksLet me explai the context: i had to implement a classic nQueens problem using a Grasp Algorithm and a Backtrack algorithm, then in dorder to compare them, i want to make the garap one to run find 100000 solutions and register the time it is needes, then divide by 100000. so i need the timer running and making a variable increase every millisecond from the beggining until the end of the last solution. But the timer is not generating a event or the event is not being caought by the actionPerformed.
-
Need to clear concepts in V1,V2 and V3 updates. see the scenarios
please refer to this thread and help.....
want to know whether my concepts about V1,V2 and V3 are correct or notHi John,
When we extract data from SAP using LIS, we can use V1 or V2 update. In LO extraction, we use V3 update. In most of the business scenarios, Only LO extractors are used and no LIS. As you asked,
V1 - Synchronous update
V2 - Assynchronous update
and
V3 - Assynchronous Background
We can schedule a periodic job for V3 update which runs in background without user interaction.
Regards,
Shashi -
Help needed with HTC One regarding mic problem with noise cancellation
I picked up an HTC One last week, and so far I am loving the phone. Great build quality, screen, sound - all as advertised.
However, there is one very annoying problem I am having. When I am talking to someone, I can gear them great, but they keep telling me I sound muffled or robotic. I performed some tests, and the problem appears to be something with the dual microphones and the HTC One's noise cancellation features.
Here are the tests I ran:
Typical phone call, with holding the phone as I normally do on the sides and to my ear. Call result, pretty muffled voice. I'd give the call quality a 5/10.
Help the phone as I typically do, but covered the mic hole on the back of the phone. This definatelyimproved call quality. Was louder and clearer, but not perfect. I'd rate it at 8/10.
Help the phone towards the bottom, using my hand to kind of cup the bottom directing the sound to the bottom mic. This was a further improvement in sound quality. Rating would be 9/10.
Help phone as normal, but covered the bottom mic hole. Very low volume and muffled sound. Rating a 4/10.
Talked directly into the bottom of the phone into the bottom mic. This gave perfect call quality and volume. Rating a 10/10!
Talked directly into the mic on the back of the phone. Horrible quality, couldn't hear hardly anything. Rating 0/10.
Speaker phone on, held the phone up and moved it around as I would normally use a speaker phone. Call quality was really nice. Id give it 9/10.
Speaker phone on, covered back mic hole and used speaker phone as in #7. Very bad quality, rating 1/10 for call quality.
Speaker phone on, covered bottom mic and help speaker phone in hand. Really good quality, even an improvement over test #7. Would give the call quality a 9.5/10.
Speaker phone on, placed face down on table. Volume a bit low, a little muffled. Call quality 6/10.
Speaker phone on, place face up on table. A bit worse than test #10, low volume and a bit muffled. Call quality is 5/10.
Based on these tests, I know this problem has nothing to do with the network CDMA connection. It is obvious that the noise cancellation features are a bit too aggressive, or I have some hardware problem with one or both mics.
I question wether its really a hardware mic problem, because on non-speaker phone calls, talking directly into the bottom mic gives great quality. And on Speaker phone, covering the bottom mic makes the speaker phone sound really good. That's why I think there's something going on with the "Sense Sound" noise cancellation.
Is anyone else seeing the same issues? I want to be able to hold the phone normal on a non speaker phone call and get good quality.
Looking for any tips and advice anyone can give. Is it worth exchanging for a new one, as I am still in my 14 day window.
Thanks in advance for the help!Here are some other threads that seem to be having similar issues:
http://forum.xda-developers.com/showthread.php?t=2262648
http://forum.xda-developers.com/showthread.php?t=2294532 -
Help needed in solving issue regarding shwoing data
Hello,
I am using obiee 11g,I am trying to create a report for finding the usage for each user.
Now i have auser column and usage 5 columns.
Each usage column is from 4 tables,3 from 3 diff tables and 2 columns from 1 tables.
I have a head prompt so that report gets filtered for head.
And the users belonging to head will display in the report.
Now the problem is especailly when i dont have data for a user for col4 or col5 of table4
of the report in the database.The reports starts showing "No Data Found".Even though
there are data for col1(tabe1),col2(table2),col3(table3).
I can't put ifnull because there are no data itself its not as there are null data.
So confused where am i going wrong?
Users are coming from tableA with left outer join with othere table1,table2,table3,table4 on username
Please help me out.
Any help?
ThanksHi User,
You can better go for "Save Current Customization" option available in Edit Dashboard to have user specifi default prompt values.
Rgds,
Dpka -
P965 Platinum, need to clear cmos to boot (every time)
Hi
First off, the hardware:
MSI P965 Platinum (MS-7236) Latest BIOS (1.3)
Intel Core 2 Duo E6600
Arctic Cooling Freezer 7 Pro
Corsair TWIN2X 6400 DDR2, 2048MB CL4
Asus GeForce 7950GT
Creative SB X-Fi XtremeGamer
Antec Performance One P150 Miditower (430W PSU)
The system has bin working good for the last two weeks, then two days ago the system wouldnt boot. It starts for 1 second or less (lights and fans started) and then it dies. I made no changes (hardware/software) to the system before it happend.
So I made a few searches in this forum and found someone with the same problem (not the same motherboard), someone suggested to clear the cmos, which worked, it now boots and works fine.
The problem is that I need to do that every time I want to boot the computer! Really annoying... An upgrade of the BIOS did not help.
Any ideas?Setting your CAS Latency to 4 actually makes it run at CAS Latency 3, an issue caused by the current BIOS versions. Try running your memory at CAS Latency 5-5-5-15 and 800 MHz for a while, see how it works out. You might want to run Orthos, Prime95 or Memtest to test for stability.
At what time during boot does your system hang? Any info on the D bracket?
Pressing Reset button 4 times with about 10 second intervals (if system hangs during POST) should set FSB and memory back to defaults, a little trick feature of this board that may come in handy... -
Help needed: iPhone 4 software upgrade failed many times
Hello. I've bought an iPhone 4, which its operating system is 4.3, and was prompt by iTunes about this iPhone 4 software upgrade to iOS 4.3.5. I've downloaded the software and waiting for quite some time and after the dowloading has completed, the file will be processed. After processing, there is a popup saying that somehow the software upgrade failed and said something like make sure that your connection is correct etc. Do you have any idea on how to solve this issue?
Help me, please. Thank you very much.This is asked and answered many times each day. The forum search bar is on the right side of this page.
Diasble your firewall/security software and try again. -
I'm making a dice game in Java. Here is a screenshot:
http://img.villagephotos.com/p/2005-1/941114/dice2.JPG
Basicly what you have to do it line up as much as the same amount of dice in the same row. To give you the highest total. The buttons at the bottom work and when you start the program it will calcuate all the figures and results.
However this is the bit I'm stuck on. You have to be able to click on a dice to change it over to try and get more on the total. So far on mine you cna click on a dice and it will change face however the scores will not update and i can't think of a way to get them to update after the dice has changed face. Also we need to limit the amount of dice you can change to six. Here is my code and I hope someone can help
import java.io.*;
import javax.swing.*;
import java.util.*;
/** Class to represent a dice (a die, to be pedantic about the singular).
* It will roll itself and display when requested.
public class Dice extends JButton {
// Set up random number object and seed it with the time in milliseconds
//so that we don't get the same configuration every time.
private static Random rand = new Random((new GregorianCalendar()).getTimeInMillis());
// set up file stream for dice images
private BufferedReader imageFile=null;
private final int NUMBEROFFACES = 6;//we can have other shapes of die
//now define a directory where the stored file images live
private final String diceFaceImageDirectory = "." + File.separatorChar + "bigimages";
private String diceImagePathName=null; // to be constructed
//record current face value;
private int faceValue;
//set up image name root. Image names are root with 1, 2, 3 etc appended.
private final String IMAGENAMEROOT = "dice0";
//set up file suffix, e.g., jpg, bmp, gif etc
private final String SUFFIX = "gif";
/** Provides common code for both versions of the constructor and does as much
* common setup as it can. Tries to set the die to the specified number. If it can't,
* it leaves it alone.
* Uses the class number faceValue to set the die.
private void setUpDice() {
//set up filestring for all but the number part of the dice image
//use the supplied separator instead of // or \\, to ensure
// platform independence
diceImagePathName = diceFaceImageDirectory + File.separatorChar
+ IMAGENAMEROOT;
if(faceValue >0 && faceValue <= NUMBEROFFACES) {
ImageIcon icon = new ImageIcon(diceImagePathName + faceValue + "." + SUFFIX);
//and put it on the button
this.setIcon(icon);
//and repaint in case
this.repaint();
//else do nothing
/** Creates a dice object with a random face showing. The number of faces is determined
* by an internal private setting, which defaults to 6
public Dice() {
//seed each one with the time in millisec. Otherwise, the random
//number sequence is the same for each die.
//rand = new Random((new GregorianCalendar()).getTimeInMillis());
//The problem is that the system is so fast that we get the same time in milliseconds
//for all the dice, and they all yield the same sequence. That is, a six will always
//next be, say, a 1, and so on.
//We can either try to get the seeding down to nanos (can't) or put in
// a time delay (daft)
//or set up just one random sequence generator for all dice instead
//of each having its own individual one.
//This would mean having rand as a static variable.
//set faceNumber and then call the setup
setFaceNumberOnly( rand.nextInt(NUMBEROFFACES) + 1);//set face number within range
setUpDice();
/**Creates a dice object with the specified face showing. If requested
* number is out of range, a random face is shown.
* @param faceNumber the face to show
public Dice (int faceNumber) {
if (faceNumber >0 && faceNumber <= NUMBEROFFACES) { //ok
setFaceNumberOnly(faceNumber);
else { //get random value
setFaceNumberOnly( rand.nextInt(NUMBEROFFACES) + 1);
setUpDice();
/** Displays the requested face. If requested face number is out of range,
* the display is unchanged.
* @param faceNumber the face to show
public void displayFace (int faceNumber) {
if(faceNumber >0 && faceNumber <=NUMBEROFFACES) { //ok
ImageIcon icon = new ImageIcon(diceImagePathName + faceNumber + "." + SUFFIX);
//and put it on the button
this.setIcon(icon);
this.repaint(); // need to repaint since screeen already drawn nowfac
//else leave it
/** Tells us which face is showing on the dice at the moment.
* The number of faces is in the range 1..NUMBEROFFACES, where NUMBEROFFACES
* is an internal private variable, defaulting to 6.
* @return the number of the face
public int getFaceNumber(){
return faceValue;
/** Set the stored number only. Do not change display yet.
* provides a place to warn the rest of the system about changes. No checks on
* set value.
* @param number the number to set the face to
public void setFaceNumberOnly(int number) {
faceValue = number;
/** Displays a face selected at random.
public void rollDice() {
setFaceNumberOnly(rand.nextInt(NUMBEROFFACES) + 1);
setUpDice();
} import javax.swing.*;
class Harness {
//Intiate variables
int number1 = 0;
int number2 = 0;
int number3 = 0;
int number4 = 0;
int number5 = 0;
int number6 = 0;
int grandTotal = 0;
Dice d;
String result;
int resultNumber = 0;
int i;
int numberOfDice=6;
int numberOfRow =4;
JFrame frame;
JPanel panel;
Controller controller;
public Harness()
//Create frame and Panel
public void createMain()
JFrame frame = new JFrame("Dice Runner");
JPanel panel = new JPanel();
Controller controller = new Controller();
this.frame = frame;
this.panel = panel;
this.controller = controller;
//Create Dice and add to panel
public void createDice()
Dice d = new Dice();
d.addActionListener(controller);
frame.getContentPane().add(panel);
panel.add(d);
this.d = d;
//Add up number of dice on each row
public void addDice()
if (d.getFaceNumber() == 1)
number1 = number1 + 1;
this.number1 = number1;
if (d.getFaceNumber() == 2)
number2 = number2 + 1;
this.number2 = number2;
if (d.getFaceNumber() == 3)
number3 = number3 + 1;
this.number3 = number3;
if (d.getFaceNumber() == 4)
number4 = number4 + 1;
this.number4 = number4;
if (d.getFaceNumber() == 5)
number5 = number5 + 1;
this.number5 = number5;
if (d.getFaceNumber() == 6)
number6 = number6 + 1;
this.number6 = number6;
//Compare numbers on each row, to detirmine which is higher
public void compareDice()
if(number1 >= number2 & number1 >= number3 &
number1 >= number4 & number1 >= number5 & number1 >= number6)
String result = ("" + number1);
int resultNumber = number1;
this.resultNumber = resultNumber;
this.result = result;
this.number1 = number1;
if (number2 >= number1 & number2 >= number3 &
number2 >= number4 & number2 >= number5 & number2 >= number6)
result = ("" + number2);
int resultNumber = number2;
this.resultNumber = resultNumber;
this.result = result;
this.number2 = number2;
if (number3 >= number1 & number3 >= number2 &
number3 >= number4 & number3 >= number5 &
number3 >= number6)
result = ("" + number3);
int resultNumber = number3;
this.resultNumber = resultNumber;
this.result = result;
this.number3 = number3;
if (number4 >= number1 & number4 >= number3 &
number4 >= number2 & number4 >= number5 & number4 >= number6)
result = ("" + number4);
int resultNumber = number4;
this.resultNumber = resultNumber;
this.result = result;
this.number4 = number4;
if (number5 >= number1 & number5 >= number3 &
number5 >= number4 & number5 >= number2 & number5 >= number6)
result = ("" + number5);
int resultNumber = number5;
this.resultNumber = resultNumber;
this.result = result;
this.number5 = number5;
if (number6 >= number1 & number6 >= number3 &
number6 >= number4 & number6 >= number2 & number6 >= number5)
result = ("" + number6);
int resultNumber = number6;
this.resultNumber = resultNumber;
this.result = result;
this.number6 = number6;
//Store Row Values
public void storeRowValues()
if (i==0)
int row1 = resultNumber;
grandTotal = grandTotal +row1;
this.resultNumber = resultNumber;
if(i==1)
int row2 = resultNumber;
grandTotal = grandTotal +row2;
this.resultNumber = resultNumber;
if(i==2)
int row3 = resultNumber;
grandTotal = grandTotal +row3;
this.resultNumber = resultNumber;
if(i==3)
int row4 = resultNumber;
grandTotal = grandTotal +row4;
this.resultNumber = resultNumber;
//Create and Add label and TextField
public void createRowResults()
JLabel total = new JLabel("Total");
JTextField rowResult = new JTextField(" " +result + " ");
rowResult.setEditable(false);
panel.add(total);
panel.add(rowResult);
this.panel = panel;
//Reset values for next row
public void resetNumbers()
number1 = 0;
number2 = 0;
number3 = 0;
number4 = 0;
number5 = 0;
number6 = 0;
//Create Buttons At Bottom
public void createBottom()
JButton restart = new JButton("Open New Game");
Restart restartGame = new Restart();
restart.addActionListener(restartGame);
panel.add(restart);
JLabel label = new JLabel("Grand Total");
JTextField total = new JTextField(" " +grandTotal + " ");
total.setEditable(false);
panel.add(label);
panel.add(total);
JButton exit = new JButton("Exit");
exit.addActionListener(controller);
panel.add(exit);
//setSize
public void setSize()
frame.setSize(850,550);
frame.setVisible(true);
//Run program
public void run()
//Create frame and Panel
createMain();
//Start loop for adding rows
for(int i=0; i<numberOfRow; i++) {
this.i =i;
//Start loop for adding dice
for(int j=0; j<numberOfDice; j++)
//Create Dice and add to panel
createDice();
//Add up number of dice on each row
addDice();
} //End loop to add dice to the row
//Compare numbers on each row, to detirmine which is higher
compareDice();
//Store Row Values
storeRowValues();
//Create and Add label and TextField
createRowResults();
//Reset values for next row
resetNumbers();
} //End the loop for adding rows
//Create Buttons At Bottom
createBottom();
//Set Size
setSize();
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Controller implements ActionListener{
public Controller(){
public void actionPerformed(ActionEvent ae){
if(ae.getSource() instanceof Dice){
Harness h = new Harness();
Dice d = (Dice) ae.getSource();
System.out.println("Dice before roll = " +d.getFaceNumber());
d.rollDice();
System.out.println("Dice after roll = " +d.getFaceNumber() + "\n");
else if(ae.getSource() instanceof JButton){
JButton j = (JButton) ae.getSource();
System.exit(-1);
} import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Restart implements ActionListener{
public Restart(){
public void actionPerformed(ActionEvent ae){
if(ae.getSource() instanceof JButton){
JButton j = (JButton) ae.getSource();
Harness h = new Harness();
h.run();
* Write a description of class DiceRunner here.
* @author (your name)
* @version (a version number or a date)
public class DiceRunner
public static void main(String[] args)
Harness harness = new Harness();
harness.run();
} also we cannot alter the Dice class at all and any help at all and suggestions and I will be very greatful.
Just to be clear using the d.rollDice(); in the Controller class does update the image and shows a different dice face but does not update the scores and i do not know why.You didn't program this did you..either class?
Inside of Dice there isn't any place where you get an update to your Harness class, specifically your number1 .. number 6. You need a number to update this with and good candidate would be faceValue in Dice that can be read through the accessor d.getFaceValue(). -
Hi guys, I need help in debugging this code I made, which is a GUI minesweeper. Its extremely buggy...I particularly need help fixing the actionListener part of the code as everytime I press a button on the GUI, an exception occurs.
help please!
package minesweeperGUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MinesweeperGUI implements ActionListener
//Declaration of attributes
static int length = 0;
JMenuItem menuItemNew = new JMenuItem();
JRadioButtonMenuItem rbEasy = new JRadioButtonMenuItem();
JRadioButtonMenuItem rbHard = new JRadioButtonMenuItem();
JMenuItem menuItemExit = new JMenuItem();
JButton buttonReset = new JButton();
JButton buttonGrid[][] = null;
JFrame frame = new JFrame();
int getBombsTotal = 0;
JLabel setBombsLabel = new JLabel();
int a = 0;
int b = 0;
//No constructor created. Uses default constructor
//Create the menu bar
public JMenuBar newMenuBar()
//Sets up the menubar
JMenuBar menuBar = new JMenuBar();
//Sets up the Game menu with choice of new, grid size, and exit
JMenu menu = new JMenu ("Game");
menuBar.add (menu);
menuItemNew = new JMenuItem ("New");
menuItemNew.addActionListener (this);
menu.add (menuItemNew);
menu.addSeparator();
//Sets up sub-menu for grid size with choice of easy and hard radio buttons
JMenu subMenu = new JMenu ("Grid Size");
rbEasy = new JRadioButtonMenuItem ("Easy: 5x5 grid");
rbEasy.addActionListener (this);
subMenu.add (rbEasy);
rbHard = new JRadioButtonMenuItem ("Hard: 10x10 grid");
rbHard.addActionListener (this);
subMenu.add (rbHard);
menu.add (subMenu);
menu.addSeparator();
menuItemExit = new JMenuItem ("Exit");
menuItemExit.addActionListener (this);
menu.add (menuItemExit);
return menuBar;
//Setting up of Bomb Grid
public int [][] setGrid (int length)
int grid[][] = null;
grid = new int[length][length];
for (int i = 0; i < length; i++)
for (int j = 0; j < length; j++)
grid[i][j] = ((int)Math.round(Math.random() * 10))% 2;
return grid;
//Setting up of the of the graphical bomb grid
public JButton[][] setButtonGrid (int length)
JButton buttonGrid[][] = null;
buttonGrid = new JButton[length][length];
for (int i = 0; i < length; i++)
for (int j = 0; j < length; j++)
buttonGrid[i][j] = new JButton();
return buttonGrid;
//Setting up of a way to count the total number of bombs in the bomb grid
public int getBombsTotal (int length, int setGrid[][])
int bombsTotal = 0;
for (int i = 0; i < length; i++)
for (int j = 0; j < length; j++)
if (setGrid[i][j] == 1)
bombsTotal += 1;
return bombsTotal;
//Create a label for number of bombs left
public JLabel setBombsLabel (int getBombsTotal)
JLabel bombsLabel = new JLabel(String.valueOf (getBombsTotal) + " Bombs Left");
return bombsLabel;
//Setting up a way to count the number of bombs around a button
public String setBombs (int length, int setGrid[][], int x, int y)
int bombs[][] = new int[length][length];
String bombsString = null;
for (int i = 0; i < length; i++)
for (int j = 0; j < length; j++)
if (i == 0 && j == 0)
bombs[i][j] = setGrid[i][j+1] + setGrid[i+1][j] +
setGrid[i+1][j+1];
else if (i ==0 && j == (length - 1))
bombs[i][j] = setGrid[i][j-1] + setGrid[i+1][j-1] +
setGrid[i+1][j];
else if (i == (length - 1) && j == 0)
bombs[i][j] = setGrid[i-1][j] + setGrid[i-1][j+1] +
setGrid[i][j+1];
else if (i == (length - 1) && j == (length - 1))
bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
setGrid[i][j-1];
else if (i == 0 && j != 0 && j != (length - 1))
bombs[i][j] = setGrid[i][j-1] + setGrid[i][j+1] +
setGrid[i+1][j-1] + setGrid[i+1][j] +
setGrid[i+1][j+1];
else if (i == (length - 1) && j != 0 && j != (length - 1))
bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
setGrid[i-1][j+1] + setGrid[i][j-1] +
setGrid[i][j+1];
else if (i != 0 && i != (length - 1) && j == 0)
bombs[i][j] = setGrid[i-1][j] + setGrid[i-1][j+1] +
setGrid[i][j+1] + setGrid[i+1][j] +
setGrid[i+1][j+1];
else if (i != 0 && i != (length - 1) && j == (length - 1))
bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
setGrid[i][j-1] + setGrid[i+1][j-1] +
setGrid[i+1][j];
else
bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
setGrid[i-1][j+1] + setGrid[i][j-1] +
setGrid[i][j+1] + setGrid[i+1][j-1] +
setGrid[i+1][j] + setGrid[i+1][j+1];
bombsString = String.valueOf (bombs[x][y]);
return bombsString;
//create the panel for the bombs label and reset button
public JPanel newTopPanel(int length)
int setGridNew [][] = null;
setGridNew = new int[length][length];
int getBombsTotalNew = 0;
JLabel setBombsLabelNew = new JLabel();
setGridNew = setGrid (length);
getBombsTotalNew = getBombsTotal (length, setGridNew);
setBombsLabelNew = setBombsLabel (getBombsTotalNew);
JPanel topPanel = new JPanel ();
topPanel.setLayout (new BorderLayout (50,50));
JLabel bombsLabel = new JLabel ();
bombsLabel = setBombsLabelNew;
topPanel.add (bombsLabel, BorderLayout.WEST);
buttonReset = new JButton("Reset");
buttonReset.addActionListener (this);
topPanel.add (buttonReset, BorderLayout.CENTER);
return topPanel;
//create the panel for the play grids
public JPanel newBottomPanel(int length)
JButton setButtonGridNew[][] = null;
setButtonGridNew = new JButton [length][length];
setButtonGridNew = setButtonGrid (length);
JPanel bottomPanel = new JPanel ();
bottomPanel.setLayout (new GridLayout (length, length));
buttonGrid = new JButton[length][length];
for (a = 0; a < length; a++)
for (b = 0; b < length; b++)
buttonGrid[a] = setButtonGridNew[a][b];
buttonGrid[a][b].addActionListener (this);
bottomPanel.add (buttonGrid[a][b]);
return bottomPanel;
//Overiding of abstract method actionPerformed
public void actionPerformed(ActionEvent e)
if (e.getSource() == menuItemNew)
launchFrame(length);
else if (e.getSource() == menuItemExit)
frame.setVisible (false);
System.exit(0);
else if (e.getSource() == rbEasy)
length = 5;
launchFrame(length);
else if (e.getSource() == rbHard)
length = 10;
launchFrame(length);
else if (e.getSource() == buttonReset)
launchFrame(length);
else if (e.getSource() == buttonGrid[a][b])
int setGridNew [][] = null;
setGridNew = new int[length][length];
JButton bombButton [][] = null;
bombButton = new JButton [length][length];
String bombString [][] = null;
bombString = new String[length][length];
setGridNew = setGrid (length);
bombString[a][b] = setBombs (length, setGridNew, a, b);
bombButton[a][b] = new JButton (bombString[a][b]);
if (setGridNew[a][b] == 0)
buttonGrid[a][b] = bombButton[a][b];
getBombsTotal--;
JLabel setBombsLabelNew = new JLabel();
setBombsLabelNew = setBombsLabel (getBombsTotal);
else if (setGridNew[a][b] == 1 )
buttonGrid[a][b] = new JButton("x");
JOptionPane.showMessageDialog (null, "Game Over. You hit a Bomb!");
System.exit(0);
//create the content pane
public Container newContentPane(int length)
JPanel topPanel = new JPanel();
JPanel bottomPanel = new JPanel();
topPanel = newTopPanel(length);
bottomPanel = newBottomPanel (length);
JPanel contentPane = new JPanel();
contentPane.setOpaque (true);
contentPane.setLayout (new BorderLayout(50,50));
contentPane.add (topPanel, BorderLayout.NORTH);
contentPane.add (bottomPanel, BorderLayout.CENTER);
return contentPane;
public void launchFrame (int length)
//Makes sure we have nice window decorations
JFrame.setDefaultLookAndFeelDecorated(true);
//Sets up the top-level window
frame = new JFrame ("Minesweeper");
//Exits program when the closed button is clicked
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
Container contentPane = new Container();
menuBar = newMenuBar();
contentPane = newContentPane (length);
//Sets up the menu bar and content pane
frame.setJMenuBar (menuBar);
frame.setContentPane (contentPane);
//Displays the window
frame.pack();
frame.setVisible (true);
public static void main (String args[])
//Default length is 5
length = 5;
MinesweeperGUI minesweeper = new MinesweeperGUI();
minesweeper.launchFrame(length);hi, thanks. that removed the exception; although now the buttons action listener won't work :(
here is the revised code:
To anyone out there, can you guys run this code and help me debug it?
I'm really desperate as this is a school project of mine and the deadline is 7 hours away. I have already been working on it for 3 days, but the program is still very buggy.
thanks!
/* Oliver Ian C. Wee 04-80112
* CS12 MHRU
* Machine Problem 2
package minesweeperGUI;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MinesweeperGUI implements ActionListener
//Declaration of attributes
static int length = 0;
JMenuItem menuItemNew = new JMenuItem();
JRadioButtonMenuItem rbEasy = new JRadioButtonMenuItem();
JRadioButtonMenuItem rbHard = new JRadioButtonMenuItem();
JMenuItem menuItemExit = new JMenuItem();
JButton buttonReset = new JButton();
JButton buttonGrid[][] = null;
JFrame frame = new JFrame();
int getBombsTotal = 0;
JLabel setBombsLabel = new JLabel();
int a = 0;
int b = 0;
//No constructor created. Uses default constructor
//Create the menu bar
public JMenuBar newMenuBar()
//Sets up the menubar
JMenuBar menuBar = new JMenuBar();
//Sets up the Game menu with choice of new, grid size, and exit
JMenu menu = new JMenu ("Game");
menuBar.add (menu);
menuItemNew = new JMenuItem ("New");
menuItemNew.addActionListener (this);
menu.add (menuItemNew);
menu.addSeparator();
//Sets up sub-menu for grid size with choice of easy and hard radio buttons
JMenu subMenu = new JMenu ("Grid Size");
ButtonGroup bg = new ButtonGroup();
rbEasy = new JRadioButtonMenuItem ("Easy: 5x5 grid");
bg.add (rbEasy);
rbEasy.addActionListener (this);
subMenu.add (rbEasy);
rbHard = new JRadioButtonMenuItem ("Hard: 10x10 grid");
bg.add (rbHard);
rbHard.addActionListener (this);
subMenu.add (rbHard);
menu.add (subMenu);
menu.addSeparator();
menuItemExit = new JMenuItem ("Exit");
menuItemExit.addActionListener (this);
menu.add (menuItemExit);
return menuBar;
//Setting up of Bomb Grid
public int [][] setGrid (int length)
int grid[][] = null;
grid = new int[length][length];
for (int i = 0; i < length; i++)
for (int j = 0; j < length; j++)
grid[i][j] = ((int)Math.round(Math.random() * 10))% 2;
return grid;
//Setting up of the of the graphical bomb grid
public JButton[][] setButtonGrid (int length)
JButton buttonGrid[][] = null;
buttonGrid = new JButton[length][length];
for (int i = 0; i < length; i++)
for (int j = 0; j < length; j++)
buttonGrid[i][j] = new JButton();
return buttonGrid;
//Setting up of a way to count the total number of bombs in the bomb grid
public int getBombsTotal (int length, int setGrid[][])
int bombsTotal = 0;
for (int i = 0; i < length; i++)
for (int j = 0; j < length; j++)
if (setGrid[i][j] == 1)
bombsTotal += 1;
return bombsTotal;
//Create a label for number of bombs left
public JLabel setBombsLabel (int getBombsTotal)
JLabel bombsLabel = new JLabel(" " +String.valueOf (getBombsTotal) + " Bombs Left");
return bombsLabel;
//Setting up a way to count the number of bombs around a button
public String setBombs (int length, int setGrid[][], int x, int y)
int bombs[][] = new int[length][length];
String bombsString = null;
for (int i = 0; i < length; i++)
for (int j = 0; j < length; j++)
if (i == 0 && j == 0)
bombs[i][j] = setGrid[i][j+1] + setGrid[i+1][j] +
setGrid[i+1][j+1];
else if (i ==0 && j == (length - 1))
bombs[i][j] = setGrid[i][j-1] + setGrid[i+1][j-1] +
setGrid[i+1][j];
else if (i == (length - 1) && j == 0)
bombs[i][j] = setGrid[i-1][j] + setGrid[i-1][j+1] +
setGrid[i][j+1];
else if (i == (length - 1) && j == (length - 1))
bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
setGrid[i][j-1];
else if (i == 0 && j != 0 && j != (length - 1))
bombs[i][j] = setGrid[i][j-1] + setGrid[i][j+1] +
setGrid[i+1][j-1] + setGrid[i+1][j] +
setGrid[i+1][j+1];
else if (i == (length - 1) && j != 0 && j != (length - 1))
bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
setGrid[i-1][j+1] + setGrid[i][j-1] +
setGrid[i][j+1];
else if (i != 0 && i != (length - 1) && j == 0)
bombs[i][j] = setGrid[i-1][j] + setGrid[i-1][j+1] +
setGrid[i][j+1] + setGrid[i+1][j] +
setGrid[i+1][j+1];
else if (i != 0 && i != (length - 1) && j == (length - 1))
bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
setGrid[i][j-1] + setGrid[i+1][j-1] +
setGrid[i+1][j];
else
bombs[i][j] = setGrid[i-1][j-1] + setGrid[i-1][j] +
setGrid[i-1][j+1] + setGrid[i][j-1] +
setGrid[i][j+1] + setGrid[i+1][j-1] +
setGrid[i+1][j] + setGrid[i+1][j+1];
bombsString = String.valueOf (bombs[x][y]);
return bombsString;
//create the panel for the bombs label and reset button
public JPanel newTopPanel(int length)
int setGridNew [][] = null;
setGridNew = new int[length][length];
int getBombsTotalNew = 0;
JLabel setBombsLabelNew = new JLabel();
setGridNew = setGrid (length);
getBombsTotalNew = getBombsTotal (length, setGridNew);
setBombsLabelNew = setBombsLabel (getBombsTotalNew);
JPanel topPanel = new JPanel ();
topPanel.setLayout (new BorderLayout (20,20));
JLabel bombsLabel = new JLabel ();
bombsLabel = setBombsLabelNew;
topPanel.add (bombsLabel, BorderLayout.WEST);
buttonReset = new JButton("Reset");
buttonReset.addActionListener (this);
topPanel.add (buttonReset, BorderLayout.CENTER);
return topPanel;
//create the panel for the play grids
public JPanel newBottomPanel(int length)
JButton setButtonGridNew[][] = null;
setButtonGridNew = new JButton [length][length];
setButtonGridNew = setButtonGrid (length);
JPanel bottomPanel = new JPanel ();
bottomPanel.setLayout (new GridLayout (length, length));
buttonGrid = new JButton[length][length];
for (int i = 0; i < length; i++)
for (int j = 0; j < length; j++)
buttonGrid[i][j] = setButtonGridNew[i][j];
buttonGrid[i][j].addActionListener (this);
bottomPanel.add (buttonGrid[i][j]);
return bottomPanel;
//Overiding of abstract method actionPerformed
public void actionPerformed(ActionEvent e)
if (e.getSource() == menuItemNew)
closeFrame();
launchFrame(length);
else if (e.getSource() == menuItemExit)
frame.setVisible (false);
System.exit(0);
else if (e.getSource() == rbEasy)
closeFrame();
length = 5;
launchFrame(length);
else if (e.getSource() == rbHard)
closeFrame();
length = 10;
launchFrame(length);
else if (e.getSource() == buttonReset)
closeFrame();
launchFrame(length);
else if (e.getSource() == buttonGrid[a])
int setGridNew [][] = null;
setGridNew = new int[length][length];
JButton bombButton [][] = null;
bombButton = new JButton [length][length];
String bombString [][] = null;
bombString = new String[length][length];
setGridNew = setGrid (length);
for (int i = 0; i < length; i++)
for (int j = 0; j < length; j++)
bombString[i][j] = setBombs (length, setGridNew, i, j);
bombButton[i][j] = new JButton (bombString[i][j]);
if (setGridNew[a][b] == 0)
buttonGrid[a][b] = bombButton[a][b];
getBombsTotal--;
JLabel setBombsLabelNew = new JLabel();
setBombsLabelNew = setBombsLabel (" " String.valueOf (getBombsTotal) " Bombs Left");
else if (setGridNew[a][b] == 1 )
buttonGrid[a][b] = new JButton("x");
JOptionPane.showMessageDialog (null, "Game Over. You hit a Bomb!");
System.exit(0);
//create the content pane
public Container newContentPane(int length)
JPanel topPanel = new JPanel();
JPanel bottomPanel = new JPanel();
topPanel = newTopPanel(length);
bottomPanel = newBottomPanel (length);
JPanel contentPane = new JPanel();
contentPane.setOpaque (true);
contentPane.setLayout (new BorderLayout(5,5));
contentPane.add (topPanel, BorderLayout.NORTH);
contentPane.add (bottomPanel, BorderLayout.CENTER);
return contentPane;
public void closeFrame ()
frame = new JFrame ("Minesweeper");
frame.dispose();
public void launchFrame (int length)
//Makes sure we have nice window decorations
JFrame.setDefaultLookAndFeelDecorated(true);
//Sets up the top-level window
frame = new JFrame ("Minesweeper");
//Exits program when the closed button is clicked
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
Container contentPane = new Container();
menuBar = newMenuBar();
contentPane = newContentPane (length);
//Sets up the menu bar and content pane
frame.setJMenuBar (menuBar);
frame.setContentPane (contentPane);
//Displays the window
frame.pack();
frame.setVisible (true);
public static void main (String args[])
//Default length is 5
length = 5;
MinesweeperGUI minesweeper = new MinesweeperGUI();
minesweeper.launchFrame(length); -
Algorithm help needed for electrically charged metallic sphere simulation
I am making a simulation program using Java which takes into account the gravity, air resistance as well as electrical forces of the two charged metal spheres.
The user can input/select:
1) The initial velocity for each metallic sphere
2) The variables in g = MG/(r+h)^2 Newton's law of gravitation (so gravity is SLIGHTLY different per metallic sphere depending on the height from the surface of the Earth - assuming the user chooses Earth)
3) Metallic spheres' charges
4) Dielectric constant
5) Separation distance
6) Drag coefficient
7) Radius of metallic spheres
8) Horizontal position
9) Mass of metallic spheres
10) Vacuum
11) Air
12) Other medium
My question is: How do I make it so that these change over time where the time is determined by a javax.swing.Timer object? In other words, I want the Timer object to change at least one thing which will then change something else and cause a chain reaction such that when the metallic spheres are drawn, there is motion hence it becomes an animation.
I just need the initial push to get started because I haven't yet "seen the light". So I would appreciate it very much if someone could help me see how to change the very first datum that will cause a domino-effect and then the animation.
Thanks in advance!Ok so this is what I'm planning to do but just wanted to know if it's the best way to go about it:
a = v/s => g = v/s (where g is not a constant but varies very slightly)
and then v = gs and update the velocity every 100 milliseconds. (0.1 seconds).
before re-updating the velocity again I am planning to update the position (I'm not thinking about other stuff yet) based on the velocity via:
v = p/s => vs = p
where for all cases s is seconds s = s+100milliseconds if whoever you are reading this right now didn't know for whatever reason. -
KeyListener Help Needed for Tetris Game!
* Tetris - Java Enhacned
* By: Kunnel Zachariah, Johnathan Smith, Johnathan Adkins
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.Timer;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import static java.lang.Character.*;
import java.awt.*;
import java.awt.image.*;
import java.applet.*;
import java.lang.Math;
import java.lang.System;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.awt.event.KeyAdapter;
public class TetrisMain extends JFrame implements KeyListener
int s;
int p;
int xPos;
int yPos;
int level = 1;
int lines = 0;
int score = 0;
int switchPiece;
private boolean[] keys;
private int SLEEP = 50; //bigger # = slower animation
private Timer timer;
int bologna = 11;
int posX[], posY[];
Color color;
boolean isSquare = false;
public TetrisMain()
setSize(550,710);
setBackground(Color.black);
setVisible(true);
getContentPane();
public static void main( String args[] )
TetrisMain pongLab = new TetrisMain();
public void paint (Graphics g)
s=0;
keys = new boolean[4];
this.addKeyListener(this);
g.setColor(Color.blue);
g.fillRect(0,0,550,710);
g.setColor(Color.black);
g.fillRect(0,0,460,600);
g.setColor(Color.blue);
g.setColor (Color.black);
g.setFont(new Font("Helvetica",Font.BOLD,14));
g.drawString ("Level: " + level, 485, 40);
g.drawString ("Lines: " + lines, 485, 80);
g.drawString ("Score: " + score, 485, 120);
ActionListener paintCaller = new ActionListener(){
public void actionPerformed(ActionEvent event)
repaint(); //recalls paint every SLEEP milliseconds
timer = new Timer(SLEEP, paintCaller);
timer.start();
while (bologna <= 30)
if ( keys[0] == true )
//move left paddle up and draw it on the window
s+=3;
if ( keys[1] == true )
//move left paddle down and draw it on the window
p+=3;
if ( keys[2] == true )
s-=3;
if ( keys[3] == true )
p-=3;
displayRandomPiece(g);
bologna++;
public void drawGridVertical(Graphics g)
for(xPos = 0; xPos <=460; xPos+=23)
for(yPos=0; yPos <=600; yPos+=23)
g.drawLine(xPos,yPos,xPos,yPos);
public void drawBlock(Graphics g)
ImageIcon animatedIcon1 = new ImageIcon("untitled.gif");
for(p =0; p <=530; p+=2)
animatedIcon1.paintIcon(this,g,s,p);
delay(100000);
public void drawTpiece(Graphics g)
ImageIcon animatedIcon = new ImageIcon("tpiece.gif");
for(p =0; p <=530; p+=2)
animatedIcon.paintIcon(this,g,s,p);
delay(100000);
public void drawZigZagpiece(Graphics g)
ImageIcon animatedIcon2 = new ImageIcon("zigzagpiece.gif");
for(p =0; p <=530; p+=2)
animatedIcon2.paintIcon(this,g,s,p);
delay(100000);
public void Rectanglepiece(Graphics g)
ImageIcon animatedIcon3 = new ImageIcon("rectangle.gif");
for(p =0; p <=530; p+=2)
animatedIcon3.paintIcon(this,g,s,p);
delay(100000);
public void Unknownpiece(Graphics g)
ImageIcon animatedIcon4 = new ImageIcon("unknownpiece.gif");
for(p =0; p <=530; p+=2)
animatedIcon4.paintIcon(this,g,s,p);
delay(100000);
public void otherZigZagpiece(Graphics g)
ImageIcon animatedIcon5 = new ImageIcon("otherzigzagpiece.gif");
for(p =0; p <=530; p+=2)
animatedIcon5.paintIcon(this,g,s,p);
delay(100000);
public void otherUnknownpiece(Graphics g)
ImageIcon animatedIcon6 = new ImageIcon("otherunknownpiece.gif");
for(p =0; p <=530; p+=2)
animatedIcon6.paintIcon(this,g,s,p);
delay(100000);
public static void delay(double n)
for (double x = 0; x <= n; x += .01);
public boolean keyPressed(Event e, int key)
if (key == Event.LEFT)
s=-1;
else if (key == Event.RIGHT)
s+=1;
else if (key == Event.UP)
p-=1;
else if (key == Event.DOWN)
// fast=true;
else if (key == Event.ESCAPE)
// ingame=false;
return true;
public void keyPressed(KeyEvent e)
System.out.println("keypressed");
switch(toUpperCase(e.getKeyChar()))
case 'W' : keys[0]=true;System.out.println("W keypressed"); break;
case 'Z' : keys[1]=true; System.out.println("z keypressed");break;
case 'I' : keys[2]=true; System.out.println("i keypressed");break;
case 'M' : keys[3]=true; System.out.println("m keypressed");break;
public void keyReleased(KeyEvent e)
System.out.println("released");
switch(toUpperCase(e.getKeyChar()))
case 'W' : keys[0]=true; System.out.println("W realeased");break;
case 'Z' : keys[1]=true; System.out.println("Z realeased");break;
case 'I' : keys[2]=true; System.out.println("i realeased");break;
case 'M' : keys[3]=true; System.out.println("m realeased");break;
public void keyTyped(KeyEvent e)
//no code needed here
public void displayRandomPiece(Graphics g)
Random rand = new Random();
int c = rand.nextInt((7)+1);
switch(c)
case 1:
drawBlock(g);
break;
case 2:
drawTpiece(g);
break;
case 3:
drawZigZagpiece(g);
break;
case 4:
Rectanglepiece(g);
break;
case 5:
Unknownpiece(g);
break;
case 6:
otherZigZagpiece(g);
break;
case 7:
otherUnknownpiece(g);
break;
}This is my code so far for Tetris. I am having issues with my keylisteners! I keep pressing the specified keys and the println statements wont show up or the piece wont move! i really need major help. can anyone give me some advice
Much Thanks,
Chris!http://forum.java.sun.com/thread.jspa?threadID=5175447
Don't double post! No help for you!
Maybe you are looking for
-
I have managed to sync a ringtone to my ne i phone 5C but the volume is way too soft. The sound is great on my computer but hard to hear at all on the phone. I have tried turning up the volume button on the phone but it doesn' do anything for the ri
-
I bought a film on iTunes and whenever I try and play it it says "your computer is not authorised to play this" and so I type my password in and it says "your computer is already authorised" and then doesn't play the film. Can anyone help?
-
Slow loading of reports and forms
hi, i have created forms and reports- but they take atleat a minute to load when i goto the customize form of any report- the report running itself does not take time.. i have created the WWA_MODULE_BINDINGS_IDX1 and WWA_MODULE_LOV_BINDINGS_IDX1 inde
-
I receive the following error from the Jclient statement : JUMetaObjectManager.setBaseErrorHandler(new JUErrorHandlerDlg()); Warning(100,27): method setBaseErrorHandler(oracle.jbo.uicli.binding.JUErrorHandler) in class oracle.jbo.uicli.mom.JUMetaObje
-
Can an Advanced Action Launch another Advanced Action (or more than one)?
Hi Everyone, I was wondering if an Advanced action could launch another Advanced Action? I have a custom quiz results page and I want several different Advanced Actions to run when the learner enters the page. Is this possible? paul...