| | |
adding keylistener
![]() |
•
•
Join Date: Jul 2005
Posts: 3
Reputation:
Solved Threads: 0
hi guys, i need to write a program about slide show in java, please help me with these wrong code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class myframe extends JWindow
{
myframe()
{
setLocation(200,200);
setSize(250,150);
addKeyListener(new Listen());
show();
}
class Listen extends KeyAdapter
{
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == e.VK_ENTER)
{
System.exit(0);}
}
}
}
public class key_listener
{
public static void main(String[] args )
{
new myframe();
}
}
thanks in advance
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class myframe extends JWindow
{
myframe()
{
setLocation(200,200);
setSize(250,150);
addKeyListener(new Listen());
show();
}
class Listen extends KeyAdapter
{
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == e.VK_ENTER)
{
System.exit(0);}
}
}
}
public class key_listener
{
public static void main(String[] args )
{
new myframe();
}
}
thanks in advance
•
•
Join Date: Jun 2004
Posts: 2,108
Reputation:
Solved Threads: 18
You have to override all the keylistener methods:
Java Syntax (Toggle Plain Text)
public void keyTyped(KeyEvent key) { } public void keyPressed(KeyEvent ke) { } public void keyReleased(KeyEvent key) { }
•
•
Join Date: Jul 2005
Posts: 3
Reputation:
Solved Threads: 0
I found a slideshow program written in java at www.geocities.com/kengssoft/slideshow/
but I got that the ' addKeyListener ' didn't run properly , when it executed, it looked likes could not accept the 'Enter' key , I have j2re 1.4.2 on Win Xp
The following lines are the codes :
// SSWindow.java
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
/**
* The Slide Show window
*/
public class SSWindow extends JWindow implements KeyListener,
ActionListener, FileFilter
{
/** The image label */
JLabel imageLabel;
/** The parent */
JFrame parent;
/** The directory */
String direc;
/** List of files in the directory */
String[] filenames;
/** Delay in milliseconds */
int delay;
/** Counter */
int count;
/** The timer that displays the Slide Show */
Timer timer;
/* Constructor */
public SSWindow(JFrame par, String direc, float seconds)
{
super(par);
parent = par;
this.direc = direc;
delay = (int)(seconds*1000);
// Add label to center of screen
Container back = getContentPane();
imageLabel = new JLabel();
back.setBackground(Color.black);
back.add(imageLabel);
imageLabel.setVerticalAlignment(JLabel.CENTER);
imageLabel.setHorizontalAlignment(JLabel.CENTER);
// Display the window
JFrame loading = JFrame();
addKeyListener(this);
setSize(getToolkit().getScreenSize());
setVisible(true);
// Get the names of the files
File[] files = (new File(direc)).listFiles(this);
filenames = new String[files.length];
//System.out.println("Filenames.length = "+filenames.length);
for (int i=0; i<filenames.length; i++) {
filenames[i] = files[i].toString();
}
count = -1;
timer = new Timer(delay, this);
timer.start();
} // End constructor
/** Function that changes the image */
public void updateImage()
{
try {
imageLabel.setIcon(new ImageIcon(filenames[count]));
} catch(Exception ex) {
timer.stop();
}
} // End updateImage()
/** Handle the key released event from the text field. */
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
switch(keyCode)
{
// If ESC is pressed, then quit
case KeyEvent.VK_ESCAPE:
timer.stop();
System.exit(0);
break;
// If ENTER is pressed, then go back to Main Menu
case KeyEvent.VK_ENTER:
timer.stop();
parent.setVisible(true);
SSWindow.this.dispose();
break;
}
} // end keyReleased()
/* These have to implemented */
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void actionPerformed(ActionEvent e) {
count++;
/*
// If we have gone past the last file,...
// return to beginning.
if (count > filenames.length) {
count = 0;
}
*/
// System.out.print(new Integer(count).toString()+" ");
updateImage();
} // End actionPerformed()
public boolean accept(File file)
{
String filename = file.toString();
if (filename.endsWith(".tiff") ||
filename.endsWith(".tif") ||
filename.endsWith(".gif") ||
filename.endsWith(".jpeg") ||
filename.endsWith(".jpg")) {
return true;
} else {
return false;
}
} // End accept()
} // End class SSWindow
And here is the main() class :
// SSFrame.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/**
* The Slide Show's Opening Screen
*/
public class SSFrame extends JFrame
{
JTextField direcText, delayText;
JFileChooser fc;
static final String
WINTITLE="Kengs' Slide Show Viewer",
DIRECTORY="Directory : ",
BROWSE="Browse...",
DELAY="Delay : ",
TIME="2",
SECONDS="seconds",
START="Start SlideShow!",
ADVANCED="Advanced...",
ABOUT="About...",
EXIT="Exit";
public static void main(String args[])
{
SSFrame ss = new SSFrame();
} // End main()
public SSFrame()
{
// Set the title
setTitle(WINTITLE);
Container back = getContentPane();
back.setLayout(new GridLayout(0,1));
back.add(new JLabel(new ImageIcon("images/kss.gif")));
fc = new JFileChooser();
fc.setFileSelectionMode(fc.DIRECTORIES_ONLY);
JPanel p1 = new JPanel();
p1.add(new JLabel(DIRECTORY, new ImageIcon ("images/directory.gif"), JLabel.CENTER));
p1.add(direcText = new JTextField(20));
JButton browseButton = new JButton(BROWSE, new ImageIcon("images/browse.gif"));
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(SSFrame.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
direcText.setText(fc.getSelectedFile().toString());
}
}
});
p1.add(browseButton);
back.add(p1);
JPanel p1e = new JPanel();
p1e.add(new JLabel(DELAY, new ImageIcon("images/delay.gif"), JLabel.CENTER));
p1e.add(delayText = new JTextField(TIME, 5));
p1e.add(new JLabel(SECONDS));
back.add(p1e);
JPanel p2 = new JPanel();
JPanel butPanel = new JPanel();
butPanel.setBorder(BorderFactory.createLineBorder(Color.black));
JButton startButton = new JButton(START, new ImageIcon("images/start.gif"));
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SSFrame.this.hide();
SSWindow s = new SSWindow(
SSFrame.this, direcText.getText(),
new Float(delayText.getText()).floatValue()
);
}
});
butPanel.add(startButton);
p2.add(butPanel);
JButton aboutButton = new JButton(ABOUT, new ImageIcon("images/about.gif"));
aboutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Should display message box here
}
});
p2.add(aboutButton);
JButton exitButton = new JButton(EXIT, new ImageIcon("images/exit.gif"));
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
p2.add(exitButton);
back.add(p2);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
pack();
setVisible(true);
} // End constructor
} // End class MainFrame
Please again help me solve this problem. :-|
Thanks for the help. :p
but I got that the ' addKeyListener ' didn't run properly , when it executed, it looked likes could not accept the 'Enter' key , I have j2re 1.4.2 on Win Xp
The following lines are the codes :
// SSWindow.java
import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
/**
* The Slide Show window
*/
public class SSWindow extends JWindow implements KeyListener,
ActionListener, FileFilter
{
/** The image label */
JLabel imageLabel;
/** The parent */
JFrame parent;
/** The directory */
String direc;
/** List of files in the directory */
String[] filenames;
/** Delay in milliseconds */
int delay;
/** Counter */
int count;
/** The timer that displays the Slide Show */
Timer timer;
/* Constructor */
public SSWindow(JFrame par, String direc, float seconds)
{
super(par);
parent = par;
this.direc = direc;
delay = (int)(seconds*1000);
// Add label to center of screen
Container back = getContentPane();
imageLabel = new JLabel();
back.setBackground(Color.black);
back.add(imageLabel);
imageLabel.setVerticalAlignment(JLabel.CENTER);
imageLabel.setHorizontalAlignment(JLabel.CENTER);
// Display the window
JFrame loading = JFrame();
addKeyListener(this);
setSize(getToolkit().getScreenSize());
setVisible(true);
// Get the names of the files
File[] files = (new File(direc)).listFiles(this);
filenames = new String[files.length];
//System.out.println("Filenames.length = "+filenames.length);
for (int i=0; i<filenames.length; i++) {
filenames[i] = files[i].toString();
}
count = -1;
timer = new Timer(delay, this);
timer.start();
} // End constructor
/** Function that changes the image */
public void updateImage()
{
try {
imageLabel.setIcon(new ImageIcon(filenames[count]));
} catch(Exception ex) {
timer.stop();
}
} // End updateImage()
/** Handle the key released event from the text field. */
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
switch(keyCode)
{
// If ESC is pressed, then quit
case KeyEvent.VK_ESCAPE:
timer.stop();
System.exit(0);
break;
// If ENTER is pressed, then go back to Main Menu
case KeyEvent.VK_ENTER:
timer.stop();
parent.setVisible(true);
SSWindow.this.dispose();
break;
}
} // end keyReleased()
/* These have to implemented */
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void actionPerformed(ActionEvent e) {
count++;
/*
// If we have gone past the last file,...
// return to beginning.
if (count > filenames.length) {
count = 0;
}
*/
// System.out.print(new Integer(count).toString()+" ");
updateImage();
} // End actionPerformed()
public boolean accept(File file)
{
String filename = file.toString();
if (filename.endsWith(".tiff") ||
filename.endsWith(".tif") ||
filename.endsWith(".gif") ||
filename.endsWith(".jpeg") ||
filename.endsWith(".jpg")) {
return true;
} else {
return false;
}
} // End accept()
} // End class SSWindow
And here is the main() class :
// SSFrame.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
/**
* The Slide Show's Opening Screen
*/
public class SSFrame extends JFrame
{
JTextField direcText, delayText;
JFileChooser fc;
static final String
WINTITLE="Kengs' Slide Show Viewer",
DIRECTORY="Directory : ",
BROWSE="Browse...",
DELAY="Delay : ",
TIME="2",
SECONDS="seconds",
START="Start SlideShow!",
ADVANCED="Advanced...",
ABOUT="About...",
EXIT="Exit";
public static void main(String args[])
{
SSFrame ss = new SSFrame();
} // End main()
public SSFrame()
{
// Set the title
setTitle(WINTITLE);
Container back = getContentPane();
back.setLayout(new GridLayout(0,1));
back.add(new JLabel(new ImageIcon("images/kss.gif")));
fc = new JFileChooser();
fc.setFileSelectionMode(fc.DIRECTORIES_ONLY);
JPanel p1 = new JPanel();
p1.add(new JLabel(DIRECTORY, new ImageIcon ("images/directory.gif"), JLabel.CENTER));
p1.add(direcText = new JTextField(20));
JButton browseButton = new JButton(BROWSE, new ImageIcon("images/browse.gif"));
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int returnVal = fc.showOpenDialog(SSFrame.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
direcText.setText(fc.getSelectedFile().toString());
}
}
});
p1.add(browseButton);
back.add(p1);
JPanel p1e = new JPanel();
p1e.add(new JLabel(DELAY, new ImageIcon("images/delay.gif"), JLabel.CENTER));
p1e.add(delayText = new JTextField(TIME, 5));
p1e.add(new JLabel(SECONDS));
back.add(p1e);
JPanel p2 = new JPanel();
JPanel butPanel = new JPanel();
butPanel.setBorder(BorderFactory.createLineBorder(Color.black));
JButton startButton = new JButton(START, new ImageIcon("images/start.gif"));
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SSFrame.this.hide();
SSWindow s = new SSWindow(
SSFrame.this, direcText.getText(),
new Float(delayText.getText()).floatValue()
);
}
});
butPanel.add(startButton);
p2.add(butPanel);
JButton aboutButton = new JButton(ABOUT, new ImageIcon("images/about.gif"));
aboutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Should display message box here
}
});
p2.add(aboutButton);
JButton exitButton = new JButton(EXIT, new ImageIcon("images/exit.gif"));
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
p2.add(exitButton);
back.add(p2);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
pack();
setVisible(true);
} // End constructor
} // End class MainFrame
Please again help me solve this problem. :-|
Thanks for the help. :p
•
•
Join Date: Jun 2004
Posts: 609
Reputation:
Solved Threads: 8
Hi everyone,
First what do you want the program to do when you press enter??
Try this
Try running the above program. If it does not work then most probably it is a bug.
Let me know what happens
Here by the way here is an article on the keylistener with sample code
http://javaalmanac.com/egs/java.awt....KeyEvents.html
I hope this helps you
Yours Sincerely
Richard West
First what do you want the program to do when you press enter??
Try this
Java Syntax (Toggle Plain Text)
public class A implements KeyListener { public void keyTyped(KeyEvent key) { } public void keyPressed(KeyEvent key) { int code = key.getKeyCode(); if(code == KeyEvent.VK_ENTER) { //Do something here System.out.println("You pressed enter"); } } public void keyReleased(KeyEvent key) { } }
Try running the above program. If it does not work then most probably it is a bug.
Let me know what happens
Here by the way here is an article on the keylistener with sample code
http://javaalmanac.com/egs/java.awt....KeyEvents.html
I hope this helps you
Yours Sincerely
Richard West
Microsoft uses "One World, One Web, One Program" as a slogan.
Doesn’t that sound like "Ein Volk, Ein Reich, Ein Führer" to you, too?
— Eric S. Raymond
Tell me what type of software do you like and what would you pay for it
http://www.daniweb.com/techtalkforums/thread19660.html
Doesn’t that sound like "Ein Volk, Ein Reich, Ein Führer" to you, too?
— Eric S. Raymond
Tell me what type of software do you like and what would you pay for it
http://www.daniweb.com/techtalkforums/thread19660.html
•
•
Join Date: Jul 2005
Posts: 3
Reputation:
Solved Threads: 0
Hi everyone,
This listing code doesn't work for me , any suggestion welcome please...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyKeyListener extends KeyAdapter
{
public void keyReleased(KeyEvent key)
{ }
public void keyTyped(KeyEvent key)
{ }
public void keyPressed(KeyEvent key)
{
// Check for key characters.
int code = key.getKeyCode();
if(code == KeyEvent.VK_ENTER)
{
System.exit(0);
}
}
}
public class myframe
{
public static void main(String[] args)
{
JWindow wnd = new JWindow();
wnd.setSize(250,150);
wnd.show();
wnd.addKeyListener(new MyKeyListener());
}
}
This listing code doesn't work for me , any suggestion welcome please...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyKeyListener extends KeyAdapter
{
public void keyReleased(KeyEvent key)
{ }
public void keyTyped(KeyEvent key)
{ }
public void keyPressed(KeyEvent key)
{
// Check for key characters.
int code = key.getKeyCode();
if(code == KeyEvent.VK_ENTER)
{
System.exit(0);
}
}
}
public class myframe
{
public static void main(String[] args)
{
JWindow wnd = new JWindow();
wnd.setSize(250,150);
wnd.show();
wnd.addKeyListener(new MyKeyListener());
}
}
![]() |
Similar Threads
- I lack focus... (Java)
- adding quick reply to a phpbb board (Growing an Online Community)
- Adding Totals from Listbox DB (DAO) (Visual Basic 4 / 5 / 6)
- My ie keeps adding favorites w/out my permission and . . . (Web Browsers)
- adding totals in listboxes (Visual Basic 4 / 5 / 6)
Other Threads in the Java Forum
- Previous Thread: JRadioButtons not working! need help urgently
- Next Thread: refuses to compile
| Thread Tools | Search this Thread |
-xlint add android api applet application array arrays automation bank bi binary blackberry bluetooth chat class client code compile compiler component converter database dice digit eclipse equation error event fractal freeze functiontesting game gameprogramming givemetehcodez graphics gui health html hyper ide idea image infinite input int integer j2me java javame javaprojects jetbrains jni jpanel jtable julia learningresources linux list login loop main map method methods mobile myregfun netbeans newbie nonstatic notdisplaying pearl problem program programming project qt recursion scanner screen scrollbar server set sms sort sorting spamblocker sql sqlserver string superclass swing system text-file thread threads tree variablebinding windows xor






