JApplet not running properly in eclipse - java

I wrote a pretty basic applet program in eclipse:
public class SwingAppletDemo extends JApplet {
private static final long serialVersionUID = -1935096480915162747L;
JLabel jl;
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
new SwingAppletDemo().makeGUI();
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
private void makeGUI() {
jl = new JLabel("Press a button!");
setLayout(new FlowLayout());
add(jl);
}
}
It compiled fine and then I ran it as an applet by right-clicking on the SwingAppletDemo.java and then I selected Run As > Java Applet
The applet viewer opened but no label was displayed in it. Can anyone please tell me where did I went wrong, I referred to a few tutorials but couldn't find the necessary info.
I also tried running it in Google Chrome but there too only an empty applet was displayed.
Thanx in advance!

You are creating a new SwingAppletDemo in your init method which is never shown. You can simply replace:
new SwingAppletDemo().makeGUI();
with
makeGUI();

Related

Blank JFrame when program is run

I am an absolute beginner in coding. I would like to know why is my Jframe blank when run, how do I fix it. From what I have research on the internet it seems that I should put the component inside the JFrame as it is empty but how do I do it
My Code
public class Video extends JFrame
{
public static void main(String[] args) throws URISyntaxException {
final URI uri = new URI("https://www.youtube.com/watch?v=rl0YiZjTqpw");
class OpenUrlAction implements ActionListener
{
#Override public void actionPerformed(ActionEvent e) {
open(uri);
}
}
JFrame frame = new JFrame("Links");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(410, 400);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
JButton btnclickHereTo = new JButton();
btnclickHereTo.setText("<HTML> <FONT color=\"#000099\"><U>Click Here To Watch Video</U></FONT>");
btnclickHereTo.setHorizontalAlignment(SwingConstants.LEFT);
btnclickHereTo.setBorderPainted(false);
btnclickHereTo.setOpaque(false);
btnclickHereTo.setBackground(Color.WHITE);
btnclickHereTo.setToolTipText(uri.toString());
btnclickHereTo.addActionListener(new OpenUrlAction());
container.add(btnclickHereTo);
frame.setVisible(true);
}
private static void open(URI uri)
{
if (Desktop.isDesktopSupported())
{
try
{
Desktop.getDesktop().browse(uri);
}
catch (IOException e)
{ /* TODO: error handling */ }
}
else
{ /* TODO: error handling */ }
}
}
public void setVisible(boolean b) {
Why would you override the setVisible(...) method of your frame? There is no reason to do that.
I am an absolute beginner in coding
Start with something basic, like the example from the Swing tutorial on How to Make Frames.
Keep a reference to the tutorial link handy since it contains information and examples for all Swing basics.

Java applet button click open link

We have an applet code below. where we have specified a button and when the button is clicked it should open a new website. Yahoo website in this case. The code for the applet is below
public class GotoLinkApplet extends Applet implements ActionListener{
public void init()
{
String link="yahoo";
Button b=new Button(link);
b.addActionListener(this);
add(b);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("1");
Button src= (Button)e.getSource();
String link="http://www."+src.getLabel()+".com";
try{
AppletContext a=getAppletContext();
URL url =new URL(link);
//a.showDocument(url, "_self");
a.showDocument(url, "_blank");
System.out.println("a");
}
catch(MalformedURLException ae)
{
System.out.println(ae.getMessage());
}
}
}
We executed the above code in eclipse,but when we click on the button, the yahoo link is not coming up. Request you to help. But the code that specifies showdocument runs fine.
Any help on the above is much appreciated.
This should be possible using Desktop.browse(uri);
You'll of course want to make sure the Desktop is supported first.

Panel in Java Applet does not display

I have a Java Applet (java.applet.Applet) embedded into an HTML page. There is a Control class, which extends Applet and a Panel (java.awt.Panel) the same shape and size of the Applet which displays everything on the screen.
When I run the project from the NetBeans IDE, everything displays as intended: the Applet opens and contains a Panel with my splash screen.
When I run the project from the HTML page on my website, I see a blank white page. The images do load; in Google Chrome, I can right-click the page and click "Inspect Element", and the whole game displays and functions properly. You can view the page at http://www.philipthegreat.com/control.html.
My thought: the Panel is displaying behind the Applet instead of in front of the Applet.
Here is the code in the Control and SplashScreen classes.
Control
public class Control extends Applet {
private Panel displayPanel;
#Override
public void init() {
setFocusable(true);
}
#Override
public void start() {
displayPanel = new SplashScreen(this);
add(displayPanel);
displayPanel.requestFocus();
}
public void setDisplayPanel (Panel displayPanel) {
remove(this.displayPanel);
this.displayPanel = displayPanel;
add(this.displayPanel);
this.displayPanel.requestFocus();
}
}
SplashScreen
public SplashScreen(Control control) {
setLayout(null);
setSize(800,600);
setBackground(Color.BLUE);
this.control = control;
init();
}
public void init() {
try {
splashScreen = ImageIO.read(getClass().getResourceAsStream("/images/SplashScreen.png"));
} catch (Exception e) {
e.printStackTrace();
}
addMouseListener((MouseListener) this);
}
public void destroy() {
}
#Override
public void paint(Graphics g) {
g.drawImage(splashScreen, 0, 0, null);
}
As I am relatively new to Java, any pointers would be appreciated.
Try this as Control.java instead of your Control.java
//<applet code="Control.java" height=200 width=500></applet>
public class Control extends JApplet {
private Panel displayPanel;
#Override
public void init() {
setFocusable(true);
}
#Override
public void start() {
displayPanel = new SplashScreen(this);
add(displayPanel);
displayPanel.requestFocus();
}
public void setDisplayPanel(Panel displayPanel) {
remove(this.displayPanel);
this.displayPanel = displayPanel;
add(this.displayPanel);
this.displayPanel.requestFocus();
}
}

Java Applet Game Design : Keyboard focus

I had posted this in a wrong place (GameDev) and got no response there. So I'm posting it again here.
I'm making an applet game and it is rendering, the game loop is running, the animations are updating, but the keyboard input is not working. Here's an SSCCE.
public class Game extends JApplet implements Runnable {
public void init(){
// Initialize the game when called by browser
setFocusable(true);
requestFocus();
requestFocusInWindow(); // Always returning false
GInput.install(this); // Install the input manager for this class
new Thread(this).start();
}
public void run(){
startGameLoop();
}
}
And Here's the GInput class.
public class GInput implements KeyListener {
public static void install(Component c){
new GInput(c);
}
public GInput(Component c){
c.addKeyListener(this);
}
public void keyPressed(KeyEvent e){
System.out.println("A key has been pressed");
}
......
}
This is my GInput class. When run as an applet, it doesn't work and when I add the Game class to a frame, it works properly.
Thanks
Solved now. See my solution
One possible solution is to use the JApplet's contentPane, to set the focus on it rather than on the JApplet itself. But my preference is to use Key Bindings instead. You may need to use a Swing Timer for this to work:
My SSCCE:
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
#SuppressWarnings("serial")
public class AppletKeyListen extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
setFocusable(true);
int timerDelay = 100;
Timer myTimer = new Timer(timerDelay , new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
boolean focusObtained = requestFocusInWindow();
System.out.println("focusObtained for JApplet: " + focusObtained);
Container contentPane = getContentPane();
contentPane.setFocusable(true);
focusObtained = contentPane.requestFocusInWindow();
System.out.println("focusObtained for contentPane: " + focusObtained);
}
});
myTimer.setRepeats(false);
myTimer.start();
// boolean focusObtained = requestFocusInWindow();
// System.out.println("focusObtained: " + focusObtained);
//
// Container contentPane = getContentPane();
// contentPane.setFocusable(true);
//
// focusObtained = contentPane.requestFocusInWindow();
// System.out.println("focusObtained: " + focusObtained);
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
}
If you're running in a browser, you probably need to click on the applet to give it focus. For security reasons most browsers won't let an applet just grab the keyboard focus without the user clicking it.
So, I would add a mouse listener instead of doing the focus grabbing directly in init():
addMouseListener(new MouseAdapter() {
public void onMousePress(MouseEvent e) {
requestFocus();
}
});
Now that I have two options,
Use JWS
Don't make an applet mode
Now I had tried to make a new class called GApplet. It loads a game into a new JFrame which worked from the applet. Now I can access the fullscreen mode from web too. Here's a link to the class.
The GApplet class
And now it's working like the webstart and is actually an applet.

