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();
}
}
Related
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.
I am very new to the Graphics portion of Java. I have created a frame and on it I have added a panel whose color has been set to Green. Now on clicking that panel I want to draw a circle using a test class's object called Mypanel. But it does not happen. Please guide !
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
class Mypanel extends JPanel
{
#Override
public void paintComponent(Graphics g)
{
g.drawOval(15, 15, 5, 5);
}
}
public class algo extends javax.swing.JFrame {
public algo() {
initComponents();
jPanel1.setBackground(Color.GREEN);
}
Mypanel p = new Mypanel() ;
private void jPanel1MouseClicked(java.awt.event.MouseEvent evt) {
p.repaint();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new algo().setVisible(true);
}
});
}
}
If I were to guess I would say that I am not supposed to use the repaint method, but I was told that this was to be used.
That code as supplied would not compile. For better help sooner, post a Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Mypanel extends JPanel {
boolean clicked = false;
Mypanel() {
setBackground(Color.GREEN);
MouseListener mouseListener = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
clicked = true;
repaint();
}
};
this.addMouseListener(mouseListener);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 100);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (clicked) {
g.drawOval(15, 15, 50, 50);
}
}
}
public class algo extends JFrame {
public algo() {
initComponents();
pack();
//jPanel1.setBackground(Color.GREEN); ?!?
}
protected final void initComponents() {
add(new Mypanel());
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new algo().setVisible(true);
}
});
}
}
There are a few things to correct in your example...
When you create the frame (i.e. in the constructor) you'll want to call super(). This is the first thing the constructor has to do. Then, you'll probably want to set an initial width/height, and set the background color of the frame green.
You need to add a mouse listener so that the mouseClicked method is actually called. Then have it add the 'MyPanel' object to the frame, and call repaint.
I think that's roughly what you're going for.
i got a problem with my SplashScreen not showing up, but running in the background..
Heres my Code, taken from this tutorial (hope it ok to post the link?!?) :
SplashScreen Class:
public final class SplashScreen extends JWindow {
BorderLayout borderLayout1 = new BorderLayout();
JLabel imageLabel = new JLabel();
JPanel southPanel = new JPanel();
FlowLayout southPanelFlowLayout = new FlowLayout();
JProgressBar progressBar = new JProgressBar();
ImageIcon imageIcon;
public SplashScreen(ImageIcon imageIcon) {
this.imageIcon = imageIcon;
try {
jbInit();
}
catch(Exception ex) {
}
}
// note - this class created with JBuilder
void jbInit() throws Exception {
imageLabel.setIcon(imageIcon);
this.getContentPane().setLayout(borderLayout1);
southPanel.setLayout(southPanelFlowLayout);
southPanel.setBackground(Color.BLACK);
this.getContentPane().add(imageLabel, BorderLayout.CENTER);
this.getContentPane().add(southPanel, BorderLayout.SOUTH);
southPanel.add(progressBar, null);
this.pack();
}
public void setProgressMax(int maxProgress)
{
progressBar.setMaximum(maxProgress);
}
public void setProgress(int progress)
{
final int theProgress = progress;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
progressBar.setValue(theProgress);
}
});
}
public void setProgress(String message, int progress)
{
final int theProgress = progress;
final String theMessage = message;
setProgress(progress);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
progressBar.setValue(theProgress);
setMessage(theMessage);
}
});
}
public void setScreenVisible(boolean b)
{
final boolean boo = b;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
setVisible(boo);
}
});
}
private void setMessage(String message)
{
if (message==null)
{
message = "";
progressBar.setStringPainted(false);
}
else
{
progressBar.setStringPainted(true);
}
progressBar.setString(message);
}
}
In my Main() I start the SplashScren like this:
SplashScreen initscreen;
ImageIcon myImage = new ImageIcon(FilterConfiguratorJFrame.class.getResource("/images/logo.png"));
initscreen = new SplashScreen(myImage);
initscreen.setLocationRelativeTo(null);
initscreen.setProgressMax(100);
initscreen.setScreenVisible(true);
Then I set the progress like this:
initscreen.setProgress("...loading Projects" , 40);
Then my program is loading Projects via a VPN from a Server at work.
Till here i dont get any errors, but the SplashScreen isn't showing up...
I have a OptionPane showing up when theres no connection to the server, and when THIS OptionPane is showing up the SplashScreen does to. When i click "OK" on the OptionPane it disappears, and so does the SplashScreen...
I tried it, and the SplashScreen shows up no matter when or where i let an OptionPane show...
So my Question is, how do i force the SplashScreen into the foreground?
I want the SplashScreen to show up on startup and updating its progressbar while different data ist loaded from the Database (which can last 1-2 minutes).
EDIT: Tried to force the SplashScreen to show by showinf a JFrame, doesn' work, seems like ist only working with OptionPanes.
The applet consists of following code:
public class TestApplet extends Applet {
public TestApplet() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JDialog dialog = new JDialog();
dialog.setContentPane(new JLabel("Hello"));
dialog.setSize(new Dimension(300, 200));
dialog.setModal(true);
dialog.setVisible(true);
}
});
}}
When I open it on InternetExplorer running on Windows 7 it works: I change browser tabs, dialog always stays in front.
When I open it on Firefox ESR 10.0.5 running on Red Hat Enterprise Linux Server Release 6.3, Java 1.7.0_07-b10 then it instantly goes behind the Browser window and I have to minimize browser in order to find it again.
What do I have to do to make the modal dialog always stay in front of the Applet?
Update:
Changing creation of JDialog to
JDialog dialog = new JDialog(javax.swing.SwingUtilities.getWindowAncestor(TestApplet.this));
makes not difference.
Finally, after trying alot of things I figured out the following workaround:
public class ModalDialog extends JDialog {
private boolean isClosing = false;
protected synchronized boolean isClosing() {
return isClosing;
}
protected synchronized void setClosing(boolean isClosing) {
this.isClosing = isClosing;
}
public ModalDialog() {
setSize(200, 300);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent arg0) {
if (isClosing()) {
System.out.println("Returned because dialog is already closing");
return;
}
EventQueue.invokeLater(new Runnable() {
public void run() {
ModalDialog.this.setVisible(false);
ModalDialog.this.setVisible(true);
}
});
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Dialog is closing");
setClosing(true);
}
});
}
}
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.