|
THanks a lot Bro, u really made my day...
U must be a real guru at this, more grease to your elbows
i'll get back to u soon but thanks....
If at first you don't succeed, you're not Abraham Lincoln.
|
|
|
|
|
how can i add the facebook bottom toolbar to my project?is there any api for that toolbar?
|
|
|
|
|
This has nothing to do with Java.
Use the CSS attribute 'position' with the value 'fixed'. Then position it using the 'top', 'bottom', 'left', 'right' attributes.
If at first you don't succeed, you're not Chuck Norris.
|
|
|
|
|
Good Day,
i have a problem with j2me programming. i was trying to implement a mp3 player using wireless toolkit, i had this error message. pls can anyone interprete it.
Creating project "player"
Place Java source files in "C:\WTK25\apps\player\src"
Place application resource files in "C:\WTK25\apps\player\res"
Place application library files in "C:\WTK25\apps\player\lib"
Settings updated
Project settings saved
Building "player"
C:\WTK25\apps\player\src\Player.java:91: reached end of file while parsing
}
^
1 error
com.sun.kvem.ktools.ExecutionException
Build failed
Running with storage root DefaultColorPhone
Running with locale: English_United States.1252
Unable to create MIDlet player
java.lang.ClassNotFoundException: player
at com.sun.midp.midlet.MIDletState.createMIDlet(+29)
at com.sun.midp.midlet.Selector.run(+22)
Unable to create MIDlet player
java.lang.ClassNotFoundException: player
at com.sun.midp.midlet.MIDletState.createMIDlet(+29)
at com.sun.midp.midlet.Selector.run(+22)
Execution completed.
3472532 bytecodes executed
1028 thread switches
1647 classes in the system (including system classes)
17853 dynamic objects allocated (537092 bytes)
1 garbage collections (0 bytes collected)
|
|
|
|
|
Hello,
Maybe you didn't finish properly your braces {} then the compiler couldn't complete the parsing of your "Player" class.
Good luck!
|
|
|
|
|
is there anything wrong with this code?
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
import javax.microedition.io.*;
public class FileConnection extends MIDlet implements CommandListener {
private Command exit, start;
private Display display;
private Form form;
public FileConnection ()
{
display = Display.getDisplay(this);
exit = new Command("Exit", Command.EXIT, 1);
start = new Command("Start", Command.EXIT, 1);
form = new Form("Write To File");
form.addCommand(exit);
form.addCommand(start);
form.setCommandListener(this);
}
public void startApp() throws MIDletStateChangeException
{
display.setCurrent(form);
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void commandAction(Command command, Displayable displayable)
{
if (command == exit)
{
destroyApp(false);
notifyDestroyed();
}
else if (command == start)
{
try
{
OutputConnection connection = (OutputConnection)
Connector.open("file://c:/myfile.txt;append=true", Connector.WRITE );
OutputStream out = connection.openOutputStream();
PrintStream output = new PrintStream( out );
output.println( "This is a test." );
out.close();
connection.close();
Alert alert = new Alert("Completed", "Data Written", null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
catch( ConnectionNotFoundException error )
{
Alert alert = new Alert(
"Error", "Cannot access file.", null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
catch( IOException error )
{
Alert alert = new Alert("Error", error.toString(), null, null);
alert.setTimeout(Alert.FOREVER);
alert.setType(AlertType.ERROR);
display.setCurrent(alert);
}
}
}
|
|
|
|
|
Just add an extra } at the end.
|
|
|
|
|
this is the error i have after adding } at the end.
Project "player" loaded
Running with storage root DefaultColorPhone
Running with locale: English_United States.1252
Unable to create MIDlet player
java.lang.ClassNotFoundException: player
at com.sun.midp.midlet.MIDletState.createMIDlet(+29)
at com.sun.midp.midlet.Selector.run(+22)
Unable to create MIDlet player
java.lang.ClassNotFoundException: player
at com.sun.midp.midlet.MIDletState.createMIDlet(+29)
at com.sun.midp.midlet.Selector.run(+22)
|
|
|
|
|
Hi,
Looks like you have an error in your project configuration. Maybe it wants to load a class named "player". But it seems that "player" is the name of your project, not of a class.
If your development tool allows it then generate a sample MIDlet application so you can have a working example to start with.
I'd recommend NetBeans but Eclipse is very good too.
Cheers!!
|
|
|
|
|
Hello,
I am a genuine novice with Java. I have written the following code to accept a passed variable and open a window designed to show an enlarged graphic. It is giving the following error, which seems to indicate that the path is incorrect, however, it is the exact path is used to display the original graphic. Here is the error, followed by the code.
The Error:
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /TB_09_Online/~/GearsAds/gears33.png
The Code:
<script type="text/javascript">
function OpenLargeWindow(image)
{
window.open("~/GearsAds/" + image, "", " width=760,height=300,top=200,left=200,scrollbars=0").focus();
}
</script>
<td class="tdr2">
<asp:Image ID="Image13" runat="server" ImageUrl="~/GearsAds/gears33.png" Height="200px" Width="430px" />
<a href="javascript:OpenLargeWindow('gears33.png')">
<asp:Image ID="Image18" runat="server" ImageUrl="~/GearsAds/plus_sign.png" /></a>
</td>
Seems simple enough...I cannot understand why the path is wrong, unless it is a syntax error of some sort. Any Idea's?
Thank You for your help, Pat
|
|
|
|
|
How can i catch the Mozilla firefox closing Event using Java Script,,,
Any one Please help me....
|
|
|
|
|
|
Hi Everybody
i was looking for a solution for a memory problem in big project
the problem is that we have a very large data set that fit entirely in the memory causing OutOfHeapException , even under 8 Gigabyte of memory, so i am looking for a solution that manage the data in the heap and store them in the hard disk in case i will need them again.
thanks
|
|
|
|
|
try dividing your dataset into sub sets
|
|
|
|
|
hi ,
even if divided the data to number of sets it will still have the same problem but anyway i made my homework and i found the number of solutions. first, is force garbage collection but it still got its disadvantage and the last solution and night be the best one is to cache the object according to reference or other staff
|
|
|
|
|
Hi,
I am testing a finger print reader, does any body know how to verify the input of the fingerprint reader, Example: I would let the client touch the reader 4x then i will verfiy if the four inputs are the same.
Thanks,
Eugene
|
|
|
|
|
I guess, you should check the accompayining software with the device whether it contains any Java package. They usually provide C/C++/C# libraries.
Or you should look on the web for any general related package.
Kujtim
|
|
|
|
|
I am making a web browser in java, in that I am using URLConnection object's method getHeaderFieldKey to read cookies while trying to login to any website(say gmail or yahoo mail). When I want to send that cookie to access a secure page (Page, that can be viewed after logging in), I need to send that cookie in this second method setRequestProperty of URLConnection object. But how do I find out, what cookie name the site expects?
The following function reads the cookies.
static Hashtable theCookies = new Hashtable();
public void readCookies(URLConnection urlConn, boolean printCookies, boolean reset)
{
if (reset)
theCookies.clear();
int i=1;
String hdrKey;
String hdrString;
String aCookie;
while ((hdrKey = urlConn.getHeaderFieldKey(i)) != null) {
if (hdrKey.equals("Set-Cookie")) {
hdrString = urlConn.getHeaderField(i);
StringTokenizer st = new StringTokenizer(hdrString,",");
while (st.hasMoreTokens()) {
String s = st.nextToken();
aCookie = s.substring(0, s.indexOf(";"));
// aCookie = hdrString.substring(0, s.indexOf(";"));
int j = aCookie.indexOf("=");
if (j != -1) {
if (!theCookies.containsKey(aCookie.substring(0, j))){
// if the Cookie do not already exist then when keep it,
// you may want to add some logic to update
// the stored Cookie instead. thanks to rwhelan
theCookies.put(aCookie.substring(0, j),aCookie.substring(j + 1));
if (printCookies){
System.out.println();
System.out.println("Reading Key: " + aCookie.substring(0, j));
System.out.println(" Val: " + aCookie.substring(j + 1));
}
}
}
}
}
i++;
}
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------
What should be done before calling writeCookies function (shown below)?
Now I want to process the received cookies so as to give the server what it expects.
According to my understanding,there is a some generic way of processing the received cookies
which applies to all websites.
After processing the cookies I want to send the cookies back to the Server using the function below.
Any idea how to do the 2nd step, i.e how to process the cookies?
Any help will be highly appreciated.
--------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------
public URLConnection writeCookies(URLConnection urlConn, boolean printCookies) throws Exception
{
String cookieString = "";
Enumeration keys = theCookies.keys();
urlConn.connect();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
cookieString += key + "=" + theCookies.get(key);
if (keys.hasMoreElements())
cookieString += "; ";
}
System.out.println("\n cookies: " + cookieString);
urlConn.setRequestProperty("Cookie", cookieString);
if (printCookies)
System.out.println("Wrote cookies:\n " + cookieString);
return urlConn;
}
------------------------------------------------------------------------------------------------------END.
|
|
|
|
|
Hello Everyone,
Im using My Eclipse6.0 and have oracle10g express edition. Now actually im creating a simple web project in eclipse at first i created a package called con.avanza.test1 and added a class called TestDB1.java.
The following code is present in TestDB1.java :
package com.avanza.test1;
import java.sql.*;
import oracle.jdbc.*;
public class TestDB1
{
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
public void connect()
{
try
{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:xe","system","admin");
System.out.println("Connected.");
}
catch(Exception e)
{
e.getStackTrace();
System.out.println(e);
}
}
public void display()
{
try
{
ps = con.prepareStatement("select * from details");
rs = ps.executeQuery();
int count = 0;
while(rs.next())
{
System.out.println("Name :: "+rs.getString(1)+" , Age :: "+rs.getString(2)+" , Phone No :: "+rs.getString(3));
count++;
}
System.out.println(count+" records selected...");
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String args[])
{
TestDB1 aa=new TestDB1();
aa.connect();
aa.display();
}
}
On executing the above code the records in the DB gets displayed on the Console. Now Under the webroot is my JSP file called index.jsp
The coding in my JSP File is as follows:
<%@ page language="java" import="java.sql.*" pageEncoding="ISO-8859-1"%>
<%@ page import="com.avanza.test1.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
TestDB1 aa=new TestDB1();
aa.connect();
aa.display();
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
</body>
</html>
i have included my package in the above code, on running it with server i can see only a blank page in my browser but my records from my DB gets displayed on the console... I need My records to be displayed on the browser through my JSP page... Wat kind of changes should i implement on my Jsp page... Do help me with some sample codes.. I am a beginner in java... Do plzz help me...
Thanx in advance...
Cheers,
Thashif
|
|
|
|
|
This is a very big subject, too big to answer in a simple post here on this forum.
Go to Google, and search for "jsp tutorial" and "jdbc tutorial". This will bring up lots of entries that should get you started.
And, I would recommend getting a good book on JEE. There are plenty around, and many of them focus specifically on JSP and servlets.
|
|
|
|
|
David is right, this is too much to start with. You need to start with just JSPs or just JDBC.
But you could try this:
<%@ page language="java" import="java.sql.*" pageEncoding="ISO-8859-1"%>
<%@ page import="com.avanza.test1.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
TestDB1 aa=new TestDB1();
aa.connect();
aa.display();
%>
</body>
</html>
|
|
|
|
|
That still doesn't work because the display() method directs the output to System.out, i.e. the console. In order to appear in the final web page it would need to be directed to the JSP output stream (there are a number of ways to do this).
The best thing to do is to find a beginner's JSP tutorial and start from there.
|
|
|
|
|
import java.io.IOException;
import java.sql.*;
import javax.servlet.http.*;
import oracle.jdbc.*;
public class TestDB1 extends HttpServlet
{
private static final long serialVersionUID = -1L;
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
try {
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:xe","system","admin");
ps = con.prepareStatement("select * from details");
rs = ps.executeQuery();
int count = 0;
while(rs.next())
{
response.getWriter().write("Name :: "+rs.getString(1)+" , Age :: "+rs.getString(2)+" , Phone No :: "+rs.getString(3)+"<br>");
count++;
}
response.getWriter().write(count+" records selected...");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Good luck
|
|
|
|
|
Thanx a lot for spending ur valuable time 2 help me out.. well i hav started reading Beginers Jsp book on Wrox publication its really helpful 2 understd.. Thanx again 4 ur advice..
Cheers,
Thashif
|
|
|
|
|
Sir,
I want to create a download manager as a part of my academic project. The code which I used is listed below.During the execution of this pgm, i faced a pblm . I can't able to download the url .Moreover , after downloding the url, I want to save it in a local directory.Can u help me for doing that.
Download.java
import java.io.*;
import java.net.*;
import java.util.*;
// This class downloads a file from a URL.
class Download extends Observable implements Runnable {
// Max size of download buffer.
private static final int MAX_BUFFER_SIZE = 1024;
// These are the status names.
public static final String STATUSES[] = {"Downloading",
"Paused", "Complete", "Cancelled", "Error"};
// These are the status codes.
public static final int DOWNLOADING = 0;
public static final int PAUSED = 1;
public static final int COMPLETE = 2;
public static final int CANCELLED = 3;
public static final int ERROR = 4;
private URL url; // download URL
private int size; // size of download in bytes
private int downloaded; // number of bytes downloaded
private int status; // current status of download
// Constructor for Download.
public Download(URL url) {
this.url = url;
size = -1;
downloaded = 0;
status = DOWNLOADING;
// Begin the download.
download();
}
// Get this download's URL.
public String getUrl() {
return url.toString();
}
// Get this download's size.
public int getSize() {
return size;
}
// Get this download's progress.
public float getProgress() {
return ((float) downloaded / size) * 100;
}
// Get this download's status.
public int getStatus() {
return status;
}
// Pause this download.
public void pause() {
status = PAUSED;
stateChanged();
}
// Resume this download.
public void resume() {
status = DOWNLOADING;
stateChanged();
download();
}
// Cancel this download.
public void cancel() {
status = CANCELLED;
stateChanged();
}
// Mark this download as having an error.
private void error() {
status = ERROR;
stateChanged();
}
// Start or resume downloading.
private void download() {
Thread thread = new Thread(this);
thread.start();
}
// Get file name portion of URL.
private String getFileName(URL url) {
String fileName = url.getFile();
return fileName.substring(fileName.lastIndexOf('/') + 1);
}
// Download file.
public void run() {
RandomAccessFile file = null;
InputStream stream = null;
try {
// Open connection to URL.
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range",
"bytes=" + downloaded + "-");
// Connect to server.
connection.connect();
// Make sure response code is in the 200 range.
if (connection.getResponseCode() / 100 != 2) {
error();
}
// Check for valid content length.
int contentLength = connection.getContentLength();
if (contentLength < 1) {
error();
}
/* Set the size for this download if it
hasn't been already set. */
if (size == -1) {
size = contentLength;
stateChanged();
}
// Open file and seek to the end of it.
file = new RandomAccessFile(getFileName(url), "rw");
file.seek(downloaded);
stream = connection.getInputStream();
while (status == DOWNLOADING) {
/* Size buffer according to how much of the
file is left to download. */
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1)
break;
// Write buffer to file.
file.write(buffer, 0, read);
downloaded += read;
stateChanged();
}
/* Change status to complete if this point was
reached because downloading has finished. */
if (status == DOWNLOADING) {
status = COMPLETE;
stateChanged();
}
} catch (Exception e) {
error();
} finally {
// Close file.
if (file != null) {
try {
file.close();
} catch (Exception e) {}
}
// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {}
}
}
}
// Notify observers that this download's status has changed.
private void stateChanged() {
setChanged();
notifyObservers();
}
}
DownloadManager.java
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
// The Download Manager.
public class DownloadManager extends JFrame
implements Observer {
// Add download text field.
private JTextField addTextField;
// Download table's data model.
private DownloadsTableModel tableModel;
// Table listing downloads.
private JTable table;
// These are the buttons for managing the selected download.
private JButton pauseButton, resumeButton;
private JButton cancelButton, clearButton;
// Currently selected download.
private Download selectedDownload;
// Flag for whether or not table selection is being cleared.
private boolean clearing;
// Constructor for Download Manager.
public DownloadManager() {
// Set application title.
setTitle("Download Manager");
// Set window size.
setSize(640, 480);
// Handle window closing events.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
actionExit();
}
});
// Set up file menu.
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem fileExitMenuItem = new JMenuItem("Exit",
KeyEvent.VK_X);
fileExitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionExit();
}
});
fileMenu.add(fileExitMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Set up add panel.
JPanel addPanel = new JPanel();
addTextField = new JTextField(30);
addPanel.add(addTextField);
JButton addButton = new JButton("Add Download");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionAdd();
}
});
addPanel.add(addButton);
// Set up Downloads table.
tableModel = new DownloadsTableModel();
table = new JTable(tableModel);
table.getSelectionModel().addListSelectionListener(new
ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
tableSelectionChanged();
}
});
// Allow only one row at a time to be selected.
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Set up ProgressBar as renderer for progress column.
ProgressRenderer renderer = new ProgressRenderer(0, 100);
renderer.setStringPainted(true); // show progress text
table.setDefaultRenderer(JProgressBar.class, renderer);
// Set table's row height large enough to fit JProgressBar.
table.setRowHeight(
(int) renderer.getPreferredSize().getHeight());
// Set up downloads panel.
JPanel downloadsPanel = new JPanel();
downloadsPanel.setBorder(
BorderFactory.createTitledBorder("Downloads"));
downloadsPanel.setLayout(new BorderLayout());
downloadsPanel.add(new JScrollPane(table),
BorderLayout.CENTER);
// Set up buttons panel.
JPanel buttonsPanel = new JPanel();
pauseButton = new JButton("Pause");
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionPause();
}
});
pauseButton.setEnabled(false);
buttonsPanel.add(pauseButton);
resumeButton = new JButton("Resume");
resumeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionResume();
}
});
resumeButton.setEnabled(false);
buttonsPanel.add(resumeButton);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionCancel();
}
});
cancelButton.setEnabled(false);
buttonsPanel.add(cancelButton);
clearButton = new JButton("Clear");
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionClear();
}
});
clearButton.setEnabled(false);
buttonsPanel.add(clearButton);
// Add panels to display.
getContentPane().setLayout(new BorderLayout());
getContentPane().add(addPanel, BorderLayout.NORTH);
getContentPane().add(downloadsPanel, BorderLayout.CENTER);
getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
}
// Exit this program.
private void actionExit() {
System.exit(0);
}
// Add a new download.
private void actionAdd() {
URL verifiedUrl = verifyUrl(addTextField.getText());
if (verifiedUrl != null) {
tableModel.addDownload(new Download(verifiedUrl));
addTextField.setText(""); // reset add text field
} else {
JOptionPane.showMessageDialog(this,
"Invalid Download URL", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
// Verify download URL.
private URL verifyUrl(String url) {
// Only allow HTTP URLs.
if (!url.toLowerCase().startsWith("http://"))
return null;
// Verify format of URL.
URL verifiedUrl = null;
try {
verifiedUrl = new URL(url);
} catch (Exception e) {
return null;
}
// Make sure URL specifies a file.
if (verifiedUrl.getFile().length() < 2)
return null;
return verifiedUrl;
}
// Called when table row selection changes.
private void tableSelectionChanged() {
/* Unregister from receiving notifications
from the last selected download. */
if (selectedDownload != null)
selectedDownload.deleteObserver(DownloadManager.this);
/* If not in the middle of clearing a download,
set the selected download and register to
receive notifications from it. */
if (!clearing) {
selectedDownload =
tableModel.getDownload(table.getSelectedRow());
selectedDownload.addObserver(DownloadManager.this);
updateButtons();
}
}
// Pause the selected download.
private void actionPause() {
selectedDownload.pause();
updateButtons();
}
// Resume the selected download.
private void actionResume() {
selectedDownload.resume();
updateButtons();
}
// Cancel the selected download.
private void actionCancel() {
selectedDownload.cancel();
updateButtons();
}
// Clear the selected download.
private void actionClear() {
clearing = true;
tableModel.clearDownload(table.getSelectedRow());
clearing = false;
selectedDownload = null;
updateButtons();
}
/* Update each button's state based off of the
currently selected download's status. */
private void updateButtons() {
if (selectedDownload != null) {
int status = selectedDownload.getStatus();
switch (status) {
case Download.DOWNLOADING:
pauseButton.setEnabled(true);
resumeButton.setEnabled(false);
cancelButton.setEnabled(true);
clearButton.setEnabled(false);
break;
case Download.PAUSED:
pauseButton.setEnabled(false);
resumeButton.setEnabled(true);
cancelButton.setEnabled(true);
clearButton.setEnabled(false);
break;
case Download.ERROR:
pauseButton.setEnabled(false);
resumeButton.setEnabled(true);
cancelButton.setEnabled(false);
clearButton.setEnabled(true);
break;
default: // COMPLETE or CANCELLED
pauseButton.setEnabled(false);
resumeButton.setEnabled(false);
cancelButton.setEnabled(false);
clearButton.setEnabled(true);
}
} else {
// No download is selected in table.
pauseButton.setEnabled(false);
resumeButton.setEnabled(false);
cancelButton.setEnabled(false);
clearButton.setEnabled(false);
}
}
/* Update is called when a Download notifies its
observers of any changes. */
public void update(Observable o, Object arg) {
// Update buttons if the selected download has changed.
if (selectedDownload != null && selectedDownload.equals(o))
updateButtons();
}
// Run the Download Manager.
public static void main(String[] args) {
DownloadManager manager = new DownloadManager();
manager.show();
}
}
DownloadTableModel.java
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
// This class manages the download table's data.
class DownloadsTableModel extends AbstractTableModel
implements Observer {
// These are the names for the table's columns.
private static final String[] columnNames = {"URL", "Size",
"Progress", "Status"};
// These are the classes for each column's values.
private static final Class[] columnClasses = {String.class,
String.class, JProgressBar.class, String.class};
// The table's list of downloads.
private ArrayList downloadList = new ArrayList();
// Add a new download to the table.
public void addDownload(Download download) {
// Register to be notified when the download changes.
download.addObserver(this);
downloadList.add(download);
// Fire table row insertion notification to table.
fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1);
}
// Get a download for the specified row.
public Download getDownload(int row) {
return (Download) downloadList.get(row);
}
// Remove a download from the list.
public void clearDownload(int row) {
downloadList.remove(row);
// Fire table row deletion notification to table.
fireTableRowsDeleted(row, row);
}
// Get table's column count.
public int getColumnCount() {
return columnNames.length;
}
// Get a column's name.
public String getColumnName(int col) {
return columnNames[col];
}
// Get a column's class.
public Class getColumnClass(int col) {
return columnClasses[col];
}
// Get table's row count.
public int getRowCount() {
return downloadList.size();
}
// Get value for a specific row and column combination.
public Object getValueAt(int row, int col) {
Download download = (Download) downloadList.get(row);
switch (col) {
case 0: // URL
return download.getUrl();
case 1: // Size
int size = download.getSize();
return (size == -1) ? "" : Integer.toString(size);
case 2: // Progress
return new Float(download.getProgress());
case 3: // Status
return Download.STATUSES[download.getStatus()];
}
return "";
}
/* Update is called when a Download notifies its
observers of any changes */
public void update(Observable o, Object arg) {
int index = downloadList.indexOf(o);
// Fire table row update notification to table.
fireTableRowsUpdated(index, index);
}
}
ProgressRenderer.java
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
// This class renders a JProgressBar in a table cell.
class ProgressRenderer extends JProgressBar
implements TableCellRenderer {
// Constructor for ProgressRenderer.
public ProgressRenderer(int min, int max) {
super(min, max);
}
/* Returns this JProgressBar as the renderer
for the given table cell. */
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
// Set JProgressBar's percent complete value.
setValue((int) ((Float) value).floatValue());
return this;
}
}
regards
Soumya
|
|
|
|
|