LWUIT ArrayOutOfBoundException

I am new to LWUIT, and even though I am finding it very interesting to use, I have been having the challenge of previewing whatever MIDlet I generate. Each time i run the MIDlet in an emulator, I get an ArrayOutOfBOundException displaying as a form on the screen of the emulator and will only leave after pressing OK on the form.
This is my code
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.*;
import com.sun.lwuit.Form;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
import java.io.IOException;
public class Ruwwa extends MIDlet implements ActionListener {
public void startApp() {
Display.init(this);
Form f = new Form("");
f.setTitle("Mairuwa Portal");
Label bottomText = new Label();
bottomText.setText("Welcome to the Mairuwa Portal");
bottomText.setTextPosition(Component.CENTER);
f.addComponent(bottomText);
Command exitCommand = new Command("Exit");
f.addCommand(exitCommand);
f.addCommandListener(this);
f.show();
try {
Resources r = Resources.open("/res/working.res");
UIManager.getInstance().setThemeProps(r.getTheme("Mairuwa Theme"));
} catch (IOException ioe) {
// Do something here.
}
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void actionPerformed(ActionEvent ev) {
Label label = new Label();
label.setText("Initiating IO, please wait...");
Display.getInstance().invokeAndBlock(new Runnable() {
public void run() {
// perform IO operation...
}
});
label.setText("IO completed!");
// update UI...
}
}
It displayed the form with this code but it didnt display it on the theme i created.The name of the theme is "working.res" and i included it in a res folder in the project folder.Thanx
While im running your code im getting illegalargumentexception on this line, bottomText.setTextPosition(Component.CENTER);.
Because you can't set the label text position as Component.CENTER. You should use the label text position as LEFT/RIGHT/BOTTOM/TOP. If you change the label text position as I mentioned, it will work properly.
So If you getting ArrayOutOfBOundException, you did a mistake on some other place. Try to debug your application and find out where did you made a mistake.
Update:
Display.init(this);
try {
Resources r = Resources.open("/res/working.res");
UIManager.getInstance().setThemeProps(r.getTheme("Mairuwa Theme"));
} catch (IOException ioe) {
// Do something here.
}
// your code.

Categories