ActionListener & MouseListener applet
Hi, i have an applet which determines where the user clicks the mouse within the applet and displays coordinates in the status bar
public void mouseClicked(MouseEvent e)
//get coordinates of click
mousex=e.getX(); mousey=e.getY();
paint(getGraphics());
repaint();
public void paint(Graphics g)
//Draw location pointer on map
g.setColor(Color.black);
g.fillOval(mousex-2,mousey-2,4,4);
showStatus("You clicked at ("+mousex+ ","+mousey+")");
}I also have a textfield which allows the user to type in a search term. Then in the actionPerformed() method, a for loop gets the text from the textfield and compares it to an array of keywords; if a match is found then a corresponding message is printed on the screen.
public void actionPerformed(ActionEvent e)
if(e.getSource()==text)
textStr=e.getActionCommand(); //Possibly use getText?
for (int i =0;i<items.length;i++)
if (items.equals(textStr))
dataString = data[i];break;
else
dataString = ("Sorry, No information for " + textStr);
My problem is this: when the mouse click functionality above is enabled, the textfield will not accept any input from the keyboard. If i comment the mouse code out then the textfield works as it should.
Any suggestions/ideas appreciated.
Many thanks.
Joe.
what do you mean by it is not working?
what happen when you dont comment out any part of your code andyou click on your applet?
try to separate the graphics part and the t textfield
is your applet implementing actionlistener?
if so change your code
and add a textfield in your applet and then make the textfield implements actionlistener
it should work fine
Similar Messages
-
ActionListener&MouseListener add to Drawing Object in JApplet
hi,guys
When I am doing my JApplet, I wanna add the ActionListener and MouseListener to the Drawing Object...
Like this:
Graphics2D g11 = (Graphics2D)g;
g11.setColor(Color.orange);
g11.fillOval(10,300, 100, 40);
g11.setColor(Color.darkGray);
g11.drawString(""+firstpro,30,325); //first protein object
g11 is the object, and now I wanna add both ActionListener and MouseListener on it.. that means if I click g11 area in my JApplet, it will do certain actions like open another URL page, and send a String from applet to that page also...
Does is possible to achieve?? If it does, how do I add the source code??
Hope you guys could kindly help me with some sample code...Thanks a lot!!
SDI don't believe the Graphics derived objects have any support for the Component derived stuff. But you can certainly add these listeners to whichever Component contains your graphics. If you want them to respond only if they are over a drawn part of the component, thats up to you application code as its the only thing that knows where the drawing ends.
-
Implementing ActionListener & MouseListener
Hello all!!
I was just wondering, is it possible to implement both an ActionListener and a MouseListener into one class? ex:
public class NAME extends JFrame implements ActionListener implements MouseListener
//etc
I have a program that relies heavily on MouseListener that I want to add a JMenu to, but I need ActionListener to do that... so, is it possible and I only have the wrong code? Or do I have to work around that somehow?
Thank you so much for your help!
Blessings,
Sarahpublic class Name extends JFrame implements ActionListener, MouseListener
-
Displaying a Timestamp on a Java Applet
Hi, I am working on a java applet in Jbuilder. I would like to display a timestamp on my applet. Where can I find the code for this. I have searched the forums and can't find anything I need. I just wanted it to current time.
thanksHere is a little of my code.. I imported the 2 packages and the I placed it at the bottom of this portion of code. The error I am getting is
illegal start of expression at 141 (141:1)
';' expected at line 141 (141:8)
import java.sql.Time;
import java.sql.Timestamp;
public class JavaProject extends Applet implements ItemListener, ActionListener, MouseListener
Connection conjavafinal;
Statement cmdjavafinal;
ResultSet rsjavafinal;
private String dbURL =
"jdbc:mysql://web6.duc.auburn.edu/?user=hansokl&password=tiger21";
boolean blnSuccessfulOpen = false;
Choice lstNames = new Choice();
TextField txtLastName = new TextField(15);
TextField txtFirstName = new TextField(15);
TextField txtid_number = new TextField(15);
TextField txtemployee = new TextField(15);
TextField txthoursbilled = new TextField(15);
TextField txtbillingrate = new TextField(15);
TextField txttotalcharged = new TextField(15);
TextField txtAddress = new TextField(15);
TextField txtCity = new TextField(15);
TextField txtState = new TextField(2);
TextField txtZip = new TextField(4);
TextField txtPhone = new TextField(15);
TextField txtemail = new TextField(15);
Label lblLastName = new Label("Last Name");
Label lblFirstName = new Label("First Name");
Label lblid_number = new Label("Id Number");
Label lblemployee = new Label("Employee");
Label lblhoursbilled = new Label("Hours Billed");
Label lblbillingrate = new Label("Billing Rate");
Label lblAddress = new Label("Address");
Label lblCity = new Label("City");
Label lblState = new Label("State");
Label lblZip = new Label("Zip");
Label lblPhone = new Label("Phone");
Label lblemail = new Label("Email");
Button btntotalcharged = new Button("Calculate");
Button btnAdd = new Button("Add");
Button btnEdit = new Button("Save");
Button btnCancel = new Button("Cancel");
Button btnDelete = new Button("Delete");
Button btnNext = new Button("Next");
Button btnLast = new Button("Last");
Button btnPrevious = new Button("Previous");
Button btnFirst = new Button( "First");
TextArea txaResults = new TextArea(10, 30);
String strid_number;
String stremployee;
String strhoursbilled;
String strbillingrate;
String strtotalcharged;
String strLastName;
String strFirstName;
String strAddress;
String strCity;
String strState;
String strZip;
String strPhone;
String stremail;
public void init() {
public void mouseClicked(MouseEvent e)
float flttotalcharged;
float fltbillingrate;
float flthoursbilled;
fltbillingrate = Float.valueOf(txtbillingrate.getText()).floatValue();
flthoursbilled = Float.valueOf(txthoursbilled.getText()).floatValue();
flttotalcharged = fltbillingrate * flthoursbilled;
txttotalcharged.setText("" + flttotalcharged);
public void mousePressed(MouseEvent e)
public void mouseReleased(MouseEvent e)
btnAdd.setForeground(Color.cyan);
btnAdd.setBackground(Color.white);
public void mouseEntered(MouseEvent e)
showStatus("Calculate Total Charge");
public void mouseExited(MouseEvent e)
showStatus("Ready");
setBackground(Color.ORANGE);
setForeground(Color.BLUE);
LoadDatabase();
if (blnSuccessfulOpen) {
add(new Label("Client Billing System"));
this is line 141 in my code ------> public class Main
public static void main(String[] args)
Timestamp ts = new Timestamp(System.currentTimeMillis());
Time time = new Time(ts.getTime());
System.out.println(time);
} -
FlowChart Applet.. where to begin?
Hello =)
could any of you help me please
I have to make an Applet to build FlowCharts..
this applet eventually has to integrate with MySQL database to save and fetch data to rebuild the FlowChart
for now I've used some buttons and icons to make the flowchart with absolute positioning.. for now that was good enough but I don't have the slightest clue how to position my icons somewhere that I could replace them.. or how to make them actual items so I could edit the text on them later..
could you please tell me how to get started with all that
this is what I have so far
// importeren van de benodigde swing libraries
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.ImageIcon;
// importeren van de benodigde awt libraries
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.*;
// importeren van de overige libraries
import java.util.Date;
import java.net.URL;
// begin de class, maak de applet en breid deze uit met een ActionListener
public class main extends JApplet implements ActionListener, MouseListener, MouseMotionListener {
// maak een serialVersionUID om van een waarschuwing af te komen
static final long serialVersionUID = 1;
// maak 2 panels om alles in te plaatsen
private JPanel onderPanel = new JPanel();
private JScrollPane centerPanel = new JScrollPane();
private JPanel scherm = new JPanel();
private JSplitPane splitPaneTest = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
// maak de JButtons
private JButton links = new JButton("links");
private JButton onder = new JButton("onder");
private JButton rechts = new JButton("rechts");
private JButton ok = new JButton("OK");
// maak de te gebruiken variabelen
private int linksbovenX = 10;
private int linksbovenY = 15;
private final int breedte = 70;
private final int hoogte = 20;
//private final int appletH = getHeight();
private int appletB;
// maak textfield
private JTextField invoerveld = new JTextField();
// maak de radiobuttons
private JRadioButton rechthoekKeuze = new JRadioButton();
private JRadioButton ovaalKeuze = new JRadioButton();
private JRadioButton driehoekKeuze = new JRadioButton();
// maak een buttongroup voor de radiobuttons
private ButtonGroup icon = new ButtonGroup();
// maak een string aan voor de text
private String text;
private String plaatje;
// maak een URL zodat de plaatjes in applet ook goed werken
private URL plaatjelocatie;
JLabel statusbar = new JLabel("blaat");
// -----------------------------------BEGIN-DE-APPLET---------------------------------------\\
public void init() {
appletB = getWidth();
// actionlistener toevoegen aan de buttons
links.addActionListener(this);
onder.addActionListener(this);
rechts.addActionListener(this);
// buttons in het onderPanel plaatsen
onderPanel.add(links, BorderLayout.EAST);
onderPanel.add(onder, BorderLayout.CENTER);
onderPanel.add(rechts, BorderLayout.WEST);
onderPanel.add(statusbar, BorderLayout.SOUTH);
// layout van het centerPanel bepalen
centerPanel.setLayout(null);
// linker gedeelte van de splitPane instellen
splitPaneTest.setLeftComponent(centerPanel);
// rechter gedeelte van de splitPane instellen
splitPaneTest.setRightComponent(scherm);
// bepalen op welke locatie het scherm gesplitst wordt
splitPaneTest.setDividerLocation(appletB);
// splitPaneTest uitzetten
splitPaneTest.setEnabled(false);
// maak de Start knop
plaatje = "ovaal.png";
MaakButton1("Start8", new JLabel());
// panels toevoegen aan de applet
add(splitPaneTest);
add(onderPanel, BorderLayout.SOUTH);
// radiobuttons voor het kiezen van het plaatje in een buttongroup zetten
icon.add(rechthoekKeuze);
icon.add(ovaalKeuze);
icon.add(driehoekKeuze);
// geef het panel scherm een layout manager
scherm.setLayout(new GridLayout(8,1));
// voeg rechthoekKeuze toe aan het scherm
scherm.add(rechthoekKeuze);
// verander de waarde van plaatje
plaatje = "rechthoek.png";
// label toevoegen aan het scherm en deze een icoon geven
scherm.add(new JLabel(new ImageIcon(MaakURL())));
// voeg ovaalKeuze toe aan het scherm
scherm.add(ovaalKeuze);
// verander de waarde van plaatje
plaatje = "ovaal.png";
// label toevoegen aan het scherm en deze een icoon geven
scherm.add(new JLabel(new ImageIcon(MaakURL())));
// voeg driehoekKeuze toe aan het scherm
scherm.add(driehoekKeuze);
// verander de waarde van plaatje
plaatje = "driehoek.png";
// label toevoegen aan het scherm en deze een icoon geven
scherm.add(new JLabel(new ImageIcon(MaakURL())));
// invoerveld toevoegen aan scherm
scherm.add(invoerveld);
// ok toevoegen aan scherm
scherm.add(ok);
// voeg actionlistener toe aan ok knopje
ok.addActionListener(this);
// voeg mouse listener toe aan het centerPanel
centerPanel.addMouseListener(this);
centerPanel.addMouseMotionListener(this);
// -----------------------------BEGIN-VAN-DE-ACTION-LISTENER--------------------------------\\
public void actionPerformed(ActionEvent e) {
// verkrijg de datum + tijd van nu
Date nu = new Date(e.getWhen());
// als er op een knop word geklikt afdrukken welke knop dat was en wanneer
System.out.println("Er is op \"" + e.getActionCommand() + "\" geklikt op: " + nu);
// als er op het knopje links word geklikt
if (e.getSource() == links) {
// controleer of er nog genoeg ruimte links is om het knopje aan te kunnen maken in beeld
if (linksbovenX - 80 <= 0) {
// zet text in de System.out
System.out.println("Error Links kan niet verder");
// als er nog wel genoeg ruimte is
else {
// verander de X (rechts) waarde van de linkerbovenhoek
linksbovenX = linksbovenX - 80;
// toon het invoer scherm via de methode ToonScherm1
ToonScherm1();
// als er op het knopje onder word geklikt
if (e.getSource() == onder) {
// veranderd de Y (hoogte) waarde van de linkerbovenhoek
linksbovenY = linksbovenY + 30;
// toon het invoer scherm via de methode ToonScherm1
ToonScherm1();
// als er op het knopje recht word geklikt
if (e.getSource() == rechts) {
// verander de X (rechts) waarde van de linkerbovenhoek
linksbovenX = linksbovenX + 80;
// toon het invoer scherm via de methode ToonScherm1
ToonScherm1();
// als er op het knopje OK uit het invoerscherm word geklikt
if (e.getSource() == ok){
// maak een boolean om te bepalen of de invoer goed is
boolean invoerjuist = true;
// probeer
try{
// de text uit invoerveld omzetten naar een String
text = invoerveld.getText();
// als er iets mis gaat tijdens het proberen
catch (Exception ex){
// zeg dat de invoer niet goed is
invoerjuist = false;
// als je ovaal kiest in het scherm
if(ovaalKeuze.isSelected()){
// verander de waarde van plaatje
plaatje = "ovaal.png";
// als je rechthoek kiest in het scherm
if(rechthoekKeuze.isSelected()){
// verander de waarde van plaatje
plaatje = "rechthoek.png";
// als je driehoek kiest in het scherm
if(driehoekKeuze.isSelected()){
// verander de waarde van plaatje
plaatje = "driehoek.png";
// als het textveld leeg is of er geen plaatje is gekozen
if ((text.isEmpty()) || (plaatje.isEmpty())){
// zeg dat de invoer niet goed is
invoerjuist = false;
// als de invoer goed is
if (invoerjuist == true){
// verberg het invoerscherm
splitPaneTest.setEnabled(false);
splitPaneTest.setDividerLocation(appletB);
// maak een nieuwe Button met behulp van de MaakButton1 methode
MaakButton1(text, new JLabel());
// schakel de knoppen weer aan
schakelaar();
public void mouseClicked(MouseEvent evt){
linksbovenX = evt.getX();
linksbovenY = evt.getY();
ToonScherm1();
public void mousePressed (MouseEvent evt) { }
public void mouseReleased (MouseEvent evt) { }
public void mouseEntered (MouseEvent evt) { }
public void mouseExited (MouseEvent evt) { }
public void mouseDragged(MouseEvent evt) {}
public void mouseMoved(MouseEvent evt) {
centerPanel.setToolTipText("(" + evt.getX() + ", " + evt.getY() + ")");
// Methode voor het aanmaken van nieuwe knopjes
public void MaakButton1(String text, JLabel label) {
// Afdrukken welke text er op de knop komt en de x, y waardes
System.out.println("MaakLabel \"" + text + "\" op (" + linksbovenX + ", " + linksbovenY +")");
// voeg het plaatje toe met behulp van de MaakURL methode
label.setIcon(new ImageIcon(MaakURL()));
// bepaal de plaats waar de knop komt
label.setBounds(linksbovenX, linksbovenY, breedte, hoogte);
// zet de text van de knop
label.setText(text);
// stel in dat de text van de knop horizontaal in het midden komt
label.setHorizontalTextPosition(JLabel.CENTER);
// stel in dat de text van de knop verticaal in het midden komt
label.setVerticalTextPosition(JLabel.CENTER);
// maak de String text weer leeg
text = "";
// maak het invoerveld weer leeg
invoerveld.setText("");
// zet de plaatjes keuzes ongeselecteerd
rechthoekKeuze.setSelected(false);
ovaalKeuze.setSelected(false);
driehoekKeuze.setSelected(false);
// voeg de knop toe aan het centerPanel
centerPanel.add(label);
// herteken de applet zodat de knop zichtbaar wordt
repaint();
// methode om een URL te maken
public URL MaakURL(){
// proberen
try {
// maak de URL
plaatjelocatie = new URL("jar:" + getCodeBase() + "flowchart.jar!/"+ plaatje);
// als er iets fout gaat
catch (java.net.MalformedURLException e) {
// print de foutmelding
System.out.println("Kon plaatje URL niet maken");
// stuur de URL terug
return(plaatjelocatie);
// methode om het invoerscherm te tonen
public void ToonScherm1(){
// start de methode schakelaar
schakelaar();
// toon het invoerscherm
splitPaneTest.setEnabled(true);
splitPaneTest.setDividerLocation((appletB / 4) * 3);
// methode om de knoppen aan of uit te zetten
public void schakelaar(){
// als het knopje links uit staat
if (links.isEnabled() == false){
// zet alle knopjes aan
links.setEnabled(true);
onder.setEnabled(true);
rechts.setEnabled(true);
// als het knopje links aan staat
else{
// zet alle knopjes uit
links.setEnabled(false);
onder.setEnabled(false);
rechts.setEnabled(false);
}Hi there,
you might want to grab a copy of the Open Solaris Bible (OpenSolaris Bible: Nicholas A. Solter, Jerry Jelinek, David Miner: 9780470385487: Amazon.com: Books) which, while being a little outdated, gives a quite decent jump start into the matter. Then install Solaris - should be piece of cake if you know Linux - and simply start comparing to what you know from Linux. Alternatively, if you don't have access to Solaris, go for OpenIndiana (http://openindiana.org), which is a true descendant of Sun's former open source variant, OpenSolaris. The operating system is free, the community is friendly, and you learn quite a lot you can take with you when you start using 'real' Solaris.
Cheers
Stevie -
Converting an applet into a frame
hello.
this is james mcfadden. I am developing a 2-player BlackJack card game in java. how do i convert the following 2 pieces of code from an applet into a frame?
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Blackjack extends Applet implements ActionListener,Runnable{
private Deck deck; //The deck...
private Hand player_hand;//player hand
private Hand dealer_hand;//dealer hand.
private Button bHit=new Button("Hit");
private Button bStay=new Button("Stay");
private Button bRestart=new Button("New Game");
//lets do some double buffering.
Image offIm=null;
Graphics offGraphics=null;
Dimension offDimension=null;
Image[] card_images = new Image[52];
private boolean cards_loaded = false;
private int current_card_loading = 0;
String message; //print a message...
int width; //The width of the applet
int height; //The height of the applet
int card_width = -1;
int card_padding = -1; //How much should we pad the cards by..?
private int games=-1; //How many games have been played?
public void init() {
Thread card_loader = new Thread(this);
card_loader.start();
public void newGame(){
bHit.setEnabled(true);
bStay.setEnabled(false);
player_hand = new Hand(); //Create new hands...
dealer_hand = new Hand();
//shuffle the deck.
deck.shuffleCards();
games++;
public void hit(){
bStay.setEnabled(true);
player_hand.addCard(deck.dealCard());
if(player_hand.getValue() > 21){
message = "You loose! (score:"+player_hand.getValue()+")";
//disable the hit and stay buttons...
bHit.setEnabled(false);
bStay.setEnabled(false);
return;
message = "Score: "+player_hand.getValue();
public void stay(){
while(dealer_hand.getValue() < 17){
dealer_hand.addCard(deck.dealCard());
if(dealer_hand.getValue() <= 21 && player_hand.getValue() < dealer_hand.getValue())
message = "You loose! (" + player_hand.getValue()+
" - "+dealer_hand.getValue()+")";
}else if (player_hand.getValue() == dealer_hand.getValue())
message = "You draw! (" + player_hand.getValue()+")";
}else {
message = "You win! (" + player_hand.getValue()+
" - "+dealer_hand.getValue()+")";
bHit.setEnabled(false);
bStay.setEnabled(false);
public void actionPerformed(ActionEvent e) {
if(e.getSource() == bRestart)
newGame();
}else if (e.getSource() == bHit)
hit();
}else if (e.getSource() == bStay)
stay();
repaint();
public void paint(Graphics g) {
update(g);
public void update(Graphics g) {
//lets sord out double buffering
if(offGraphics==null){
offIm=createImage(getSize().width,getSize().height);
offGraphics=offIm.getGraphics();
if(!cards_loaded){
//display a message saying we're loading the cards...
offGraphics.setFont(new Font("Arial",Font.PLAIN,14));
offGraphics.setColor(new Color(171,205,239));
offGraphics.fillRect(0,0,getSize().width,getSize().height);
offGraphics.setColor(Color.black);
offGraphics.drawString("Loading cards... ",5,20);
offGraphics.drawRect(15,40, 102 ,10);
offGraphics.drawRect(13,38, 106 ,14);
offGraphics.setColor(new Color(171,205,239));
offGraphics.fillRect(0,0,150,35);
offGraphics.setColor(Color.black);
offGraphics.fillRect(15,40, (current_card_loading)*2 ,10);
offGraphics.drawString("Loading card: "+current_card_loading+1,15,20);
}else{
Image currentCard;
while(card_width == -1)
card_width = deck.getCard(0).getImage().getWidth(this);
if(card_padding == -1)
card_padding = (width - (card_width * 2) - 4) / 4;
//clear the background...
offGraphics.setColor(Color.blue);
offGraphics.fillRect(0,0,width,height);
offGraphics.setColor(Color.black);
offGraphics.fillRect(1,1,width-2,height-2);
offGraphics.setColor(Color.white);
offGraphics.drawString("PLAYER:",card_padding,40);
offGraphics.drawString("DEALER:",(width/2) + card_padding,40);
offGraphics.drawString(message,5,height - 20);
if(games > 0)
offGraphics.drawString(games + " game(s) played...",5,height - 10);
//Draw the players hand...
for(int i=0;i<player_hand.getCardCount();i++){
currentCard = player_hand.getCards().getImage();
offGraphics.drawImage(currentCard, card_padding, 70+(20*(i-1)), this);
//now draw the dealers hand...
for(int i=0;i<dealer_hand.getCardCount();i++){
currentCard = dealer_hand.getCards()[i].getImage();
offGraphics.drawImage(currentCard, (width/2 ) + card_padding, 70+(20*(i-1)), this);
//draw buffered image.
g.drawImage(offIm,0,0,this);
public void run(){
MediaTracker t=new MediaTracker(this);
System.out.println("Applet getting cards...");
for(current_card_loading=0; current_card_loading < 52; current_card_loading++){
//try{
card_images[current_card_loading] = getImage(getCodeBase(),
"cards/" + (current_card_loading+1) + ".gif");
if(card_images[current_card_loading] == null){
System.out.println("Null card... ["+current_card_loading+"]");
}else{
t.addImage(card_images[current_card_loading],0);
try{
t.waitForID(0);
}catch(InterruptedException e){
System.err.println("Interrupted waiting for images..>");
//lets show our new status.
repaint();
//create the deck object now
deck = new Deck(this,card_images); //Create a new deck object.
card_width = deck.getCard(0).getImage().getWidth(this);
bHit.addActionListener(this);
bStay.addActionListener(this);
bRestart.addActionListener(this);
bHit.setEnabled(false);
bStay.setEnabled(false);
width = getSize().width;
height = getSize().height;
this.add(bHit);
this.add(bStay);
this.add(bRestart);
player_hand = new Hand(); //Create the hands...
dealer_hand = new Hand();
//make sure that the buttons appear properly.
this.validate();
message = "";
cards_loaded = true;
System.out.println("End of thread...");
repaint();
import java.awt.*;
import java.applet.*;
import java.net.*;
import java.io.*;
class Deck {
Card[] cards = new Card[52];
int currCard;
public Deck(Blackjack myApplet,Image[] card_images) {
// These are the (initial) values of all the cards
int[] values = {11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10,
11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10,
11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10,
11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
// Make all the cards, getting the images individually
for (int i=0; i<52; i++) {
// Image image = myApplet.getImage(myApplet.getCodeBase(), "cards/" + (i+1) + ".gif");
cards[i] = new Card(card_images, values[i]);
// Shuffle the cards.
shuffleCards();
public void shuffleCards(){
Card temp;
//loop through each card in the deck and swap it with some random card.
for (int i=0; i<52; i++) {
int rand = (int)(Math.random()*52);
temp = cards[51-i];//take the current card...
cards[51-i] = cards[rand];//and swap it with some random card...
cards[rand] = temp;
//now, reset the currentCard to deal...
currCard = 0;
public Card dealCard() {
Card card = cards[currCard];
currCard++;
return card;
public Card getCard(int i) {
return cards[i];thanks for the advice.
i've done what you suggested. but when i went try to compile the 2 programs i get error messages (shown below along with the modified code). do you know what are causing these error messages?
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Blackjack extends JFrame implements ActionListener,MouseListener{
private Deck deck; //The deck...
private Hand player_hand;//player hand
private Hand dealer_hand;//dealer hand.
//private Button bHit=new Button("Hit");
JButton bHit=new JButton("Hit");
//private Button bStay=new Button("Stay");
JButton bStay=new JButton("Stay");
//private Button bRestart=new Button("New Game");
JButton bRestart=new JButton("New Game");
//lets do some double buffering.
Image offIm=null;
Graphics offGraphics=null;
Dimension offDimension=null;
Image[] card_images = new Image[52];
private boolean cards_loaded = false;
private int current_card_loading = 0;
String message; //print a message...
int width; //The width of the applet
int height; //The height of the applet
int card_width = -1;
int card_padding = -1; //How much should we pad the cards by..?
private int games=-1; //How many games have been played?
public static void main(String[] args){
Blackjack bj =new Blackjack();
bj.pack();
bj.setVisible(true);
public Blackjack(){
Thread card_loader = new Thread(this);
card_loader.start();
bHit.addMouseListener(this);
bHit.addActionListener(this);
//bHit.addMouseMotionListener(this);
add(bHit);
bStay.addMouseListener(this);
bStay.addActionListener(this);
//bStay.addMouseMotionListener(this);
add(bStay);
bRestart.addMouseListener(this);
bRestart.addActionListener(this);
//bRestart.addMouseMotionListener(this);
add(bRestart);
JFrame frame=new JFrame("BlackJack");
frame.setSize(400,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.pack();
frame.setVisible(true);
public void newGame(){
bHit.setEnabled(true);
bStay.setEnabled(false);
player_hand = new Hand(); //Create new hands...
dealer_hand = new Hand();
//shuffle the deck.
deck.shuffleCards();
games++;
public void hit(){
bStay.setEnabled(true);
player_hand.addCard(deck.dealCard());
if(player_hand.getValue() > 21){
message = "You loose! (score:"+player_hand.getValue()+")";
//disable the hit and stay buttons...
bHit.setEnabled(false);
bStay.setEnabled(false);
return;
message = "Score: "+player_hand.getValue();
public void stay(){
while(dealer_hand.getValue() < 17){
dealer_hand.addCard(deck.dealCard());
if(dealer_hand.getValue() <= 21 && player_hand.getValue() < dealer_hand.getValue()){
message = "You loose! (" + player_hand.getValue()+" - "+dealer_hand.getValue()+")";
else if (player_hand.getValue() == dealer_hand.getValue()){
message = "You draw! (" + player_hand.getValue()+")";
else{
message = "You win! (" + player_hand.getValue()+" - "+dealer_hand.getValue()+")";
bHit.setEnabled(false);
bStay.setEnabled(false);
public void actionPerformed(ActionEvent e){
if(e.getSource() == bRestart){
newGame();
else if (e.getSource() == bHit){
hit();
else if (e.getSource() == bStay){
stay();
repaint();
public void paint(Graphics g){
update(g);
public void update(Graphics g){
//lets sord out double buffering
if(offGraphics==null){
offIm=createImage(getSize().width,getSize().height);
offGraphics=offIm.getGraphics();
if(!cards_loaded){
//display a message saying we're loading the cards...
offGraphics.setFont(new Font("Arial",Font.PLAIN,14));
offGraphics.setColor(new Color(171,205,239));
offGraphics.fillRect(0,0,getSize().width,getSize().height);
offGraphics.setColor(Color.black);
offGraphics.drawString("Loading cards... ",5,20);
offGraphics.drawRect(15,40, 102 ,10);
offGraphics.drawRect(13,38, 106 ,14);
offGraphics.setColor(new Color(171,205,239));
offGraphics.fillRect(0,0,150,35);
offGraphics.setColor(Color.black);
offGraphics.fillRect(15,40, (current_card_loading)*2 ,10);
offGraphics.drawString("Loading card: "+current_card_loading+1,15,20);
else{
Image currentCard;
while(card_width == -1){
card_width = deck.getCard(0).getImage().getWidth(this);
if(card_padding == -1){
card_padding = (width - (card_width * 2) - 4) / 4;
//clear the background...
offGraphics.setColor(Color.blue);
offGraphics.fillRect(0,0,width,height);
offGraphics.setColor(Color.black);
offGraphics.fillRect(1,1,width-2,height-2);
offGraphics.setColor(Color.white);
offGraphics.drawString("PLAYER:",card_padding,40);
offGraphics.drawString("DEALER:",(width/2) + card_padding,40);
offGraphics.drawString(message,5,height - 20);
if(games > 0){
offGraphics.drawString(games + " game(s) played...",5,height - 10);
//Draw the players hand...
for(int i=0;i<player_hand.getCardCount();i++){
currentCard = player_hand.getCards().getImage();
offGraphics.drawImage(currentCard, card_padding, 70+(20*(i-1)), this);
//now draw the dealers hand...
for(int i=0;i<dealer_hand.getCardCount();i++){
currentCard = dealer_hand.getCards()[i].getImage();
offGraphics.drawImage(currentCard, (width/2 ) + card_padding, 70+(20*(i-1)), this);
//draw buffered image.
g.drawImage(offIm,0,0,this);
public void run(){
MediaTracker t=new MediaTracker(this);
System.out.println("Frame getting cards...");
for(current_card_loading=0; current_card_loading < 52; current_card_loading++){
//try{
card_images[current_card_loading] = getImage(getCodeBase(),"cards/" + (current_card_loading+1) + ".gif");
if(card_images[current_card_loading] == null){
System.out.println("Null card... ["+current_card_loading+"]");
else{
t.addImage(card_images[current_card_loading],0);
try{
t.waitForID(0);
catch(InterruptedException e){
System.err.println("Interrupted waiting for images..>");
//lets show our new status.
repaint();
//create the deck object now
deck = new Deck(this,card_images); //Create a new deck object.
card_width = deck.getCard(0).getImage().getWidth(this);
bHit.addActionListener(this);
bStay.addActionListener(this);
bRestart.addActionListener(this);
bHit.setEnabled(false);
bStay.setEnabled(false);
width = getSize().width;
height = getSize().height;
this.add(bHit);
this.add(bStay);
this.add(bRestart);
player_hand = new Hand(); //Create the hands...
dealer_hand = new Hand();
//make sure that the buttons appear properly.
this.validate();
message = "";
cards_loaded = true;
System.out.println("End of thread...");
repaint();
----jGRASP exec: javac -g X:\NETPROG\Assignment2\Blackjack.java
Blackjack.java:7: Blackjack is not abstract and does not override abstract method mouseExited(java.awt.event.MouseEvent) in java.awt.event.MouseListener
public class Blackjack extends JFrame /*Applet*/ implements ActionListener,MouseListener/*,Runnable*/{
^
Blackjack.java:53: cannot find symbol
symbol : constructor Thread(Blackjack)
location: class java.lang.Thread
Thread card_loader = new Thread(this);
^
Blackjack.java:209: cannot find symbol
symbol : method getCodeBase()
location: class Blackjack
card_images[current_card_loading] = getImage(getCodeBase(),"cards/" + (current_card_loading+1) + ".gif");
^
3 errors
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
import java.awt.*;
import javax.swing.JFrame;
import java.net.*;
import java.io.*;
class Deck {
Card[] cards = new Card[52];
int currCard;
public Deck(/*Blackjack myApplet*/Blackjack myFrame,Image[] card_images) {
// These are the (initial) values of all the cards
int[] values = {11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10,
11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10,
11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10,
11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
// Make all the cards, getting the images individually
for (int i=0; i<52; i++) {
cards[i] = new Card(card_images, values[i]);
// Shuffle the cards.
shuffleCards();
public void shuffleCards(){
Card temp;
//loop through each card in the deck and swap it with some random card.
for (int i=0; i<52; i++) {
int rand = (int)(Math.random()*52);
temp = cards[51-i];//take the current card...
cards[51-i] = cards[rand];//and swap it with some random card...
cards[rand] = temp;
//now, reset the currentCard to deal...
currCard = 0;
public Card dealCard() {
Card card = cards[currCard];
currCard++;
return card;
public Card getCard(int i) {
return cards[i];
----jGRASP exec: javac -g X:\NETPROG\Assignment2\Deck.java
Blackjack.java:6: Blackjack is not abstract and does not override abstract method mouseExited(java.awt.event.MouseEvent) in java.awt.event.MouseListener
public class Blackjack extends JFrame implements ActionListener,MouseListener{
^
Blackjack.java:45: cannot find symbol
symbol : constructor Thread(Blackjack)
location: class java.lang.Thread
Thread card_loader = new Thread(this);
^
Blackjack.java:201: cannot find symbol
symbol : method getCodeBase()
location: class Blackjack
card_images[current_card_loading] = getImage(getCodeBase(),"cards/" + (current_card_loading+1) + ".gif");
^
3 errors
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete. -
If anyone can, please help me by writing a java applet code for a web based chat system! It�s better if it can write the chat lines into a Notepad as a chat log.
Because of the limited time frame in my project completion, I�m unable to complete my project on due to this reason...
It will be a great help, if you guys could support me on this issue!
Thanking you.
Best regards,
Aslam Cader
Message was edited by:
aslamcWell, i've a code here of a messenger who makes a new log every day and put the information into it. The language is Dutch but the main things are english!
There are some things like JEditorPane who are not very importent.
But... here you are:
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
import java.net.*;
import java.util.*;
import java.io.*;
import java.text.*;
class frame extends JFrame implements ActionListener, Runnable
//Alle benodigde variable aanmaken
Menu menu, help;
MenuBar balk;
MenuItem Refresh, help_item, Afsluiten;
JTextArea ontvangen, zenden;
JButton opslaan;
JScrollBar scrollbar;
JEditorPane textvak;
boolean Done;
String Vandaag, Jaar_Map, File_Directory, inhoud;
JScrollPane sp_a, sp_z;
Thread controle = new Thread(this);
int menu_nummer = 1, dialog_type;
String Persoon, bericht, venster, Titel;
hulp HelpVenster;
URL site_name;
//Alles aangemaakt
public void init()
start();
frame()
super("WestOnline Messenger");
setSize(300, 515);
//Voorbereidingen
if (Done == false)
Date dt = new Date();
SimpleDateFormat df_y = new SimpleDateFormat("yyyy");
SimpleDateFormat df_d = new SimpleDateFormat("D");
Vandaag = df_d.format(dt);
Jaar_Map = df_y.format(dt);
Done = true;
//Einde voorbereidingen
//Connectie met Server
//De menubar maken
balk = new MenuBar();
menu = new Menu("Bestand");
Refresh = new MenuItem("Refresh");
menu.add(Refresh);
Refresh.addActionListener(this);
menu.addSeparator();
Afsluiten = new MenuItem("Afsluiten");
menu.add(Afsluiten);
Afsluiten.addActionListener(this);
balk.add(menu);
help = new Menu("Help");
help_item = new MenuItem("Help");
help.add(help_item);
help_item.addActionListener(this);
//Menubar klaar
//Inhoud van het scherm
//Onderdelen aanmaken
ontvangen = new JTextArea(20, 24);
sp_a = new JScrollPane(ontvangen);
sp_a.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
sp_a.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
zenden = new JTextArea(4, 25);
sp_z = new JScrollPane(zenden);
sp_z.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
sp_z.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
balk.add(help);
textvak = new JEditorPane();
setMenuBar(balk);
opslaan = new JButton("Verzend");
//Onderdelen klaar
//Onderdelen in scherm
Container layout = getContentPane();
layout.setBackground(Color.black);
layout.setLayout(new FlowLayout(FlowLayout.LEFT));
layout.add(sp_a);
layout.add(textvak);
layout.add(opslaan);
opslaan.addActionListener(this);
//Onderdelen neergezet
//Alles in scherm gezet
//Naam verkrijgen
if (menu_nummer == 1)
bericht = "Geef een naam op AUB";
Persoon = JOptionPane.showInputDialog(bericht);
if (Persoon == null)
bericht = "U MOET een naam opgeven!";
Persoon = JOptionPane.showInputDialog(bericht);
if (Persoon == null)
bericht = "U MOET EEN NAAM OPGEVEN!";
Persoon = JOptionPane.showInputDialog(bericht);
if (Persoon == null)
dialog_type = JOptionPane.PLAIN_MESSAGE;
dialog_type = JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog((Component) null, "Uw naam is ingesteld als 'Regisseur'", "Naam ingesteld", dialog_type);
Persoon = "Regisseur";
else
dialog_type = JOptionPane.PLAIN_MESSAGE;
dialog_type = JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog((Component) null, "Uw naam is ingesteld als " + Persoon, "Naam ingesteld", dialog_type);
menu_nummer = 2;
//Naam verkregen
//Bestand lezen
try
textvak.setText("");
textvak.setPage("http://www.maartenz.org/~jasper/Java/RTV/" + Jaar_Map + "/" + Vandaag + ".txt");
ontvangen.setText("");
ontvangen.read(new FileReader(File_Directory), File_Directory);
ontvangen.setCaretPosition(ontvangen.getDocument().getLength());
catch(Exception ec)
//alles uitgelezen
public void actionPerformed(ActionEvent e)
if (e.getSource() == Afsluiten)
dialog_type = JOptionPane.showConfirmDialog((Component) null, "Wilt u het chatbestand legen?\n (Zie 'Help' voor details)", "Bestand legen?", JOptionPane.YES_NO_OPTION);
if (dialog_type == JOptionPane.YES_OPTION)
try
zenden.setText("");
zenden.write(new FileWriter(File_Directory));
catch(Exception ex)
setVisible(false);
else
setVisible(false);
if (e.getSource() == Refresh)
try
ontvangen.setText("");
ontvangen.read(new FileReader(File_Directory), File_Directory);
ontvangen.setCaretPosition(ontvangen.getDocument().getLength());
catch(Exception ee)
if (e.getSource() == help_item)
HelpVenster = new hulp();
HelpVenster.setVisible(true);
if (e.getSource() == opslaan)
try
ontvangen.setText("");
ontvangen.read(new FileReader(File_Directory), File_Directory);
zenden.setText(ontvangen.getText() + ">" + Persoon + "\n" + zenden.getText() + "\n" + "\n");
zenden.write(new FileWriter(File_Directory));
ontvangen.setText("");
ontvangen.read(new FileReader(File_Directory), File_Directory);
catch(Exception ex)
ontvangen.setText("Schrijferror!");
ontvangen.setCaretPosition(ontvangen.getDocument().getLength());
zenden.setText("");
public void start()
controle.start();
ontvangen.setText("");
public void stop()
controle.stop();
public void run()
try
ontvangen.setText("");
ontvangen.read(new FileReader(File_Directory), File_Directory);
ontvangen.setCaretPosition(ontvangen.getDocument().getLength());
Thread.sleep(10000);
catch(Exception ex)
ontvangen.setText("Schrijferror!");
class hulp extends JFrame implements ActionListener, MouseListener
String[] menu_ond = {"Welkom ", "Namen", "Chatbestand", "Internet", "Rechten", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "};
JList lijst;
JScrollPane sp_een, sp_twee;
JTextArea inhoud_text;
Menu menu_twee;
MenuBar bar;
MenuItem Quit;
String lees_bestand;
hulp()
//Instellingen
super("WestOnline Messenger Help");
setSize(500, 400);
//Einde instellingen
//Menu
bar = new MenuBar();
menu_twee = new Menu("Bestand");
Quit = new MenuItem("Afsluiten");
menu_twee.add(Quit);
Quit.addActionListener(this);
bar.add(menu_twee);
setMenuBar(bar);
//Einde Menu
//Inhoud pagina
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.setBackground(Color.black);
lijst = new JList(menu_ond);
lijst.addMouseListener(this);
contentPane.add(lijst);
inhoud_text = new JTextArea(20, 34);
sp_twee = new JScrollPane(inhoud_text);
contentPane.add(sp_twee);
//Einde inhoud
public void actionPerformed(ActionEvent e)
if (e.getSource() == Quit)
setVisible(false);
public void mouseClicked(MouseEvent l)
lees_bestand = "help/" + lijst.getSelectedIndex() + ".txt";
inhoud_text.setText("");
try
inhoud_text.read(new FileReader(lees_bestand), lees_bestand);
catch(Exception ex)
inhoud_text.setText("Oops");
if (lijst.getSelectedIndex() == 0)
inhoud_text.setText(inhoud_text.getText() + "\n" + "\n" + "Gemaakt door Jasper Kouwenberg, 2007");
public void mouseEntered(MouseEvent l){}
public void mouseExited(MouseEvent l){}
public void mousePressed(MouseEvent l){}
public void mouseReleased(MouseEvent l){}
public class rtv extends JApplet
public void init()
frame Scherm = new frame();
boolean Done = true;
if (Done)
Scherm.setVisible(true);
Done = false;
} -
Can applet have JFileChooser?
i am trying to develop an applet. but i can't implement the Jfilechooser in the applet, i wonder whether that is even possible in the first place?
timthanks but i have done something similar but i have got something like
java.security.AccessControlException:access denied, and i can't solve it. i have enclose my problem below, and those with **** i guess it may have something to do with that. not sure
many many many thanks for your help.
tim
============================================
public class TSP extends Applet implements ActionListener, MouseListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == inputFile && openFile()){
//do whatever i want
public boolean openFile() {
//open the file chooser
int returnVal = fChooser.showOpenDialog(TSP.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
tspSF = fChooser.getSelectedFile();
System.out.println(tspSF.getName()+" is chosen");
**** inputFile = new Input(this, errHandler);
inputFile.readandinputdata(tspSF);
return true;
else return false;
public init(){......}
==========================================
public class Input{
public Input(TSP tsp, ErrHandler errHandler){
**** this.tsp = tsp;
this.errHandler = errHandler;
// method readandinputdata
public void readandinputdata(File tspSF){
try {
input = new BufferedReader(new FileReader(tspSF));
catch....
try {
//read in the first line
data = input.readLine();
while (data != null){
st = new StringTokenizer(data);
nodeNumber = tokenChanger.parseInt(st.nextToken());
x = tokenChanger.parseInt(st.nextToken());
y = tokenChanger.parseInt(st.nextToken());
//store the x and y with some method in TSP class
**** tsp.storeNodes(x, y);
// read next time
data = input.readLine();
}// end of while data != null
closeFile();
} // end of second scan
catch.....
}//end of readandinoputdata
} -
I am very new to java and I have written several stand alone applets but when I try to call the different applets from a main they fail to load or end up in a new instance loop. Sorry if the verbage is incorrect. Here is an example of what I am trying to accomplish
public class MainLayout extends Applet implements ActionListener,MouseListener {
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
SwingUtilities.invokeLater(new Runnable() {
public void run()
new anotherApplet(); //not working
createAndShowFrame(); // works and creates an empty frame.
public static void createAndShowFrame() {
JFrame myFrame = new JFrame("My JFrame");
myFrame.setSize(250, 250);
myFrame.setLocation(300,200);
myFrame.getContentPane().add(BorderLayout.CENTER, new JTextArea(10, 40));
myFrame.show();
Like I said "MainLayout" runs no problem but I am unable to load "anotherApplet". However if I run anotherApplet seperately it executes correctly. Any help would be greatly appreciated.Applet containers usually invoke a number of lifecycle methods on their applets, such as init, start, stop, destroy, etc. and provide an AppletContext. If your applets rely on any of these methods, then your attempt to execute them from a main should invoke those methods and potentially provide a context.
-
Page Functionality(Prev and Next) using applet
Hi,
I am trying to implement an applet which has the paging functionality(previous and next). How do I handle the mouse event for that.
Appreciate your help.
Thanks
Sankar.ok. Sorry about that, Here is my applet implementation,
public class PageApplet extends JApplet implements ActionListener,MouseListener
JTextField name,age;
JRadioButton male, female;
static String maleStr = "Male";
static String femaleStr = "Female";
private boolean inAnApplet = true;
JComboBox status;
JPanel pane;
GridBagConstraints c;
private static int count =0;
private String nameStr;
public PageApplet() {
this(true);
public PageApplet(boolean inAnApplet) {
this.inAnApplet = inAnApplet;
if (inAnApplet) {
getRootPane().putClientProperty("defeatSystemEventQueueCheck",
Boolean.TRUE);
* The entry point for the applet.
public void init()
setContentPane(makeContentPane());
public Container makeContentPane() {
//Add Components to a JPanel, using the default FlowLayout.
pane = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
JLabel namel = new JLabel("Name : ",JLabel.LEFT);
c.weightx = 0.6;
c.gridx = 0;
c.gridy = 0;
pane.add(namel,c);
name = new JTextField(20);
name.setColumns(20);
c.gridx = 5;
c.gridy = 0;
name.addActionListener(this);
pane.add(name,c);
JLabel agel = new JLabel(" Age : ", JLabel.LEFT);
c.gridx = 0;
c.gridy = 1;
pane.add(agel,c);
age = new JTextField(2);
age.setColumns(2);
age.addActionListener(this);
c.gridx = 5;
c.gridy = 1;
pane.add(age,c);
JLabel gender = new JLabel(" Gender :", JLabel.LEFT);
c.gridx = 0;
c.gridy = 2;
pane.add(gender,c);
male = new JRadioButton(maleStr);
male.setMnemonic(KeyEvent.VK_C);
male.setActionCommand(maleStr);
male.setSelected(true);
male.setBackground(Color.WHITE);
male.addActionListener(this);
c.gridx = 5;
c.gridy = 2;
pane.add(male,c);
female = new JRadioButton(femaleStr);
female.setMnemonic(KeyEvent.VK_D);
female.setActionCommand(femaleStr);
female.setBackground(Color.WHITE);
female.addActionListener(this);
c.gridx = 10;
c.gridy = 2;
pane.add(female,c);
JLabel statusl = new JLabel(" Status :", JLabel.LEFT);
c.gridx = 0;
c.gridy = 3;
pane.add(statusl,c);
String[] statusStr = {"Single","Married","Divorced"};
status = new JComboBox(statusStr);
status.setSelectedIndex(0);
status.setEditable(false);
status.setBackground(Color.WHITE);
status.addActionListener(this);
c.gridx = 5;
c.gridy = 3;
pane.add(status,c);
JButton next = new JButton("Next");
c.ipady = 0;
c.weightx=0.0;
c.weighty=1.0;
c.anchor = GridBagConstraints.SOUTH;
c.insets = new Insets(10,0,0,0);
c.gridwidth = 1;
c.gridx = 5;
c.gridy = 4;
next.addMouseListener(this);
pane.add(next,c);
//pane.setBackground(new Color(255,255,204));
pane.setBackground(Color.WHITE);
//pane.setLayout(new GridBagLayout(2,2));
pane.setBorder(BorderFactory.createMatteBorder(1,1,2,2,Color.black));
return pane;
public Container makeContentPane1() {
//pane = new JPanel(new GridBagLayout());
pane.removeAll();
c = new GridBagConstraints();
JLabel label1 = new JLabel("Hello ",JLabel.RIGHT);
c.gridx = 0;
c.gridy = 0;
pane.add(label1,c);
JTextField text1 = new JTextField(20);
text1.setText(nameStr);
text1.setColumns(20);
text1.setEditable(false);
c.gridx = 5;
c.gridy = 0;
pane.add(label1,c);
JButton finish = new JButton("Finish");
finish.addMouseListener(this);
c.anchor = GridBagConstraints.CENTER;
c.insets = new Insets(10,0,0,0);
c.gridwidth = 1;
c.gridx = 5;
c.gridy = 2;
pane.add(finish,c);
//Add Components to a JPanel, using the default FlowLayout.
// JPanel pane = new JPanel();
// pane.add(label1);
// pane.add(text1);
// pane.add(finish);
//pane.setBackground(new Color(255,255,204));
pane.setBackground(Color.WHITE);
pane.setBorder(BorderFactory.createMatteBorder(1,1,2,2,Color.black));
return pane;
public void actionPerformed(ActionEvent e)
if (e.getActionCommand().equals(maleStr)) {
male.setSelected(true);
female.setSelected(false);
} else if(e.getActionCommand().equals(femaleStr)){
male.setSelected(false);
female.setSelected(true);
nameStr = name.getText();
JComboBox cb = (JComboBox)e.getSource();
String statusStr = (String)cb.getSelectedItem();
if(statusStr.equals("Single"))
status.setSelectedIndex(0);
else if(statusStr.equals("Married"))
status.setSelectedIndex(1);
else if(statusStr.equals("Divorced"))
status.setSelectedIndex(2);
public void mousePressed(MouseEvent me){
public void mouseClicked(MouseEvent me){
JButton next = (JButton)me.getSource();
String str = next.getName();
if(((me.getClickCount()==1)) || (str.equals(next))){
setContentPane(makeContentPane1());
count=1;
}else{
URL url;
try {
String nextPage="http://"+this.getCodeBase().getHost()+":"+this.getCodeBase().getPort()+"/ShowPage.jsp";
url=new URL(nextPage);
getAppletContext().showDocument(url);
}catch(MalformedURLException ex) {
ex.printStackTrace();
public void mouseReleased(MouseEvent me){
public void mouseEntered(MouseEvent me){
public void mouseExited(MouseEvent me){
private static void createAndShowGUI(){
JFrame frame = new JFrame("Application version: AppletDemo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
PageApplet applet = new TestPartner(false);
if(count==1)
frame.setContentPane(applet.makeContentPane1());
else
frame.setContentPane(applet.makeContentPane());
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
Here is what I am trying to do, when the user hits the next button it should go to the next page. but when I hit the next page, its hanging in the same page. Since I am new to applet coding, I couldn't proceed.
Thanks
Sankar. -
hi all
following is code which compile well but didnt show any output, could any genious help me out of this problem.
i will be veryyyyyyyyyyyyyyyyy thankful to all
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GoMoku1 extends JFrame{
JButton newGameButton; // Button for starting a new game.
JButton resignButton; // Button that a player can use to end the
// game by resigning.
JLabel message; // Label for displaying messages to the user.
public void GoMoku1() {
Container content = getContentPane(); // Content pane of applet.
content.setLayout(null); // I will do the layout myself.
content.setBackground(new Color(0,150,0)); // Dark green background.
Board board = new Board(); // Note: The constructor for the
// board also creates the buttons
// and label.
content.add(board);
content.add(newGameButton);
content.add(resignButton);
content.add(message);
/* Set the position and size of each component by calling
its setBounds() method. */
board.setBounds(16,16,220,220);
newGameButton.setBounds(310, 60, 120, 30);
resignButton.setBounds(310, 120, 120, 30);
message.setBounds(0, 350, 350, 30);
public static void main(String[] args)
GoMoku1 gm=new GoMoku1();
// ----------------------- Nested class -----------------------------------
class Board extends JPanel implements ActionListener, MouseListener {
int[][] board; // The data for the board is kept here. The values
// in this array are chosen from the following constants.
static final int EMPTY = 0, // Represents an empty square.
WHITE = 1, // A white piece.
BLACK = 2; // A black piece.
boolean gameInProgress; // Is a game currently in progress?
int currentPlayer; // Whose turn is it now? The possible values
// are WHITE and BLACK. (This is valid only while
// a game is in progress.)
int win_r1, win_c1, win_r2, win_c2; // When a player wins by getting five or more
// pieces in a row, the squares at the
// ends of the row are (win_r1,win_c1)
// and (win_r2,win_c2). A red line is
// drawn between these squares. When there
// are no five pieces in a row, the value of
// win_r1 is -1. The values are set in the
// count() method. The value of win_r1 is
// tested in the paintComponent() method.
public Board() {
// Constructor. Create the buttons and label. Listen for mouse
// clicks and for clicks on the buttons. Create the board and
// start the first game.
setBackground(Color.lightGray);
addMouseListener(this);
resignButton = new JButton("Resign");
resignButton.addActionListener(this);
newGameButton = new JButton("New Game");
newGameButton.addActionListener(this);
message = new JLabel("",JLabel.CENTER);
message.setFont(new Font("Serif", Font.BOLD, 14));
message.setForeground(Color.green);
board = new int[ 15][ 15];
doNewGame();
public void actionPerformed(ActionEvent evt) {
// Respond to user's click on one of the two buttons.
Object src = evt.getSource();
if (src == newGameButton)
doNewGame();
else if (src == resignButton)
doResign();
void doNewGame() {
// Begin a new game.
if (gameInProgress == true) {
// This should not be possible, but it doesn't
// hurt to check.
message.setText("Finish the current game first!");
return;
for (int row = 0; row < 15; row++) // Fill the board with EMPTYs
for (int col = 0; col < 15; col++)
board[row][col] = EMPTY;
currentPlayer = BLACK; // BLACK moves first.
message.setText("BLACK: Make your move.");
gameInProgress = true;
newGameButton.setEnabled(false);
resignButton.setEnabled(true);
win_r1 = -1; // This value indicates that no red line is to be drawn.
repaint();
void doResign() {
// Current player resigns. Game ends. Opponent wins.
if (gameInProgress == false) {
// This should not be possible.
message.setText("There is no game in progress!");
return;
if (currentPlayer == WHITE)
message.setText("WHITE resigns. BLACK wins.");
else
message.setText("BLACK resigns. WHITE wins.");
newGameButton.setEnabled(true);
resignButton.setEnabled(false);
gameInProgress = false;
void gameOver(String str) {
// The game ends. The parameter, str, is displayed as a message.
message.setText(str);
newGameButton.setEnabled(true);
resignButton.setEnabled(false);
gameInProgress = false;
void doClickSquare(int row, int col) {
// This is called by mousePressed() when a player clicks on the
// square in the specified row and col. It has already been checked
// that a game is, in fact, in progress.
/* Check that the user clicked an empty square. If not, show an
error message and exit. */
if ( board[row][col] != EMPTY ) {
if (currentPlayer == BLACK)
message.setText("BLACK: Please click an empty square.");
else
message.setText("WHITE: Please click an empty square.");
return;
/* Make the move. Check if the board is full or if the move
is a winning move. If so, the game ends. If not, then it's
the other user's turn. */
board[row][col] = currentPlayer; // Make the move.
repaint();
if (winner(row,col)) { // First, check for a winner.
if (currentPlayer == WHITE)
gameOver("WHITE wins the game!");
else
gameOver("BLACK wins the game!");
return;
boolean emptySpace = false; // Check if the board is full.
for (int i = 0; i < 15; i++)
for (int j = 0; j < 15; j++)
if (board[j] == EMPTY)
emptySpace = true;
if (emptySpace == false) {
gameOver("The game ends in a draw.");
return;
/* Continue the game. It's the other player's turn. */
if (currentPlayer == BLACK) {
currentPlayer = WHITE;
message.setText("WHITE: Make your move.");
else {
currentPlayer = BLACK;
message.setText("BLACK: Make your move.");
} // end doClickSquare()
private boolean winner(int row, int col) {
// This is called just after a piece has been played on the
// square in the specified row and column. It determines
// whether that was a winning move by counting the number
// of squares in a line in each of the four possible
// directions from (row,col). If there are 5 squares (or more)
// in a row in any direction, then the game is won.
if (count( board[row][col], row, col, 1, 0 ) >= 5)
return true;
if (count( board[row][col], row, col, 0, 1 ) >= 5)
return true;
if (count( board[row][col], row, col, 1, -1 ) >= 5)
return true;
if (count( board[row][col], row, col, 1, 1 ) >= 5)
return true;
/* When we get to this point, we know that the game is not
won. The value of win_r1, which was changed in the count()
method, has to be reset to -1, to avoid drawing a red line
on the board. */
win_r1 = -1;
return false;
} // end winner()
private int count(int player, int row, int col, int dirX, int dirY) {
// Counts the number of the specified player's pieces starting at
// square (row,col) and extending along the direction specified by
// (dirX,dirY). It is assumed that the player has a piece at
// (row,col). This method looks at the squares (row + dirX, col+dirY),
// (row + 2*dirX, col + 2*dirY), ... until it hits a square that is
// off the board or is not occupied by one of the players pieces.
// It counts the squares that are occupied by the player's pieces.
// Furthermore, it sets (win_r1,win_c1) to mark last position where
// it saw one of the player's pieces. Then, it looks in the
// opposite direction, at squares (row - dirX, col-dirY),
// (row - 2*dirX, col - 2*dirY), ... and does the same thing.
// Except, this time it sets (win_r2,win_c2) to mark the last piece.
// Note: The values of dirX and dirY must be 0, 1, or -1. At least
// one of them must be non-zero.
int ct = 1; // Number of pieces in a row belonging to the player.
int r, c; // A row and column to be examined
r = row + dirX; // Look at square in specified direction.
c = col + dirY;
while ( r >= 0 && r < 15 && c >= 0 && c < 15 && board[r][c] == player ) {
// Square is on the board and contains one of the players's pieces.
ct++;
r += dirX; // Go on to next square in this direction.
c += dirY;
win_r1 = r - dirX; // The next-to-last square looked at.
win_c1 = c - dirY; // (The LAST one looked at was off the board or
// did not contain one of the player's pieces.
r = row - dirX; // Look in the opposite direction.
c = col - dirY;
while ( r >= 0 && r < 15 && c >= 0 && c < 15 && board[r][c] == player ) {
// Square is on the board and contains one of the players's pieces.
ct++;
r -= dirX; // Go on to next square in this direction.
c -= dirY;
win_r2 = r + dirX;
win_c2 = c + dirY;
// At this point, (win_r1,win_c1) and (win_r2,win_c2) mark the endpoints
// of the line of pieces belonging to the player.
return ct;
} // end count()
public void paintComponent(Graphics g) {
super.paintComponent(g); // Fill with background color, lightGray
/* Draw a two-pixel black border around the edges of the canvas,
and draw grid lines in darkGray. */
g.setColor(Color.darkGray);
for (int i = 1; i < 15; i++) {
g.drawLine(1 + 15*i, 0, 1 + 15*i, getSize().height);
g.drawLine(0, 1 + 15*i, getSize().width, 1 + 15*i);
g.setColor(Color.black);
g.drawRect(0,0,getSize().width-1,getSize().height-1);
g.drawRect(1,1,getSize().width-3,getSize().height-3);
/* Draw the pieces that are on the board. */
for (int row = 0; row < 15; row++)
for (int col = 0; col < 15; col++)
if (board[row][col] != EMPTY)
drawPiece(g, board[row][col], row, col);
/* If the game has been won, then win_r1 >= 0. Draw a line to mark
the five winning pieces. */
if (win_r1 >= 0)
drawWinLine(g);
} // end paintComponent()
private void drawPiece(Graphics g, int piece, int row, int col) {
// Draw a piece in the square at (row,col). The color is specified
// by the piece parameter, which should be either BLACK or WHITE.
if (piece == WHITE)
g.setColor(Color.white);
else
g.setColor(Color.black);
g.fillOval(3 + 15*col, 3 + 15*row, 10, 10);
private void drawWinLine(Graphics g) {
// Draw a 2-pixel wide red line from the middle of the square at
// (win_r1,win_c1) to the middle of the square at (win_r2,win_c2).
// This routine is called to mark the 5 pieces that won the game.
// The values of the variables are set in the count() method.
g.setColor(Color.red);
g.drawLine( 8 + 15*win_c1, 8 + 15*win_r1, 8 + 15*win_c2, 8 + 15*win_r2 );
if (win_r1 == win_r2)
g.drawLine( 8 + 15*win_c1, 7 + 15*win_r1, 8 + 15*win_c2, 7 + 15*win_r2 );
else
g.drawLine( 7 + 15*win_c1, 8 + 15*win_r1, 7 + 15*win_c2, 8 + 15*win_r2 );
public Dimension getPreferredSize() {
// Specify desired size for this component. Note:
// the size MUST be 172 by 172.
return new Dimension(220, 220);
public Dimension getMinimumSize() {
return new Dimension(220, 220);
public Dimension getMaximumSize() {
return new Dimension(220, 220);
public void mousePressed(MouseEvent evt) {
// Respond to a user click on the board. If no game is
// in progress, show an error message. Otherwise, find
// the row and column that the user clicked and call
// doClickSquare() to handle it.
if (gameInProgress == false)
message.setText("Click \"New Game\" to start a new game.");
else {
int col = (evt.getX() - 2) / 15;
int row = (evt.getY() - 2) / 15;
if (col >= 0 && col < 15 && row >= 0 && row < 15)
doClickSquare(row,col);
public void mouseReleased(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
} // end nested class Board
} // end class GoMokuThis'll do it.
regards,
Owen
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GoMoku1 extends JFrame
JButton newGameButton; // Button for starting a new game.
JButton resignButton; // Button that a player can use to end the
// game by resigning.
JLabel message; // Label for displaying messages to the user.
public GoMoku1 ( )
super("GoMoku1");
Container content = getContentPane(); // Content pane of applet.
content.setLayout(null); // I will do the layout myself.
content.setBackground(new Color(0, 150, 0)); // Dark green background.
Board board = new Board(); // Note: The constructor for the
// board also creates the buttons
// and label.
content.add(board);
content.add(newGameButton);
content.add(resignButton);
content.add(message);
/* Set the position and size of each component by calling
its setBounds() method. */
board.setBounds(16, 16, 220, 220);
newGameButton.setBounds(310, 60, 120, 30);
resignButton.setBounds(310, 120, 120, 30);
message.setBounds(0, 350, 350, 30);
public static void main(String[] args)
GoMoku1 gm = new GoMoku1();
gm.setSize ( 640, 480 );
gm.setVisible(true);
gm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// ----------------------- Nested class -----------------------------------
class Board extends JPanel implements ActionListener, MouseListener
int[][] board; // The data for the board is kept here. The values
// in this array are chosen from the following constants.
static final int EMPTY = 0, // Represents an empty square.
WHITE = 1, // A white piece.
BLACK = 2; // A black piece.
boolean gameInProgress; // Is a game currently in progress?
int currentPlayer; // Whose turn is it now? The possible values
// are WHITE and BLACK. (This is valid only while
// a game is in progress.)
int win_r1, win_c1, win_r2, win_c2; // When a player wins by getting five or more
// pieces in a row, the squares at the
// ends of the row are (win_r1,win_c1)
// and (win_r2,win_c2). A red line is
// drawn between these squares. When there
// are no five pieces in a row, the value of
// win_r1 is -1. The values are set in the
// count() method. The value of win_r1 is
// tested in the paintComponent() method.
public Board ( )
// Constructor. Create the buttons and label. Listen for mouse
// clicks and for clicks on the buttons. Create the board and
// start the first game.
setBackground(Color.lightGray);
addMouseListener(this);
resignButton = new JButton("Resign");
resignButton.addActionListener(this);
newGameButton = new JButton("New Game");
newGameButton.addActionListener(this);
message = new JLabel("", JLabel.CENTER);
message.setFont(new Font("Serif", Font.BOLD, 14));
message.setForeground(Color.green);
board = new int[15][15];
doNewGame();
public void actionPerformed(ActionEvent evt)
// Respond to user's click on one of the two buttons.
Object src = evt.getSource();
if (src == newGameButton)
doNewGame();
else if (src == resignButton)
doResign();
void doNewGame()
// Begin a new game.
if (gameInProgress == true)
// This should not be possible, but it doesn't
// hurt to check.
message.setText("Finish the current game first!");
return;
for (int row = 0; row < 15; row++)
// Fill the board with EMPTYs
for (int col = 0; col < 15; col++)
board[row][col] = EMPTY;
currentPlayer = BLACK; // BLACK moves first.
message.setText("BLACK: Make your move.");
gameInProgress = true;
newGameButton.setEnabled(false);
resignButton.setEnabled(true);
win_r1 = -1; // This value indicates that no red line is to be drawn.
repaint();
void doResign()
// Current player resigns. Game ends. Opponent wins.
if (gameInProgress == false)
// This should not be possible.
message.setText("There is no game in progress!");
return;
if (currentPlayer == WHITE)
message.setText("WHITE resigns. BLACK wins.");
else
message.setText("BLACK resigns. WHITE wins.");
newGameButton.setEnabled(true);
resignButton.setEnabled(false);
gameInProgress = false;
void gameOver(String str)
// The game ends. The parameter, str, is displayed as a message.
message.setText(str);
newGameButton.setEnabled(true);
resignButton.setEnabled(false);
gameInProgress = false;
void doClickSquare(int row, int col)
// This is called by mousePressed() when a player clicks on the
// square in the specified row and col. It has already been checked
// that a game is, in fact, in progress.
/* Check that the user clicked an empty square. If not, show an
error message and exit. */
if (board[row][col] != EMPTY)
if (currentPlayer == BLACK)
message.setText("BLACK: Please click an empty square.");
else
message.setText("WHITE: Please click an empty square.");
return;
/* Make the move. Check if the board is full or if the move
is a winning move. If so, the game ends. If not, then it's
the other user's turn. */
board[row][col] = currentPlayer; // Make the move.
repaint();
if (winner(row, col))
{ // First, check for a winner.
if (currentPlayer == WHITE)
gameOver("WHITE wins the game!");
else
gameOver("BLACK wins the game!");
return;
boolean emptySpace = false; // Check if the board is full.
for (int i = 0; i < 15; i++)
for (int j = 0; j < 15; j++)
if (board[i][j] == EMPTY)
emptySpace = true;
if (emptySpace == false)
gameOver("The game ends in a draw.");
return;
/* Continue the game. It's the other player's turn. */
if (currentPlayer == BLACK)
currentPlayer = WHITE;
message.setText("WHITE: Make your move.");
else
currentPlayer = BLACK;
message.setText("BLACK: Make your move.");
} // end doClickSquare()
private boolean winner(int row, int col)
// This is called just after a piece has been played on the
// square in the specified row and column. It determines
// whether that was a winning move by counting the number
// of squares in a line in each of the four possible
// directions from (row,col). If there are 5 squares (or more)
// in a row in any direction, then the game is won.
if (count(board[row][col], row, col, 1, 0) >= 5)
return true;
if (count(board[row][col], row, col, 0, 1) >= 5)
return true;
if (count(board[row][col], row, col, 1, -1) >= 5)
return true;
if (count(board[row][col], row, col, 1, 1) >= 5)
return true;
/* When we get to this point, we know that the game is not
won. The value of win_r1, which was changed in the count()
method, has to be reset to -1, to avoid drawing a red line
on the board. */
win_r1 = -1;
return false;
} // end winner()
private int count(int player, int row, int col, int dirX, int dirY)
// Counts the number of the specified player's pieces starting at
// square (row,col) and extending along the direction specified by
// (dirX,dirY). It is assumed that the player has a piece at
// (row,col). This method looks at the squares (row + dirX, col+dirY),
// (row + 2*dirX, col + 2*dirY), ... until it hits a square that is
// off the board or is not occupied by one of the players pieces.
// It counts the squares that are occupied by the player's pieces.
// Furthermore, it sets (win_r1,win_c1) to mark last position where
// it saw one of the player's pieces. Then, it looks in the
// opposite direction, at squares (row - dirX, col-dirY),
// (row - 2*dirX, col - 2*dirY), ... and does the same thing.
// Except, this time it sets (win_r2,win_c2) to mark the last piece.
// Note: The values of dirX and dirY must be 0, 1, or -1. At least
// one of them must be non-zero.
int ct = 1; // Number of pieces in a row belonging to the player.
int r, c; // A row and column to be examined
r = row + dirX; // Look at square in specified direction.
c = col + dirY;
while (r >= 0 && r < 15 && c >= 0 && c < 15 && board[r][c] == player)
// Square is on the board and contains one of the players's pieces.
ct++;
r += dirX; // Go on to next square in this direction.
c += dirY;
win_r1 = r - dirX; // The next-to-last square looked at.
win_c1 = c - dirY; // (The LAST one looked at was off the board or
// did not contain one of the player's pieces.
r = row - dirX; // Look in the opposite direction.
c = col - dirY;
while (r >= 0 && r < 15 && c >= 0 && c < 15 && board[r][c] == player)
// Square is on the board and contains one of the players's pieces.
ct++;
r -= dirX; // Go on to next square in this direction.
c -= dirY;
win_r2 = r + dirX;
win_c2 = c + dirY;
// At this point, (win_r1,win_c1) and (win_r2,win_c2) mark the endpoints
// of the line of pieces belonging to the player.
return ct;
} // end count()
public void paintComponent(Graphics g)
super.paintComponent(g); // Fill with background color, lightGray
/* Draw a two-pixel black border around the edges of the canvas,
and draw grid lines in darkGray. */
g.setColor(Color.darkGray);
for (int i = 1; i < 15; i++)
g.drawLine(1 + 15 * i, 0, 1 + 15 * i, getSize().height);
g.drawLine(0, 1 + 15 * i, getSize().width, 1 + 15 * i);
g.setColor(Color.black);
g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);
g.drawRect(1, 1, getSize().width - 3, getSize().height - 3);
/* Draw the pieces that are on the board. */
for (int row = 0; row < 15; row++)
for (int col = 0; col < 15; col++)
if (board[row][col] != EMPTY)
drawPiece(g, board[row][col], row, col);
/* If the game has been won, then win_r1 >= 0. Draw a line to mark
the five winning pieces. */
if (win_r1 >= 0)
drawWinLine(g);
} // end paintComponent()
private void drawPiece(Graphics g, int piece, int row, int col)
// Draw a piece in the square at (row,col). The color is specified
// by the piece parameter, which should be either BLACK or WHITE.
if (piece == WHITE)
g.setColor(Color.white);
else
g.setColor(Color.black);
g.fillOval(3 + 15 * col, 3 + 15 * row, 10, 10);
private void drawWinLine(Graphics g)
// Draw a 2-pixel wide red line from the middle of the square at
// (win_r1,win_c1) to the middle of the square at (win_r2,win_c2).
// This routine is called to mark the 5 pieces that won the game.
// The values of the variables are set in the count() method.
g.setColor(Color.red);
g.drawLine(8 + 15 * win_c1, 8 + 15 * win_r1, 8 + 15 * win_c2, 8 + 15 * win_r2);
if (win_r1 == win_r2)
g.drawLine(8 + 15 * win_c1, 7 + 15 * win_r1, 8 + 15 * win_c2, 7 + 15 * win_r2);
else
g.drawLine(7 + 15 * win_c1, 8 + 15 * win_r1, 7 + 15 * win_c2, 8 + 15 * win_r2);
public Dimension getPreferredSize()
// Specify desired size for this component. Note:
// the size MUST be 172 by 172.
return new Dimension(220, 220);
public Dimension getMinimumSize()
return new Dimension(220, 220);
public Dimension getMaximumSize()
return new Dimension(220, 220);
public void mousePressed(MouseEvent evt)
// Respond to a user click on the board. If no game is
// in progress, show an error message. Otherwise, find
// the row and column that the user clicked and call
// doClickSquare() to handle it.
if (gameInProgress == false)
message.setText("Click \"New Game\" to start a new game.");
else
int col = (evt.getX() - 2) / 15;
int row = (evt.getY() - 2) / 15;
if (col >= 0 && col < 15 && row >= 0 && row < 15)
doClickSquare(row, col);
public void mouseReleased(MouseEvent evt)
public void mouseClicked(MouseEvent evt)
public void mouseEntered(MouseEvent evt)
public void mouseExited(MouseEvent evt)
} // end nested class Board
} // end class GoMoku -
Need help to draw recangle on video
Hi guys ,
Below I have pasted my code . In this code I have defined frame and in that frame stored video run. The other class has defined rectangle in cnvas . My problem is that I want rectangle to be drawn on video player and I havnt been successful.
So its my reequest to please help me out.
Thanks a ton in advance........
public class Map extends JFrame
* MAIN PROGRAM / STATIC METHODS
public static void main(String args[])
Map mdi = new Map();
static void Fatal(String s)
MessageBox mb = new MessageBox("JMF Error", s);
* VARIABLES
JMFrame jmframe = null;
JDesktopPane desktop;
FileDialog fd = null;
CheckboxMenuItem cbAutoLoop = null;
Player player = null;
Player newPlayer = null;
//JPanel glass = null;
SelectionArea drawingPanel;
String filename;
// code//
//ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
// boolean stop=false;
* METHODS
public Map()
super("Java Media Player");
drawingPanel = new SelectionArea(this);
// Add the desktop pane
setLayout( new BorderLayout() );
desktop = new JDesktopPane();
desktop.setDoubleBuffered(true);
add("Center", desktop);
setMenuBar(createMenuBar());
setSize(640, 480);
setVisible(true);
//add(drawingPanel);
//drawingPanel.setVisible(true);
try
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
catch (Exception e)
System.err.println("Could not initialize java.awt Metal lnf");
addWindowListener( new WindowAdapter()
public void windowClosing(WindowEvent we)
System.exit(0);
Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, new Boolean(true));
private MenuBar createMenuBar()
ActionListener al = new ActionListener()
public void actionPerformed(ActionEvent ae)
String command = ae.getActionCommand();
if (command.equals("Open"))
if (fd == null)
fd = new FileDialog(Map.this, "Open File",
FileDialog.LOAD);
fd.setDirectory("/movies");
fd.show();
if (fd.getFile() != null)
String filename = fd.getDirectory() + fd.getFile();
openFile("file:" + filename);
else if (command.equals("Exit"))
dispose();
System.exit(0);
MenuItem item;
MenuBar mb = new MenuBar();
// File Menu
Menu mnFile = new Menu("File");
mnFile.add(item = new MenuItem("Open"));
item.addActionListener(al);
mnFile.add(item = new MenuItem("Exit"));
item.addActionListener(al);
// Options Menu
Menu mnOptions = new Menu("Options");
cbAutoLoop = new CheckboxMenuItem("Auto replay");
cbAutoLoop.setState(true);
mnOptions.add(cbAutoLoop);
mb.add(mnFile);
mb.add(mnOptions);
return mb;
* Open a media file.
public void openFile(String filename)
String mediaFile = filename;
Player player = null;
// URL for our media file
URL url = null;
try
// Create an url from the file name and the url to the
// document containing this applet.
if ((url = new URL(mediaFile)) == null)
Fatal("Can't build URL for " + mediaFile);
return;
// Create an instance of a player for this media
try
player = Manager.createPlayer(url);
catch (NoPlayerException e)
Fatal("Error: " + e);
catch (MalformedURLException e)
Fatal("Error:" + e);
catch (IOException e)
Fatal("Error:" + e);
if (player != null)
this.filename = filename;
JMFrame jmframe = new JMFrame(player, filename);
desktop.add(jmframe);
if (player.getVisualComponent() != null)
getContentPane().add(player.getVisualComponent());
player.start();
jmframe.add(drawingPanel);
drawingPanel.setVisible(true);
/*validate();
public void paint(Graphics g)
drawingPanel.repaint();
public void update(Graphics g)
paint(g);
drawingPanel.repaint();
class SelectionArea extends Canvas implements ActionListener, MouseListener, MouseMotionListener
Rectangle currentRect;
Map controller;
//for double buffering
Image image;
Graphics offscreen;
public SelectionArea(Map controller)
super();
this.controller = controller;
addMouseListener(this);
addMouseMotionListener(this);
public void actionPerformed(ActionEvent ae)
repaintoffscreen();
public void repaintoffscreen()
image = createImage(this.getWidth(), this.getHeight());
offscreen = image.getGraphics();
Dimension d = size();
if(currentRect != null)
//Rectangle box = new Rectangle();
//box.getDrawable(currentRect, d);
Rectangle box = getDrawableRect(currentRect, d);
//Draw the box outline.
offscreen.drawRect(box.x, box.y, box.width - 1, box.height - 1);
repaint();
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me){ }
public void mouseClicked(MouseEvent me){}
public void mouseMoved(MouseEvent me){}
public void mousePressed(MouseEvent me)
currentRect = new Rectangle(me.getX(), me.getY(), 0, 0);
repaintoffscreen();
public void mouseDragged(MouseEvent me)
System.out.println("here in dragged()");
currentRect.setSize(me.getX() - currentRect.x, me.getY() - currentRect.y);
repaintoffscreen();
repaint();
public void mouseReleased(MouseEvent me)
currentRect.setSize(me.getX() - currentRect.x, me.getY() - currentRect.y);
repaintoffscreen();
repaint();
public void update(Graphics g)
paint(g);
public void paint(Graphics g)
g.drawImage(image, 0, 0, this);
Rectangle getDrawableRect(Rectangle originalRect, Dimension drawingArea)
int x = originalRect.x;
int y = originalRect.y;
int width = originalRect.width;
int height = originalRect.height;
//Make sure rectangle width and height are positive.
if (width < 0)
width = 0 - width;
x = x - width + 1;
if (x < 0)
width += x;
x = 0;
if (height < 0)
height = 0 - height;
y = y - height + 1;
if (y < 0)
height += y;
y = 0;
//The rectangle shouldn't extend past the drawing area.
if ((x + width) > drawingArea.width)
width = drawingArea.width - x;
if ((y + height) > drawingArea.height)
height = drawingArea.height - y;
return new Rectangle(x, y, width, height);
}Chances of someone reading a gazillion lines of unformatted code: < 1%
Paste your code (from the source), highlight it and click the CODE button to retain formatting and make it readable. -
Hello.
I have my project to be done by Monday.
I typed some code, but have no idea what to do anymore. No clue...
The following is the project overview etc.
Overview
In a single source file named App.java, define an Employee class to encapsulate employee data and an App class defining an applet to maintain a collection of Employee objects.
Employee Class
Define a small, non-public class named Employee that encapsulates private instance variables for name (String) and pay rate (double). The class needs a single constructor to instantiate an Employee object with values received for both instance variables. It also needs minimal set() and get() methods (such as setName(), getPayRate(), etc.) that allow a class client to store and retrieve the value of each instance variable. Do not be concerned with editing the data within this class. It is used only to support the testing of your applet.
Code this class inside your App.java source file but after the definition of the App class. Be sure to omit the specification of public in the class header (because Java only allows one public class per source file).
App class
This public class will define the processing of your applet. Its required features are as follows:
Input Components:
Name (a TextField). For entering or displaying an employee's name.
Pay rate (a TextField). For entering or displaying an employee's pay rate. When used for input, the value must be edited (see the processing notes below). If the value is invalid, display an appropriate error message.
First (a button). When clicked, triggers the display of the name and pay rate of the first employee in the collection. If the collection is empty, display an appropriate message.
Next (a button). When clicked, triggers the display of the name and pay rate of the next employee in the collection. If there are no more objects in the collection, display an appropriate message.
Find (a button). When clicked, triggers the display of the name and pay rate of the employee whose name currently appears in the name text field. If the requested employee doesn't exist, display an appropriate error message.
Add (a button). When clicked, triggers the construction of an Employee object having the currently displayed name and pay rate and the addition of the object to the collection. Display appropriate error messages if input data is missing or incorrect or if the employee already exists within the collection.
Delete (a button). When clicked, triggers the deletion of the Employee object having the currently displayed name from the collection. If the specified employee doesn't exist, display an appropriate error message.
Output components:
Number of employees (a Label). For displaying how many Employee objects are currently within the collection. This must be changed as employees are added or deleted from the collection.
Message area (a TextArea). For displaying messages.
Processing notes:
The applet must get the value of an HTML parameter named "maxRate". Convert the associated value string to a double and use it to edit a pay rate entered by the user. It represents the maximum allowable pay rate for an employee. If an attempt is made to enter a larger pay rate, display an appropriate error message.
Use GridBagLayout for the applet's components. The arrangement of components is up to you.
Use a SortedMap implemented as a TreeMap for the collection. It is to be maintained in ascending order based upon employee name.
When the user moves the mouse to touch one of the buttons, its color or font should change. When the mouse exits the button, its color or font should return to normal.
The following is the code I have so far
<CODE>
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class App extends Applet implements ActionListener, MouseListener,
MouseMotionListener{
// Instance variables for the employees' name and pay rate.
private String name;
private double payRate;
// Instance variables for referencing the Employee name heading and its text field.
private Label nameLabel;
private TextField nameField;
// Instance variables for referencing the pay rate heading and its text field.
private Label payRateLabel;
private TextField payRateField;
// Instance variables for referencing the number of employees' heading and
// its text field.
private Label empNumLabel;
private TextField empNumField;
// Instance variables for referencing the "First", "Next", "Find", "Add", and
// "Delete" button.
private Button firstBtn;
private Button nextBtn;
private Button findBtn;
private Button addBtn;
private Button deleteBtn;
// Instance variables for referencing the message area.
private TextArea msg;
public static void main(String[] args){
SortedMap m = new TreeMap();
// This method defines initial (one-time) applet processing.
public void init(){
// Set the size and background/foreground color for the applet window.
setSize(250, 350);
setBackground(Color.lightGray);
setForeground(Color.green);
// Choose GridBagLayout and create a GridBagConstraints object for use in
// laying out components to be added to hte container.
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Initialize constraints to stretch small components to fill their entire
// display area, give all rows equal height when distributing extra vertical
// space, and give all columns equal width when distributing extra horizontal
// space.
c.fill=GridBagConstraints.BOTH;
c.anchor = GridBagConstrainst.CENTER;
c.weightx = 1;
c.weighty = 1;
// Build Employee Name label and add it to the top-left cell in the layout.
nameLabel = new Label ("Employee Name");
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
add (nameLabel, c);
// Build Employee Name text field and add it to x=1, y=0 in the layout.
nameField = new TextField (30);
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 1;
// or c.gridwidth = GridBagConstraints.REMAINDER; //Last on row.
c.gridheight = 1;
add (nameField, c);
// Build Pay Rate label and add it to the second row, first column in the layout.
payRateLabel = new Label ("Pay Rate");
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
add (payRateLabel, c);
// Build Pay Rate text field and add it to x=1, y=1 in the layout.
payRateField = new TextField (8);
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
// or c.gridwidth = GridBagConstraints.REMAINDER; //Last on row.
c.gridheight = 1;
add (payRateField, c);
// Build number of employee label and add it to x=1, y=2 in the layout.
empNumLabel = new Label ("Number of Employees");
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
add(empNumLabel, c);
// Build number of employee text field and add it to x=2, y=2 in the layout.
empNumField = new TextField (5);
c.gridx = 2;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
add(empNumField, c);
// Create the "ADD" button and add it to the x=1, y=3 in the layout.
addBtn = new Button ("Add");
addBtn.setBackground(Color.red);
addBtn.setForeground(Color.black);
addBtn.addActionListener(
new ActionListener() {
public void actionPerformed (ActionEvent e){
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 1;
add(addBtn, c);
// Create the "DELETE" button and add it to the x=2, y=3 in the layout.
deleteBtn = new Button ("Delete");
deleteBtn.setBackground(Color.red);
deleteBtn.setForeground(Color.black);
deleteBtn.addActionListener(
new ActionListener() {
public void actionPerformed (ActionEvent e){
c.gridx = 2;
c.gridy = 3;
c.gridwidth = 1;
c.gridheight = 1;
add(deleteBtn, c);
// Create the "FIRST" button and add it to the x=0, y=4 in the layout.
firstBtn = new Button ("First");
firstBtn.setBackground(Color.red);
firstBtn.setForeground(Color.black);
firstBtn.addActionListener(
new ActionListener() {
public void actionPerformed (ActionEvent e){
c.gridx = 0;
c.gridy = 4;
c.gridwidth = 1;
c.gridheight = 1;
add(firstBtn, c);
// Create the "NEXT" button and add it to the x=1, y=4 in the layout.
nextBtn = new Button ("Next");
nextBtn.setBackground(Color.red);
nextBtn.setForeground(Color.black);
nextBtn.addActionListener(
new ActionListener() {
public void actionPerformed (ActionEvent e){
c.gridx = 1;
c.gridy = 4;
c.gridwidth = 1;
c.gridheight = 1;
add(nextBtn, c);
// Create the "FIND" button and add it to the x=2, y=4 in the layout.
findBtn = new Button ("Find");
findBtn.setBackground(Color.red);
findBtn.setForeground(Color.black);
findBtn.addActionListener(
new ActionListener() {
public void actionPerformed (ActionEvent e){
c.gridx = 2;
c.gridy = 4;
c.gridwidth = 1;
c.gridheight = 1;
add(findBtn, c);
// Create message are and add it to x=0, y=5 in the layout.
msg = new TextArea (5, 20);
c.gridx = 0;
c.gridy = 5;
c.gridwidth = GridBagConstraints.REMAINDER; // Last on row
c.gridheight = 1;
add(msg, c);
//???????????????????????????????????????????????/////////////////////////???????????????????????????????????????????????///////////////////////public void setName (String newName){
name = newName;
public void setPayRate (double newPayRate){
payRate = newPayRate;
public void getName () {
return name;
public void getPayRate() {
return payRate;
//Change color of Button
public void mouseEntered (MouseEvent e){
Color oldBackground = addBtn.getBackground();
addBtn.setBackground(addBtn.getForeground());
addBtn.setForeground(oldBackground);
public void mouseExited (MouseEvent e){
Color oldBackground = addBtn.getBackground();
addBtn.setBackground(addBtn.getForeground());
addBtn.setForeground(oldBackground);
</CODE>
I don't know where to put Employee class.
I don't know what to do anymore...
I'm soooooooooooooo stuck and just want to cry...
Please give me any suggestion/help so that I could move on.
Thank you so much in advanceStep 1 (analying your specs).
In a single source file named App.java, define an Employee class to encapsulate employee data and an App class defining an applet to maintain a collection of Employee objects.
You are given lots of usefule information.
Name of the primary (source) class to create App
Primary class (source) will include an employee class.
The need to maintain a collection (list) of employee classes.
first thing i do is
public class App {
Vector myEmps = new Vector();// will hold the employee objects;
Employee emp; // single instance of an employee object
App() {
// this is how we add employee objects to the list
// in this case the list is a vector.
myEmps.add(new Employee("sean",1,80000.50));
myEmps.add(new Employee("davey",1,70000.25));
myEmps.add(new Employee("harry",1,90000.15));
class Employee {
// define employee data as variables
String name;
int ID;
double payRate;
Employee(String n, int ID, double pr) {
this.name = n;
this.ID = ID;
this.payRate = pr;
public void setName(String n) { // can set/change emps name
name = n;
public void setPayRate(double pr) { // can set/change payRate
payRate = pr;
}this is just a start -
Is there any problems in IE if using RMI.?
Hello buddies,
this is my 3rd attempt to get answer. before it i tried 2 times but didn't get answered.
actually i m making a chat application. in that there is a canvas on which we can draw something and send it to all users. i make an applet and from within the applet i m calling a frame. all this awt components like canvas and buttons etc. displays in the frame. applet is just a platform do call the frame. i m using RMI to do the chat. i tried to run it first in appletviewer and it works fine. but when i tried to run in IE from <applet> tag no frame is displays. i am trying to solve it from last 20 days but still unsolved. here is the code if anybody wishes to try it.
// clinet frame...
import java.rmi.*;
import java.rmi.server.*;
import canvas.Drawer;
import java.awt.*;
import java.applet.*;
import java.applet.Applet;
import java.awt.event.*;
import java.util.*;
import ru.zhuk.graphics.*;
/*<applet code="ChatClient" width=600 height=300>
</applet>
public class ChatClient extends Frame implements IChatClient,ActionListener,MouseListener,MouseMotionListener
// GLOBAL VARIABLES USED IN THE PROGRAMME...
boolean flag=false;
int n;
String str="";
String Coord=null;
IChatService service=null;
FrameApplet fa=null;
TextField servername,serverport,username;
Button connect,disconnect;
TextField message;
Button send,sendText;
TextArea fromserver;
int i=0,j=0;
int x[] = new int[1000];
int y[] = new int[1000];
Drawer canvas;
boolean connected=false;
String title,user="";
// Class Members //
public ChatClient()
public ChatClient(String str)
super(str);
setBounds(50,20,600,450);
setLayout(new FlowLayout(FlowLayout.CENTER,45,10));
title=str;
setStatus();
// Create controls //
add(new Label("Chat Server Name : "));
servername=new TextField(20);
add(servername);
servername.setText("localhost");
add(new Label("Chat Server Port : "));
serverport=new TextField(20);
add(serverport);
serverport.setText("900");
add(new Label("Your User Name : "));
username=new TextField(20);
add(username);
username.setText("Umesh");
connect=new Button("Connect");
connect.addActionListener(this);
add(connect);
disconnect=new Button("Disconnect");
disconnect.addActionListener(this);
add(disconnect);
message=new TextField(30);
add(message);
sendText=new Button("Send Text");
sendText.addActionListener(this);
add(sendText);
fromserver=new TextArea(10,50);
add(fromserver);
fromserver.setEditable(false);
canvas = new Drawer();
canvas.setSize(250,250);
canvas.setBackground(Color.cyan);
add(canvas);
canvas.addMouseListener(this);
canvas.addMouseMotionListener(this);
send=new Button("Send");
send.addActionListener(this);
add(send);
try
UnicastRemoteObject.exportObject(this);
catch(Exception e)
setVisible(true);
for(j=0;j<1000;j++)
x[j]=0;
y[j]=0;
Coord = new String();
Coord = "";
// fa=new FrameApplet();
public void mousePressed(MouseEvent me){}
public void mouseReleased(MouseEvent me)
Coord = Coord + "r";
public void mouseClicked(MouseEvent me){}
public void mouseEntered(MouseEvent me){}
public void mouseExited(MouseEvent me){}
public void mouseDragged(MouseEvent me)
if (Coord == "")
Coord = me.getX() + "," + me.getY();
else
Coord = Coord + " " + me.getX() + "," + me.getY();
public void mouseMoved(MouseEvent me){}
// RMI connection //
private void connect()
try
service = (IChatService)Naming.lookup("rmi://pcname/ChatService");
service.addClient(this);
connected=true;
setStatus();
user=username.getText();
Coord = "";
catch(Exception e)
fromserver.append("Error Connecting ...\n" + e);
System.out.println(e);
connected=false;
setStatus();
service=null;
private void disconnect()
try
if(service==null)
return;
service.removeClient(this);
service=null;
catch(Exception e)
fromserver.append("Error Connecting ...\n");
finally
connected=false;
setStatus();
private void setStatus()
if(connected)
setTitle(title+" : Connected");
else
setTitle(title+" : Not Connected");
// IChatClient methods //
public String getName()
return user;
public void sendMessage(String msg)
fromserver.append(msg+"\n");
public void SendCanvasObject(String str)
this.str = str;
fromserver.append(str + "\n");
Graphics g = canvas.getGraphics();
paint(g);
// Actionlistener //
public void actionPerformed(ActionEvent e)
if(e.getSource()==connect)
connect();
if(connected)
servername.setEnabled(false);
serverport.setEnabled(false);
username.setEnabled(false);
connect.setEnabled(false);
Coord = "";
else
if(e.getSource()==disconnect)
disconnect();
servername.setEnabled(true);
serverport.setEnabled(true);
username.setEnabled(true);
connect.setEnabled(true);
else
if(e.getSource()==send)
flag = true;
if(service==null)
return;
try
fromserver.append("Sending an image...\n");
service.SendCanvasObject(this,Coord);
i=0;
for(j=0;j<1000;j++)
x[j]=0;
y[j]=0;
Coord = "";
fromserver.append("\n" + "Image Sent...");
catch(RemoteException re)
fromserver.append("Error Sending Message ...\n" + re);
catch(Exception ee)
fromserver.append("Error Sending Message ...\n" + ee);
else
if(e.getSource()==sendText)
if(service==null)
return;
try
service.sendMessage(this,message.getText());
message.setText("");
catch(RemoteException exp)
fromserver.append("Remote Error Sending Message ...\n" + exp);
catch(Exception ee)
fromserver.append("Error Sending Message ...\n" + ee);
public void paint(Graphics g)
if(flag==true)
i=0;
StringTokenizer stoken = new StringTokenizer(str,"r");
String strin = "";
while(stoken.hasMoreTokens())
strin = stoken.nextToken();
fromserver.append("\n" + strin + "\n");
StringTokenizer stoken1 = new StringTokenizer(strin," ");
String strin1 = "";
j=0;
while(stoken1.hasMoreTokens())
strin1 = stoken1.nextToken();
fromserver.append("\n" + strin1 + "\n");
x[j]=Integer.parseInt(strin1.substring(0,strin1.indexOf(",")));
y[j]=Integer.parseInt(strin1.substring(strin1.indexOf(",")+1,strin1.length()));
j++;
for(int k=0;k<j-1;k++)
g.drawLine(x[k],y[k],x[k+1],y[k+1]);
i++;
import java.rmi.*;
import java.rmi.server.*;
import canvas.Drawer;
import java.util.*;
import ru.zhuk.graphics.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class FrameApplet extends Applet implements ActionListener
ChatClient f;
public void init()
Button b = new Button("Start Chat");
b.addActionListener(this);
add(b);
public void actionPerformed(ActionEvent ae)
f=new ChatClient("Chat");
f.show();
f.setSize(400,400);
here is html file which i calls from IE
<html>
<title>Micky Chat</title>
<body>
<br>
<br>
<center>
<applet code="FrameApplet.class" width=200 height=200>
</applet>
</center>
</body>
</html>
and at last a shocking thing is it is runs in Netscape displaying frames but not calling paint method.
pls. help me
thanks a lot
umeshHi Umesh!
Sorry that I cannot be too concrete about that since it has to be centuries ago when I fell over this problem.
As far as I can remember, the JDK provided by MS has no RMI built-in. These was probably one of the main reasons why Sun sued Microsoft concering its handling of Java.
Afterwards MS released a path for its Java Runtime that included RMI support, but AFAIK they never included it in the standard package. So much luck when searching for the ZIP! (-;
A little bit of googling might help, e.g.:
http://groups.google.com/groups?hl=de&lr=&ie=UTF-8&oe=UTF-8&threadm=37f8ddf6.4532124%40news.online.no&rnum=17&prev=/groups%3Fq%3Dmicrosoft%2Bjvm%2Brmi%2Bsupport%26start%3D10%26hl%3Dde%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3D37f8ddf6.4532124%2540news.online.no%26rnum%3D17
cheers,
kdi -
Repaint() - problems with queueing/blocking
hello,
im writing a game as an applet using awt, but i cant get the repaint() method to execute where i would want it to.
import java.applet.* ;
import java.awt.* ;
import java.awt.event.* ; //depreciated
import java.util.* ;
public class matches_applet extends Applet
implements ActionListener , MouseListener , ItemListener {
// var declarations
// init
// reinit for starting new game
// waiter for simulating "thinking"
public void move( int srcX , int srcY , int destX , int destY ) {
//check if vaild move...
// mode : 1 = single player , 2 = mulitplayer
// player: 1 = human , 2 = human/computer
if (mode == 1 && player == 1 ) {
waiter() ; //simulate computer player "thinking"
//add move to list of done moves...
System.out.println("repaint attempt");
try {
Thread.currentThread().sleep(2000);
field.repaint();
Thread.currentThread().sleep(2000);
} catch ( Exception e ) {}
System.out.println("repaint succsessful");
if (mode == 1 && player == -1 ) {
//send human move to ai...
//receive ai move
//write ai move to vars fromX , fromY , toX , toY
move( fromX , fromY , toX , toY ) ;
// listeners
// move invoked from mouseClicked( MouseEvent mouse ){}
public class CentrePanel extends Canvas {
@Override
public void paint( Graphics g ) {
System.out.println("repaint in");
// paint stuff
System.out.println("repaint out");
}now when i attempt to move a pawn, my console prints :
repaint attempt
repaint succsessful
repaint attempt
repaint succsessful
repaint in
repaint out
for the part inside the move.
insted it should print ( correct me if im wrong ) :
repaint attempt
repaint in
repaint out
repaint succsessful
repaint attempt
repaint in
repaint out
repaint succsessful
i know that the
if (mode == 1 && player == -1 ) {...}is blocking the queue, but i dont know how to get it not to.
thx for any answers in advance,
westernmagic
Edited by: westernmagic on Feb 1, 2009 5:36 AMPete_Kirkham wrote:
An alternative approach is to bypass the event queue and call paint directly with the components Graphics object whilst in the loop.
Pete[http://forums-beta.sun.com/thread.jspa?messageID=2065345]
thanks Pete.
@ admin/mod : feel free to close.
Edited by: westernmagic on Feb 1, 2009 1:26 PM
Maybe you are looking for
-
XWS-Security, modify namespace location
Hi, we are using JWSDP 2.0 and xws-security for sign our SOAP message. We need to save the payload and the signature in a database and need to to validate it on some occations. So have to save the <Signature> Tag. The Problem is it is not valid due t
-
Dear Collageus, my requirement is to run the report from SSHR menu (not from concurrnt requiest). and I am in 12i. I cannot use the OracleOasis.runreport in 12i, its been deprecated. i have saved my report as JSP file. in the Function registration sc
-
Hi ALL, what is the correct syntax ....i get 'illegl recovery option until' when i use RECOVER DATAFILE 'COMPLETE FILENAME WITH PATH' UNTIL TIME '2006-01-28:16:00:00' ; wHAT IS THE CORRECT ONE ? Regards Sunny
-
I want to be able to print using windows remote desktop services what printers can i use?
Hi I want to use Windows Remote Desktop Services on my iMAC. I understand some printers work but some dont when printing from the VDI client. Can anyone give me a list of printers that will work with the VDI client or some work arounds so that I can
-
New release - audio bar does not show on preview
Just wondering - I really need this to work. The audio is set to visible. Tested in FF, Chrome and Safari on Windows.