The line 23 should be replaced by
if ((suit !='C') || (suit !='D') || (suit !='H') || (suit !='S'))
If your intention is logical OR.
Probably, your intention is logical AND as javaAddict indicated(?).
The line 23 should be replaced by
if ((suit !='C') || (suit !='D') || (suit !='H') || (suit !='S'))
If your intention is logical OR.
Probably, your intention is logical AND as javaAddict indicated(?).
prem2,
Thank you for your quick response. Do you mean in my code, I can not place abstract method show() in it. If so I agree with you.
How do we say:
For the interface MouseListener there are 5 abstract methods declared:
void mouseClicked(MouseEvent e)
void mouseEntered(MouseEvent e)
void mouseExited(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
I wounder if the word "declared" used here is valid or not.
You may define an interface or abstract class where an abstract method void show() exists. If you are going to declare an abstract method void show() , for example, in an abstract class, you have to place the keyword abstract at first. Of course, in this case one may not have any instance from it. That's why in your/mine program, if an abstract method is declared, it cann't have object from it, i.e. it doen't work.
One thing you have to remember:
If you have defined some non-default constructors, the compiler will not implicitly provide a default constructor. If you need a default one you'd better define one. Otherwise it wouldn't pass compiling. For example, the following code leads to an error message for line 10:unsolved symbol
import java.io.*;
public class DefaultConstructor {
public DefaultConstructor(String s) {
System.out.println("I am Not Default with no arguments. " + s );
}
public static void main(String[] args) {
DefaultConstructor d = new DefaultConstructor();
}
}
Default constructor is the constructor with no arguments requested. It is called implicitly when creating an instance.
import java.io.*;
public class DefaultConstructor {
public DefaultConstructor() {
System.out.println("I am Default with no arguments.");
}
public static void main(String[] args) {
DefaultConstructor d = new DefaultConstructor();
}
}
output:
I am Default with no arguments.
You may declare a method (in java we call function as method) as abstract which means no definition is given, e.g.
void show();
You may declare a method with empty body, which isn't an abstract method anymore.
void show(){};
but do nothing when calling it.
Or you may define a method with its body
public void show(){ //method Definition
System.out.println("Sample Method ");
}
It is impossible by Java applet class itself to store data at the client computer due to the restriction of Java security.
However, applet class may communicate with its own server. Any demon program runs in the server may receive any information sent by the applet class at the client's computer. In this way the demon program at the server may store the data at server since the demon program does not extend Applet. Also the demon program may pass any information from one client's computer to another client's computer at different location.
jemz, it works correctly. However, it works only for one line input. IOException would be more concrete/precise than Exception. I have modified your code so that client may type in several lines of strings. Type in "end" to finish typing.
import java.io.*;
class Writefile{
public static void main(String []args)throws IOException{
String name;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new FileWriter("write.txt"));
System.out.println("Write into the file write.txt. To finish typing input \"end\".");
while(true){ //loop continues unless typing in the "end" line
name = br.readLine(); // read each line of strings you typed in
if (name.equals("end")) // check the content of input. If it is "end"
break; // then jump out of the while loop
bw.write(name + (char)10); // Add the ASCII code 10 for the character new line
}
bw.close();
}
}
"Node" is just a class name you have given. It is not a reserved word.
No. It is the security rule: Applet cann't do any operation associated with files, such as create, open, read, delete, and alter in your computer.
Thank you , jon, for your quick response and correction. Should we call it "Same Type of Reference" or "Self-Type Reference" rather than self- referencing ?
A linked list contains several Node's objects, which are connected linearly (one by another) via the attribute "next". The "next" is a reference to its next Node' instance. The type of the "next" is also Node: itself Type. Therefore, they are of not only the same type but also itself type (the type as same as itself). The relationship for linked list is one to one.
class Node{
String value; //data member
Node next; // self-Type reference, Node type reference
}
For the Linkedlist class we may call it as self-referencial class
http://www.cplusplus.com/forum/beginner/3311/
class Node { // The definition of the class Node
String value; // data member
Node next; // self referencing: referring to itself
}
Self-reference occurs in natural or formal languages when a sentence or formula refers to itself.
http://en.wikipedia.org/wiki/Self-reference
"Terminate" means cann't restart. One cann't use Applet method void start() to restart. One has to use init() to start a new run.
Due to Java security reason if a class extends Applet it cann't:
save any records on a file
open and read a file, and
alter a file.
However it may record scores in an array. As long as the program runs, one may access the data. If the program terminates all the scores recorded are lost.
import java.io.*;
import javax.swing.JOptionPane;
public class PalindromeCouplet{
static boolean palindromeCouplet (String s) {
StringBuffer s1 = new StringBuffer(s);
return ((s.compareTo(new String(s1.reverse()))==0) ? true :false) ;
}
public static void main(String[] args) {
while(true){
String str=JOptionPane.showInputDialog( null,
"Type in a string!\nPress Cancel to terminate the program",
"Palindrome or Not?",
JOptionPane.QUESTION_MESSAGE);
if (str == null) {
System.out.println("Bye for now!");
break;
}
System.out.println("Palindrome? " + palindromeCouplet(str));
}
}
}
double num = 1001.27124;
System.out.printf("%8.2f\n", num);
I added a main method so that the program runs.
public static void main(String args[]){
Display dis=new Display();
dis.setVisible(true);
dis.setSize(500,150);
dis.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
I put an icon.png in the same folder.
both the program and the button works. The problem is that the icon will be located before the text rather than after the text.
So the question has become: How to make icon inserted after the text? I think, adams161 has quoted the answer:"....the icon is effectively inserted at the current position of the caret. ". So "before inserting, put the cursor after the text" is the solution.
The output is shown in the image: icon.gif
It works in my machine. For example, you put the Main.java in the folder "forum"
Via DOS window do the following cammands:
E:\forum>javac Main.java
E:\forum>java Main
Hello everyone on the forum DaniWeb
end
so that a text file "MyFile.txt" is created where the "Hello everyone on the forum DaniWeb " is stored.
Match in size (the same width and height) or Match in the ratio of width over height, or by other criteria?
code line 17 is not correct:
BufferedReader br = new BufferedReader(new BufferedWriter((System.in)));
The argument should be a Writer object.
I have modified the program by Java source code example for your reference.
http://www.javadb.com/write-to-file-using-bufferedwriter
The data you typed in will be stored in myFile.txt
In one line type in "end" only to terminate the program.
import java.io.*;
import java.util.Scanner;
public class Main {
/**
* Type in some data to a file using a BufferedWriter via DOS
*/
public void writeToFile() {
BufferedWriter bufferedWriter = null;
BufferedReader br=null;
Scanner in = new Scanner(System.in);
try {
//Construct the BufferedWriter object
bufferedWriter = new BufferedWriter(new FileWriter("MyFile.txt"));
while(true){
String s = in.nextLine();
if (s.equals("end"))
break;
bufferedWriter.write(s);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the BufferedWriter
try {
if (bufferedWriter != null) {
bufferedWriter.flush();
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new Main().writeToFile();
}
}
Thank you for your "Why". I found I sent you a wrong version. In line code 11 if you put:
FileDialog fd = new FileDialog(null , "Open a document", FileDialog.LOAD);
you will have the error message: "the constructor file dialog is ambiguous"
However, the line of code 11:
FileDialog fd = new FileDialog(this, "Open a document", FileDialog.LOAD);
will pass compiling. Therefore, we should emphasize:
For the first argument "Frame parent" of the FileDialog constroctor one should use "this" indicating the parent Frame is the current object.
ezkonekgal ,thank you for your reply. I have checked and tested your code.
(1) You use JFileChooser which seems better than FileDialog which I use currently (because, as you reported, eclipse complains about the constructor I wrote).
(2) May I suggest you delete the "OK" button which is useless.
(3) Your code runs correctly. I have replaced your LayoutManager by FlowLayout so that components show up properly.
Attached please find the modified code. It runs correctly in my machine.
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.FileDialog;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class FileBrowse extends JFrame {
private JButton browseSwing = new JButton("Choose File");
private JTextField textField = new JTextField(30);
private JButton approve = new JButton("Ok");
public FileBrowse() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,80);
setResizable(false);
browseSwing.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource()==browseSwing)
onBrowseSwing();
}});
Container container = getContentPane();
container.setLayout(new FlowLayout());
container.add(browseSwing);
container.add(textField);
container.add(approve);
//pack();
}
protected void onBrowseSwing() {
JFileChooser fileChooser = new JFileChooser();
int result = fileChooser.showDialog(this, "Open/Save");
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
textField.setText(file.toString());
String x = file.toString();
fileRead(x);
}
}
public void fileRead(String input){
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(input);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int count = 0;
int count2 = 0;
//Read File Line By Line
while((strLine = br.readLine())!= null ){
if (strLine.trim().length() != 0){
count++;
}else{
count2++;
}
}
System.out.println("-------Lines Of COdes-------");
System.out.println("number of lines:" + count);
System.out.println("number of blank lines:" + count2);
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static void main(String[] args) {
new FileBrowse().setVisible(true);
}
}
(1) May I ask: Why only press "return key" to do something? You may do something when receiving other input string.
(2) One class may implement the interface KeyListener to listening to the keyboard.
(3) I have written a simple program using KeyAdapter to monitor the keyboard for your reference.
/* The following program is listening to the kayboard.
* DOS window output prints each character client pressed.
* When pressing return key, "Do Something" is printed.
* */
import java.awt.event.*;
import javax.swing.*;
public class Key extends JFrame{
public Key(){
setSize(200,200);
setVisible(true);
addKeyListener(new KeyAdapter(){ //anonymous class
public void keyPressed(KeyEvent e){ //call this method by pressing any key
System.out.println(e.getKeyChar()); // print any printable character
if ((int)e.getKeyChar()==10) // if pressing the "return key"
System.out.println("Do Something");// then print "Do Something"
}
});
}
public static void main(String args[]){
Key k = new Key();
k.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
You have incorrectly placed these lines of code outside of methods. This means that you are declaring attributes for your class. When you declare an array, you may initiate the String array with the corresponding values at the same time. However you wrote assignments' code during declaration, which is wrong.
String[] greeting = new String[4]; // declare an attribute of STring array. It's good.
greeting[0] = "Why, Hello there!"; // Wrong. Assignment shoud be written within a method.
greeting[1] = "Welcome.";//wrong
greeting[2] = "blah blah blah";// wrong
greeting[3] = "more useless crap";// wrong
You may write one line of code to complete the task.
String[] greeting = {"Why, Hello there!","Welcome.","blah blah blah","more useless crap"};
line 36 is not correct.
The correct code:
mb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// The value of the defined constant JFrame.EXIT_ON_CLOSE is 3
Thank you, NormR1 for your coments.
was not working
I will have a close look at tutorial on the issue of putClientProperty.
Your code shown above is correct. I have tested with a known file. The result is correct. AS long as the browsing files is concerned, as jon.kiparsky indicated, it is already available in Swing. For example, the class FileDialog is a candidate for this purpose. Since its constructor requests a parent frame , as written in Java API, the class you define has to inherit JFrame. I have modified your code as follows. You have to modify your main method accordingly. Attached please the code altered for your reference.
import java.io.*;
import java.awt.*;
import javax.swing.*;
class FileRead extends JFrame {
static File name; // it is created in constructor, then used in main
static int count =0; // count the number of lines where characters are found
static int count2=0; // count the nubmer of empty lines
public FileRead(){ // constructor for FileRead
try{
FileDialog fd = new FileDialog(this, "Open a document", FileDialog.LOAD);
fd.setDirectory(System.getProperty("user.dir")); // the window starts with current folder
fd.setVisible(true);
name= new File(fd.getDirectory(), fd.getFile());
}catch(Exception e){
System.err.println(e.getMessage());
}
setSize(400,400);
setVisible(true);
}
Good luck.
import java.io.*;
import java.awt.*;
import javax.swing.*;
class FileRead extends JFrame {
static File name;
static int count =0;
static int count2=0;
public FileRead(){
try{
FileDialog fd = new FileDialog(null, "Open a document", FileDialog.LOAD);
fd.setDirectory(System.getProperty("user.dir"));
fd.setVisible(true);
name= new File(fd.getDirectory(), fd.getFile());
}catch(Exception e){
System.err.println(e.getMessage());
}
setSize(400,400);
setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
g.drawString("Testing open file", 30,100);
g.drawString("Number of characters' lines: " + count,30,200);
g.drawString("Number of empty lines :" + count2, 30, 250);
}
public static void main(String args[]){
FileRead fr = new FileRead();
fr.setDefaultCloseOperation(2);
try{
FileInputStream fstream = new FileInputStream(name);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine = br.readLine())!= null ){
if (strLine.trim().length() != 0){
System.out.println(strLine);
count++;
}else{
count2++;
}
}
System.out.println("number of lines:" + count);
System.out.println("number of lines:" + count2);
in.close();
}catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
fr.repaint();
}
}
The following code may help you:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MultiButtons extends JFrame implements ActionListener{
JButton btn[] = new JButton[3]; // define and allocate for the array of 3 buttons
String colorName[]={"RED","BLUE","GREEN"}; // the string on each button
Color color[] = {Color.red, Color.blue, Color.green}; // Color array
Container container;
public MultiButtons(){
JPanel p = new JPanel(); // create a sub container to have 3 buttons
for (int i=0; i<btn.length;i++){ // create button and add ActionListener for each button.
btn[i]= new JButton(colorName[i]);
btn[i].addActionListener(this);
btn[i].putClientProperty( "JButton.buttonType", "roundRect" ); // setup clientProperty, as JamesCherrill indicated.
p.add(btn[i]);// put each button into the sub container
}
container= getContentPane(); // The JFrame has the default layout manager: BorderLayout
container.add(p, BorderLayout.NORTH); // the subcontainer holding 3 buttons is placed in the NORTH area
container.setBackground(color[0]); // initial background is red in color
setSize(400,200);
setVisible(true);
}
public void actionPerformed(ActionEvent e){ // the ActionListener monitoring 3 buttons.
for (int i=0; i<btn.length;i++) // using for loop to scan buttons
if (btn[i]== e.getSource()){ // the button[i] is being pressed
container.setBackground(color[i]); // re-set background color accordingly
break;
}
}
public static void main(String args[]){
MultiButtons mb= new MultiButtons();
mb.setDefaultCloseOperation(2);
}
}
e.g.
In my machine, the line code:
btn.putClientProperty( "JButton.buttonType", "roundRect" );
was not working
I tried putClientProperty() in different way. It ended with no changes in buttons' apprearence at all.
If you want the icon only. The code will be:
b2=new JButton(back);
I have made a back.gif and modified your code:
e.g. insert
Container container=getContentPane();
.....
container.add(p1);
.....
Attached please find the code modified and the image file I made. Hope it helps.
I did not add (p2). I delete the lines for login since I have no definition for it. It works
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class aboutme extends JFrame implements ActionListener
{
JMenuBar mbr;
JMenu file;
JMenuItem exit;
JPanel p1,p2;
JLabel l1,l2,l3,l4,l5,l6,l7,l8;
JButton b1,b2;
//Color c1,c2;
Font f1,f2,f3;
public aboutme()
{
Container container=getContentPane();
setVisible(true);
setSize(600,600);
mbr=new JMenuBar();
setJMenuBar(mbr);
file=new JMenu("File");
exit=new JMenuItem("exit");
p1=new JPanel();
p2=new JPanel();
l1=new JLabel("About Me");
l2=new JLabel("Online Testing! ! !");
l3=new JLabel("Project made for conducting Online tests");
l4=new JLabel("Coding and Designing by:-");
l5=new JLabel("Ashish Rai (SG 8302)");
l6=new JLabel("Karanbir Singh (SG 8321)");
l7=new JLabel("Nippon Sahore (SG 8334)");
l8=new JLabel("Varun Joshi (SG 8353)");
ImageIcon back=new ImageIcon("back.gif");
b1=new JButton("Exit");
b2=new JButton(back);
//c1=new Color(123,72,91);
//c2=new Color(64,128,200);
f1=new Font("arial",Font.BOLD,22);
f2=new Font("arial",Font.BOLD|Font.ITALIC,55);
f3=new Font("arial",Font.BOLD,18);
b1.addActionListener(this);
b2.addActionListener(this);
exit.addActionListener(this);
p1.setLayout(new BorderLayout());
l1.setBounds(50,50,250,250);
l2.setBounds(50,50,2500,75);
l3.setBounds(50,100,2500,250);
l4.setBounds(50,150,250,250);
l5.setBounds(50,200,250,250);
l6.setBounds(50,250,250,250);
l7.setBounds(50,300,250,250);
l8.setBounds(50,350,250,250);
b1.setBounds(400,450,100,50);
b2.setBounds(500,450,100,50);
//b1.setBackground(Color.blue);
//b2.setBackground(Color.blue);
b1.setFont(f3);
b2.setFont(f3);
p2.setLayout(null);
p2.add(l2);
p2.add(l3);
p2.add(l4);
p2.add(l5);
p2.add(l6);
p2.add(l7);
p2.add(l8);
p2.add(b1);
p2.add(b2);
mbr.add(file);
file.add(exit);
//p2.setBackground(c2);
p1.add(l1,BorderLayout.NORTH);
p1.add(p2,BorderLayout.CENTER);
//p1.setBackground(c1);
//l1.setForeground(Color.red);
l1.setFont(f1);
l2.setFont(f2);
l3.setFont(f3);
l4.setFont(f3);
l5.setFont(f3);
l6.setFont(f3);
l7.setFont(f3);
l8.setFont(f3);
container.add(p1);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent evt){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
{
System.exit(0);
}
else if(ae.getSource()==exit)
{
System.exit(1);
}
else if(ae.getSource()==b2)
{
//Login o2=new Login();
//o2.setSize(300,200);
//setVisible(false);
}
}
public static void main(String x[])
{
new aboutme();
}
}
Yes. In super class you may define a method to invoke the method of the subclass so that you may call the method with the super class reference.
class Superclass{
void display(){
System.out.println("Super");
}
void Sub2Display(){ // the extra method you define to call the method of its subclass
Sub2 sub2= new Sub2();
sub2.display();
}
}
class Sub1 extends Superclass{
void display(){
System.out.println("sub class1");
}
}
class Sub2 extends Sub1{
void display(){
System.out.println("Sub class2");
}
void display2(){
System.out.println("Second method");
}
}
public class reference {
public static void main(String[] args){
Superclass ref=new Sub1();
ref.display();
ref.Sub2Display(); //invoke the method of the subclass with the super class reference
//((Sub2)ref).display();
}
}
The constructor as indicated in API:
JButton(String text, Icon icon)
Create a JButton with an Icon
Therefore your code line:
b2=new JButton("Back"); // b2 is a JButton with ImageIcon
should be replaced with
b2=new JButton("Back",back);// back if the instance of ImageIcon
The constructor as indicated in API:
JButton(String text, Icon icon)
创建一个带初始文本和图标的按钮。
There fore your code line:
b2=new JButton("Back"); // b2 is a JButton with ImageIcon?
should be replaced with
b2=new JButton("Back",back);// back if the instance of ImageIcon
I have a closer look at your code and tested. Both the image file and the oval may show up although they are overlapped (at the same location). Attached please find the files I have modified. Hope the observation report may help you.
I found:
(1) in class Bullet line 49: g.drawImage(picture, xpos, ypos, width, height, null);
The ImageObserver was null so that the image never shows up
(2) I have changed the access modifiers (private) for the attributes of class Bullet with friendly so that they could be accessed in the class myApplet.
(3) Therefore, the method paint() of the class myApplet (line 101-112) can be enhanced so that the work of display() of the class Bullet can be done without calling s.paint(graphicsBuffer); (line 110)
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
graphicsBuffer.setColor(Color.white);
graphicsBuffer.fillRect(0, 0, getWidth(), getHeight());
graphicsBuffer.drawImage(s.picture, s.xpos, s.ypos, s.width, s.height, this);
graphicsBuffer.setColor(Color.red);// I have added this line of code so that the oval shows up
graphicsBuffer.fill(s.c);
g2.drawImage(imageBuffer, 0,0, getWidth(), getHeight(), this);
}
(4) The height of Applet can not be too short. Otherwise the locations of both bullet and the oval beyond the boundary.The size of the applet at least as indicated as follows
<html>
<applet code = "myApplet.class" width = 500 height = 500>
</applet>
</html>
(5) I also found that the Ellipse2D.Bouble c (very slender vertically) and the bullet at the same location so that the oval c overlapps with the bullet image.
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
public class Bullet {
Image picture;
int xpos, ypos, height, width, speed, xdir, ydir;
Ellipse2D.Double c;
public Bullet(Image p, int x, int y, int w, int h, int s, int xd)
{
picture = p;
xpos = x;
ypos = y;
width = w;
height = h;
speed = s;
xdir = xd;
ydir = 0;
c = new Ellipse2D.Double (xpos, ypos, width, height);
System.out.println("x:" + xpos + ",y:" + ypos);
}
public void move()
{
xpos = xpos + speed*xdir;
ypos = ypos + speed*ydir;
c.setFrame(xpos, ypos, width, height);
}
public int getX() { return xpos;}
public int getY() { return ypos ;}
public int getHeight() { return height; }
public int getWidth() { return width ;}
public int getXDir() { return xdir ;}
public int getYDir() { return ydir ;}
public void setPos(int a, int b) {xpos = a; ypos = b;}
public void setDir(int x, int y)
{
xdir = x;
ydir = y;
}
public boolean intersects(int x, int y, int w, int h)
{
return c.intersects(x, y, w, h);
}
public void displayBullet(Graphics2D g)
{
g.drawImage(picture, xpos, ypos, width, height, null);
}
public void paint(Graphics2D g)
{
displayBullet(g);
g.setColor(Color.red);
g.fill(c);
}
}
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.*;
import javax.swing.*;
import java.awt.image.*;
public class myApplet extends Applet implements KeyListener
{
BufferedImage imageBuffer;
Graphics2D graphicsBuffer;
private Bullet s;
private Timer t;
Image p;
public void init()
{
imageBuffer = (BufferedImage)createImage(getWidth(), getHeight());
graphicsBuffer = (Graphics2D) imageBuffer.getGraphics();
p= getImage(getCodeBase(), "sunset.jpg");
s=new Bullet(p, 20, 250, 50, 200, 20, 0);
addKeyListener(this);
setFocusable(true);
for(int j=0;j<5;j++)
{
for(int k=0;k<16;k++)
{
p= getImage(getCodeBase(), "sunset.jpg");
}
}
ActionListener z = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
s.move();
}
};
paint(graphicsBuffer);
t=new Timer(10, z);
t.start();
}
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
s.setDir(0,1); //change direction of the paddle to positive
}
if (e.getKeyCode() == KeyEvent.VK_UP)
{
s.setDir(0,-1);
}
if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
s.setDir(-1,0);
}
if(e.getKeyCode() ==KeyEvent.VK_RIGHT)
{
s.setDir(1,0);
}
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
s.setDir(0,0);
}
if (e.getKeyCode() == KeyEvent.VK_UP)
{
s.setDir(0,0);
}
if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
s.setDir(0,0);
}
if(e.getKeyCode() ==KeyEvent.VK_RIGHT)
{
s.setDir(0,0);
}
}
public void keyTyped(KeyEvent e) {}
public int width = 3000;
public int height= 300;
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
graphicsBuffer.setColor(Color.white);
graphicsBuffer.fillRect(0, 0, getWidth(), getHeight());
graphicsBuffer.drawImage(s.picture, s.xpos, s.ypos, s.width, s.height, this);
graphicsBuffer.setColor(Color.red);// I have added this line of code so that the oval shows up
graphicsBuffer.fill(s.c);
g2.drawImage(imageBuffer, 0,0, getWidth(), getHeight(), this);
}
/**
*
*/
private static final long serialVersionUID = 1L;
}
The following code may help you where clicking mouse may relocate the label.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MovingLabel extends JFrame{
int x,y; // define the location of a label
JLabel label; // movable label
Container container;
MovingLabel(){
super("Test a movable label");
x=y=100;
label= new JLabel("label relocated");
Container container= getContentPane();
setLayout(null); // Turn the layout manager off by setting the layout manager to null, as NormR1 indicated
container.add(label); // place the label into the container
label.setBounds(100,100,150,30);//position and sizing the label yourself
container.addMouseListener(new MouseAdapter(){ // add MouseListener
public void mouseClicked(MouseEvent e){
x = e.getX();
y = e.getY();
label.setBounds(x,y,150,50); // relocating label. You may also resizing the label by altering the 3rd and 4th arguments
}
});
setSize(900,500);
setVisible(true);
}
public static void main(String args[]){
MovingLabel m = new MovingLabel();
m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
(1) The buttons show up in my machine (JDK 1.6). So it seems to be some problem with your machine. You may use Button of AWT rather than JButton of swing which is a lightweight component and does not show up among any AWT stuff. However, your case is OK. Since you put all the buttons into one separated container so that no conflict occurs, and even JButton shoud show up. If you simply put a JButton into a canvas (e.g. Applet) it wouldn't show up.
(2) You did not set up Layout manager correctly. I modified your code with BorderLayout. It works. (See attached file)
(3) Should we call the class ClickyLatinHelp as a driver class rather then "main class" ? One class may implement several interfaces. Since ActionListener and MouseListener both are interfaces the driver class may implement both.
I am noticed that :
Your code:
if (showeng = true) {
showeng = false;
}else {
showeng = true;
}
}
is not correct. It should be if (showeng == true)... rather than if (showeng=true)
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ClickyLatinHelp extends JFrame implements ActionListener {
boolean showeng = true;
JButton List1Button = new JButton("List 1");
JButton List2Button = new JButton("List 2");
JButton List3Button = new JButton("List 3");
JButton List4Button = new JButton("List 4");
JButton List5Button = new JButton("List 5");
JButton List6Button = new JButton("List 6");
JButton List7Button = new JButton("List 7");
JButton List8Button = new JButton("List 8");
JButton List9Button = new JButton("List 9");
public ClickyLatinHelp() {
super("Welcome to Latin Help");
setBounds(100, 100, 700, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
DrawingArea canvas = new DrawingArea();
JPanel ButtonBanner = new JPanel();
// JPanel HoldStuff = new JPanel();
// BoxLayout box = new BoxLayout(HoldStuff, BoxLayout.Y_AXIS);
setLayout(new BorderLayout());
List1Button.addActionListener(this);
List2Button.addActionListener(this);
List3Button.addActionListener(this);
List4Button.addActionListener(this);
List5Button.addActionListener(this);
List6Button.addActionListener(this);
List7Button.addActionListener(this);
List8Button.addActionListener(this);
List9Button.addActionListener(this);
ButtonBanner.add(List1Button);
ButtonBanner.add(List2Button);
ButtonBanner.add(List3Button);
ButtonBanner.add(List4Button);
ButtonBanner.add(List5Button);
ButtonBanner.add(List6Button);
ButtonBanner.add(List7Button);
ButtonBanner.add(List8Button);
ButtonBanner.add(List9Button);
add(ButtonBanner,BorderLayout.NORTH);
add(canvas,BorderLayout.CENTER);
}
public class DrawingArea extends JPanel implements MouseListener {
public void mouseClicked(MouseEvent event){
if (showeng = true) {
showeng = false;
}else {
showeng = true;
}
}
public void mouseEntered(MouseEvent event){}
public void mouseExited(MouseEvent event){}
public void mousePressed(MouseEvent event){}
public void mouseReleased(MouseEvent event){}
public void paintComponent(Graphics comp) {
super.paintComponent(comp);
Graphics2D comp2D = (Graphics2D) comp;
comp2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Font font = new Font("Arial", Font.BOLD, 18);
comp2D.setFont(font);
comp2D.drawString("Why, Hello there", 100, 300);
}
}
public void actionPerformed(ActionEvent evt) {
}
public static void main(String[] arguments) {
ClickyLatinHelp TLH = new ClickyLatinHelp();
}
}
I hope the following code could help you.
I also made some comments to help you to understand.
import java.util.*;
public class RandomNumSelected{
static int random[] = new int [20]; // store 20 random numbers varying from 0 to 255;
static int selected[] = new int[5]; // store the 5 distinct numbers you were looking for
static int search(int a[], int n, int d){ //search the array a from subscript 0 until (n-1) for d.
for (int i=0;i<n;i++)
if (a[i]==d) // if the element is found
return i; // then return correspongding subscript
return -1; // No thing happens in the for loop, implying d is not found, thus return -1.
}
public static void main(String []args){
Random rn = new Random();
for (int i=0; i<20; i++) // assign 20 random values to the elements of array random
random[i]= rn.nextInt(256);
int counter=0;
selected[0]=random[0]; // the first random number is stored in selected array
for (int i=1; i<5; i++)
for(int j=1;i<random.length;j++)
if (search(random,i,random[j]) == -1){ // if the current selected array has no such value of random[j]
selected[i]=random[j]; // the random number random[j] is stored in the array selected
break; //terminate the nested loop so that the next run for the outerloop starts
}
System.out.println("The 20 random numbers varying betwee 0 and 255 [0,255]: ");
for(int a:random)
System.out.print(a + " ");
System.out.println();
System.out.println("The 5 distinct numbers selected from the above 20 numbers:");
for (int a:selected)
System.out.print(a + " ");
System.out.println();
}
}
The output:
The 20 random numbers …
ankilosado, I have a question for you:
Why do you declare the class statItem has an attribute valor of type of Integer instead of the primitive type int? Integer is the wrapper class of int. Am I right?
Thank you, VinC, for sharing the "Covariant".
line 22 shows that g is a variable of type Grain.
line 25 shows that a variable of type Grain is capable to receive a value of type Wheat. Why?
Because Grain is super class of class Wheat. Wheat is a kind of Grain. An instance of subclass can also be an instance of superclass.
Class Student inherits class Person. Can you say: "Student David is not a person"? definitely Not. David, the instance of class Student is definitely a person.
Also see Java tips
her58, perter_budo is right. Since you said "I am able to select 5 random numbers,.." you must have some code. How do you select?
har58, you should make plan beforehand. For example,
(1) pre-store 20 existing random nmbers in an array.
(2) when executing program store the distinct 5 random numbers in another array one by one.
Should we start with the following code as clues:
public class RandomNumSelected{
int random[] = new int [20]; // store 20 random numbers varying from 0 to 255;
int selected[] = new int[5]; // store the 5 distinct numbers you were looking for
static int search(int a[], int n, int d){ //search the array a from subscript 0 until (n-1) for d.
for (int i=0;i<n;i++)
if (a[i]==d) // if the element is found
return i; // then return correspongding subscript
return -1; // No thing happens in the for loop, implying d is not found, thus return -1.
}
public static void main(String []args){
.....
}
}
comments: The random numbers vary in a range. For example, from 0 to 255 [0,255]
You may generate by:
(1) the static method rand() in Math class.
(2) Create a instance of the class Random:
Random ran = new Random();
int n = ran.nextInt(256);
You may replace the code in line 24 where the error occurs by the following two lines of code:
int va = this.statVect[i].getValor();
va += otroVect[i].getValor();
this.statVect[i].set(va);
Can you answer me Why we should modify in this way?
jon is right. You have to put the printLoop method into the main method. This means when interpreting the program (executing the main() method only) the printLoop() is called.
However, there are two ways to follow jon's instruction.
(1) you have to place a keyword static before the method printLoop(), so that the static method main may call the printLoop().
static void printLoop() {...}
static method can call static mathods only. Or
(2) the printLoop() remains as a member method. In this way you have to create an instance of the class "While" you have defiend. Then the instance will be used as a handle to call the printLoop().
public static void main(String args[]) {
While w= new While();
w.printLoop();
}
I have modified a program from a text book by H.M.Deitel, P.J. Deitel (Java How to Program). It helps you to have a solution.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Factorial extends JApplet implements ActionListener {
JLabel numberLabel, resultLabel;
JTextField numberField, resultField;
// set up applet GUI
public void init() {
// obtain content pane and set its layout to FlowLayout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// create numberLabel and attach it to content pane
numberLabel = new JLabel( "Enter an positive integer(less than 21) and press Enter" );
container.add( numberLabel );
// create numberField and attach it to content pane
numberField = new JTextField( 10 );
container.add( numberField );
// register this applet as numberField ActionListener
numberField.addActionListener( this );
// create resultLabel and attach it to content pane
resultLabel = new JLabel( "Fibonacci value is" );
container.add( resultLabel );
// create numberField, make it uneditable
// and attach it to content pane
resultField = new JTextField( 15 );
resultField.setEditable( false );
container.add( resultField );
} // end method init
// obtain user input and call method fibonacci
public void actionPerformed( ActionEvent event )
{
long number, facValue;
// obtain user input and convert to long
number = Long.parseLong( numberField.getText() );
showStatus( "Calculating ..." );
// calculate fibonacci value for number user input
facValue = fac( number );
// indicate processing complete and display result
showStatus( "Done." );
resultField.setText( Long.toString( facValue ) );
} // end method actionPerformed
// recursive declaration of method fibonacci …
You may do in the following way. Assume the word you are going to random has n characters. In the original character order of the word, each time you select one as the first letter and print it. And then print the rest of the letter (with their order) so that you may have n random words.
For example the word july has 4 characters.
we will have:
july
ujly
ljuy
yjul
A new random word would be printed in the following way.
Each run of the outer loop will do:
(1) select a letter from word in their original order in the word. Then print this letter as the first letter of each new random word.
(2) Then use a nested loop to print the rest letters. That is, print all the characters whose indexex are not the index of the selected letter.
In this way a newly created random word is printed.
The outloop runs n times so that n random words are printed
Hope you understand my idea.
Do you mean you try to get another windonw ? Did you use javaw on DOS? If so there would be no console available so that no printed output on screen. But how do you know the System.console() returns null?
The standard method to use console() method (starting from 1.6)is shown as follows:
import java.io.Console;
public class TestConsole {
public static void main(String[] args) {
Console console = System.console(); // obtain an instance of Console
if (console != null) { // make sure if you may use the console: if console is available
String user = new String(console.readLine("Enter username:")); // read a line of characters
String pwd = new String(console.readPassword("Enter passowrd:")); // read a password whti nothing printed on screen
console.printf("Username is: " + user + "\n"); // print username
console.printf("Password is: " + pwd + "\n"); // print passward
} else {
System.out.println("Console is unavailable."); // have no right to use console
}
}
}
JButtons, JRadioButtons, JLabels, and so on come from lightweight package swing hence not are shown (overlapped) when meeting (conflicting with) heavyweight components, e.g. buttons, labels,... from java.awt. The following class extends Frame (heavyweight) rather than JFrame. Therefore, the JRadioButtons must be placed in one subframe: BorderLayout.NORTH. If they were placed directedly in the Frame, they would all disappear.
The following code also works.
import javax.swing.*; // lightweight package
import java.awt.*; // heavyweight package
import java.awt.event.*;
// Frame from java.awt. its heavy
class simo2 extends Frame implements ActionListener{
private JRadioButton red; // lightweight component
private JRadioButton yellow; // lightweight component
private JRadioButton blue; // lightweight component
private JRadioButton green; // lightweight component
private JRadioButton magenta; // lightweight component
public simo2(){
setLayout(new BorderLayout());
setVisible(true);
setSize(400,250);
JPanel p = new JPanel();
red=new JRadioButton(" red");
yellow=new JRadioButton(" yellow");
blue=new JRadioButton(" blue");
green=new JRadioButton(" green");
magenta=new JRadioButton(" magenta");
ButtonGroup group=new ButtonGroup();
group.add(red);
group.add(yellow);
group.add(blue);
group.add(green);
group.add(magenta);
red.addActionListener(this);
yellow.addActionListener(this);
blue.addActionListener(this);
green.addActionListener(this);
magenta.addActionListener(this);
p.add(red); // place the light component in a saparate container.
p.add(yellow);
p.add(blue);
p.add(green);
p.add(magenta);
add(p,BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()== red){
setBackground(Color.red);
}
if(e.getSource()== yellow){
setBackground(Color.yellow);
}
if(e.getSource()== blue){
setBackground(Color.blue);
}
if(e.getSource()== green){
setBackground(Color.green);
}
if(e.getSource()== magenta){
setBackground(Color.magenta);
}
}
}
public class simo0 {
public static void main(String[] args){
simo2 s=new simo2();
s.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}
It works with one Thread. You may add a button (not JButton) so that when client clicks, one more ball will be added. One should be noticed that the JButton, which is lightweight component, will not be shown on the heavyweight stuff( e.g. awt Graphics). That's why only Button(the heavyweight component) works. You may also setLayout(null), so that the button may use setBounds(int, int, int, int) method to have its own location and size. Then you may start a coding for a game..... Good luck.
/*
Only one Thread is used. You may have more balls up to 10.
*/
import javax.swing.*;
import java.awt.*;
public class Balls extends JFrame implements Runnable {
static Ball balls[]= new Ball[10];
static int count=0;
Thread timer = null;
class Ball { // inner class
int x,y; // each ball has its own location indicated by x,y
boolean flag; // each ball has its own flag to direct if y++ or y--
public Ball(int x){
flag=true;
y=0;
this.x=x;
}
public void drawball(Graphics g){ // draw itself
g.setColor(Color.red);
g.fillOval(x,y,10,10);
if (flag)
y++;
else
y--;
if (y >= getHeight()) // inner class may call any method of its outer class
flag = false;
else
if (y <=0)
flag = true;
}
} // end of the inner class
public void start(){
if (timer == null){
timer = new Thread(this);
timer.start();
}
}
public void run(){
while(timer !=null){
try{
Thread.sleep(10);
}catch(InterruptedException e){}
repaint();
}
}
public void paint(Graphics g){
g.setColor(Color.white);
g.fillRect(0,0,800,600);
for (int i=0; i<count; i++){ // …
SOS, I have learned a lot from your poster. The answers are highly appreciated.
I guess you did not follow NormR1's instruction precisely. I have tested your program. It works.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class simo2 extends JFrame implements ActionListener{
private JRadioButton red;
private JRadioButton yellow;
private JRadioButton blue;
private JRadioButton green;
private JRadioButton magenta;
Container container;
public simo2()
{
super("Radio Button Test");
container = getContentPane();
container.setLayout(new FlowLayout());
setVisible(true);
setSize(400,250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
red=new JRadioButton(" red");
yellow=new JRadioButton(" yellow");
blue=new JRadioButton(" blue");
green=new JRadioButton(" green");
magenta=new JRadioButton(" magenta");
ButtonGroup group=new ButtonGroup();
group.add(red);
group.add(yellow);
group.add(blue);
group.add(green);
group.add(magenta);
red.addActionListener(this);
yellow.addActionListener(this);
blue.addActionListener(this);
green.addActionListener(this);
magenta.addActionListener(this);
container.add(red);
container.add(yellow);
container.add(blue);
container.add(green);
container.add(magenta);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== red)
{
container.setBackground(Color.red);
}
if(e.getSource()== yellow)
{
container.setBackground(Color.yellow);
}
if(e.getSource()== blue)
{
container.setBackground(Color.blue);
}
if(e.getSource()== green)
{
container.setBackground(Color.green);
}
if(e.getSource()== magenta)
{
container.setBackground(Color.magenta);
}
}
}
public class simo1 {
public static void main(String[] args)
{
simo2 s=new simo2();
}
}
You may try to use one Thread only in your program.
Your class drawpanel will have attributes x,y only. That is, you define each ball as an instance with their own attributes x and y.
Thank you, NormR1. I have tested your code. Yes, it works when the BorderLayout is used swhere two balls are moving in different "subframes":BorderLayout.EAST and BorderLayout.WEST. I have tried FlowLayout, resulted int an overlap of two components. In a game program, two objects (balls) should be moving within one frame rather than two: EAST and WEST. Therefore, we have to figure out the right Layout Manager. Meanwhile programming in J2ME shows different balls are able to move within a common frame. Are they associated with one thread or different threads? We have to make further investigation.