I have made a Loader Applet which greets the user and when user clicks the button displayed on that Applet it then launches the main applet and the Loader Applet is destroyed.
But on clicking Another applet is not launched !
Loader Applet:
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
public class Loader extends JApplet implements ActionListener{
Display secondApplet;
Button button;
#Override
public void init() {
setSize(800,600);
}
#Override
public void start() {
setLayout(new FlowLayout());
button = new Button ("Click me !!");
add(button);
button.addActionListener(this);
}
#Override
public void paint(Graphics g) {
}
#Override
public void actionPerformed(ActionEvent e) {
secondApplet = (Display)getAppletContext().getApplet("Display");
if (secondApplet != null) {
secondApplet.init();
secondApplet.start();
}
else {
System.out.println("Not Running\n");
}
}
}
Display Applet:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;
public class Display extends JApplet {
#Override
public void init() {
setSize(600,400);
}
#Override
public void paint(Graphics g) {
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}
}
How can I create an instance of the other Applet and destroy the current Applet !!
Since an Applet/JApple is a java.awt.Panel itself, then you can embed one into the other, for your specific case you can embed Display into Loader using a Panel in Loader to reload Display as you need.
Something like this:
Panel container = new Panel();
container.setLayout(new GridLayout(1,0));
container.add(secondApplet); //Display Applet
add(container):
secondApplet.init();
secondApplet.start();
button.setVisible(false);
There are so many things wrong with the applets it is hard to know where to begin. But let us concentrate 1st on a more sensible strategy to cause the change beteween one view and another.
Instead of having two applets, have two panels that are swapped in a CardLayout
Instead of having both applets in one page, call getAppletContext().showDocument(secondAppletURL);. Presumably secondAppletURL is different to the URL of the page that hosts the first applet.
OK - the problems with the first applet:
Don't try to set the size of an applet. It is set by the HTML.
All the methods calls in the start() method should be moved to the init() method, since the start() method might be called repeatedly. Then there is no reason to override start() at all.
Don't mix Swing (e.g. JApplet) & AWT (e.g. Button) components without good cause. In this case, use JButton instead of Button.
As a stylistic point, it is typically better to create an anonymous inner ActionListener than implement it on the parent class.
Overriding paint() with an empty implementation is not a good idea. The original paint() draws the applet and components, so now it would do nothing.
The methods in the actionPerformed() are equally nonsensical. An applet does not get included into the AppletContext until after init() & start() have been called, which would mean that calling those methods explicitly causes them to be invoked a second time. While the start() method is meant to be called multiple times, the init() method should only be called once.
2nd Applet.
Ditto point 1. re the 1st applet.
The overridden paint() method ..would paint the BG color (or the FG color - not sure) but nothing else. Again, don't override it.
Try this method to load another applet. See if it works.
Class applet2 = Class.forName("Applet2");
Applet appletToLoad = (Applet)applet2.newInstance();
appletToLoad.setStub(this);
setLayout(new GridLayout(1,0));
add(appletToLoad);
appletToLoad.init();
appletToLoad.start();
Related
i have an assignment to make a simple drawing application using swing and mouse listener. the application has to have three classes, one that contains Main, one that contains the frame, and the last one that makes the drawing. The teacher gave us a source code we're supposed to use to complete the assignment and it looks like this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class Drawsome extends JFrame implements MouseMotionListener {
public Drawsome(){
setSize(300,400);
setForeground(Color.black);
show();;
addMouseMotionListener(this);
}
public void mouseDragged(MouseEvent evt) {
start = end;
end = new Point(evt.getX(),evt.getY());
repaint();
}
public void mouseMoved(MouseEvent evt) {
end = null;
}
public void paint(Graphics g) {
if (start!=null && end!=null)
g.drawLine(start.x, start.y, end.x, end.y);
}
public void update(Graphics g) {
paint(g);
}
Point start=null;
Point end=null;
}
now this work perfectly, but since we have to make the frame in another class i tried to do this:
import java.awt.Color;
import javax.swing.JFrame;
public class MainWindow extends JFrame {
public MainWindow() {
setSize(300,400);
setForeground(Color.black);
show();;
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class Drawsome extends JFrame implements MouseMotionListener {
public Drawsome(){
MainWindow mainwindow = new MainWindow();
addMouseMotionListener(this);
} (rest is the same as the previous code)
i'll get a frame, but the rest doesn't work, i dont' understand what i'm doing wrong, and would greatly appreciate a push in the right direction
Your teacher's source code is terrible since you should never be drawing within the paint method or within a JFrame, plus his/her paint override doesn't call the super's method, breaking the painting chain. They don't appear to know what they're doing.
Having said that, your main driver should not extend JFrame nor should you try to create a JFrame of it or even an instance of it. Instead, in this class's main method, create an instance of the terrible drawing class.
Note that I don't understand this requirement:
and the last one that makes the drawing.
Please post the exact requirements.
If this were my application, I'd
Do my drawing within a JPanel, and not a JFrame
Do it within the JPanel's paintComponent method, not the paint method.
Be sure to call the super's paintComponent method within my JPanel's paintComponent method override.
Then place my JPanel within a JFrame to display it.
I would not have my GUI class implement the MouseListener but rather would use a nested inner class for this.
I have been working with java buttons, and I have created a button ,but when i click the button, I want the shape of the object to change. This is the code I've worked on
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class shapes {
public static void main(String[] a) {
JFrame f = new JFrame("Change shapes");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Shapes Change");
f.getContentPane().add(b);
f.pack();
f.setVisible(true);
}
Public void paint (Graphics g)
{
//no clue what to do here
}
private static abstract class MyButton extends JButton implements ActionListener {
MyButton()
{
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b)
{
//no clue what to do here
}
}
}
}
At first, There is a shape created, once the button is clicked it I want to change it to another shape.
There really should be any need to subclass JButton. If you want to customise the button, you could use the Action API instead, see How to Use Actions.
To perform custom painting your should extend a Swing component like JComponent or JPanel and override the paintComponent method...
See Performing Custom Painting for more details.
You would then need to provide some method which you could call to tell the component that the shape should change to how the shape should be changed.
You would then provide a means for your buttons ActionListener to reference the instance of the paint panel and call these methods...
You simply add an ActionListener to the button:
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// do some action
}
});
A couple other things to note:
You should not run Swing methods outside the Event Dispatch Thread (EDT) or you may run into unpredictable errors.
Java naming conventions specify that class names should be capitalized. In your code, you named the class "shapes" but it is more proper to name it "Shapes".
First declare and define methods for drawing objects. For example drawSquare (), drawCircle () which draws required shapes. Define radio button or something similar to that to get the users choice (to know which object has to be drawn) . In actionPerformed () check which radiobutton is selected and call the appropriate method for drawing objects and call the repaint () for updating in user interface
I was just writing an application and i was not able to set location and size of button to desired values. whenever i open code the button comes at same location and with same size
Here is my code
public class main_class {
public static void main(String args[]){
Main_page mp = new Main_page();
mp.start();
}
}
Second file is:
import javax.swing.*;
import java.awt.*;
public class Main_page extends JPanel {
private static final long serialVersionUID = 1L;
public void start(){
JPanel panel1 = new JPanel();
panel1.setBackground(Color.pink);
JButton Button1 = new JButton("Programmer");
Button1.setSize(10, 100);
Button1.setLocation(200,500);
panel1.add(Button1);
JFrame frame1 = new JFrame("Main Window");
frame1.setSize(700,500);
frame1.setContentPane(panel1);
frame1.setResizable(false);
frame1.setVisible(true);
}
}
what is the problem.
What is the problem?
I'm so glad you asked that question. It's not just a matter of getting a Swing application to work. You must get the Swing application to work correctly so that you can add more functionality to your Swing application without your Swing application breaking.
I added a call to SwingUtilities invokeLater in the main method. This call ensures that the Swing components are defined and used on the Event Dispatch thread (EDT).
I changed the name of your class to MainPage to conform to Java standards for naming classes.
I implemented Runnable to make the invokeLater method parameter easier to define.
I removed the extends of JPanel. You use Swing components. The only reason to extend a Swing component is when you want to override one of the component methods. The only reason you extend any Java class is when you want to override one of the class methods.
I changed the name of your MainPage method to run.
I set a layout (FlowLayout) for your JPanel. You must always use a layout manager for your Swing components.
I made button1 lowercase. Java field names are lowercase, so you can easily differentiate them from class names.
I added a call to the JFrame setDefaultCloseOperation to your run method. Without this call, your Swing application will not stop executing when you close the window. After a while, you'll have dozens of copies of your Swing application running, with no easy way to stop them.
I added a call to the JFrame pack to let the JFrame expand or contract to fit the components, rather than be a fixed size.
Here's the revised code. I put the main method in the MainPage class to make it easier to paste the code.
package com.ggl.testing;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainPage implements Runnable {
#Override
public void run() {
JPanel panel1 = new JPanel();
panel1.setBackground(Color.pink);
panel1.setLayout(new FlowLayout());
JButton button1 = new JButton("Programmer");
panel1.add(button1);
JFrame frame1 = new JFrame("Main Window");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.add(panel1);
frame1.pack();
frame1.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new MainPage());
}
}
if you want to set the size and location manually then you can use panel1.setLayout(null); as people have said in the comments this isn't recommended.
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.Timer;
public class CountingSheep extends JApplet
{
private Image sheepImage;
private Image backgroundImage;
private GameBoard gameBoard;
private scoreBoard scoreBoard;
public void init()
{
loadImages();
gameBoard = new GameBoard(sheepImage, backgroundImage);
scoreBoard = new scoreBoard();
getContentPane().add(gameBoard);
getContentPane().add(scoreBoard);
}
public void loadImages()
{
sheepImage = getImage(getDocumentBase(), "sheep.png");
backgroundImage = getImage(getDocumentBase(), "bg.jpg");
}
}
The program works correctly when nothing but the GameBoard class is added to the JApplet, however, when I try to add the ScoreBoard class, both Panel classes do not show on the Applet. I'm guessing this is now down to positioning? Any ideas?
EDIT: Gone back to the previously asked question Hovercraft, and found it was due to the layout of the contentPane and the order at with the components were added.
Some suggestions:
Don't draw in the paint method of a JApplet as that is a top-level window and should not be drawn directly on. Instead draw in the paintComponent(Graphics g) method of a JPanel or other JComponent, and then add that JPanel to the JApplet's contentPane.
Similar to his advice about the super call, your first method call in this method should be the super.paintComponent(g); which will refresh the JPanel's graphics.
The flicker is from your drawing directly in the JApplet's paint method. If you do as I suggest, you'll take advantage of Swing's use of double buffering.
Since this is a Swing application, you should avoid using KeyListeners and instead use Key Bindings.
Don't get the Graphics object of a component by calling `getGraphics(). The Graphics object obtained will be short-lived and thus will not persist after any repaint.
The code you've posted above is somewhat confusing to me. What are you trying to do with it? You've added components to the JApplet, and these components should handle their own graphics, and then you're painting on the JApplet as well. What kind of behavior exactly are you trying to achieve?
In your paint method, make sure to call super.paint(g) since it is a method inherited from Container, a superclass of JApplet.
#Override
public void paint(Graphics g)
{
super.paint(g);
...
}
i make simple game , and it consist of 2 files , first file is "Alibaba.java" which is extended from JFrame , i used it to display general contents of the game !,
and the second file is "intro.java" which is extended from JPanel , i used it to show intro of the game which include (title & background & person) ,
my problem occured when i tried to add a simple button in the intro ! , i did a function to create the button , but the problem is when i run the game , the button which i added it don't appear !! , but when i tried add it from the first file which extended from JFrame , its appeared ! ,
so what is the problem in my code ? is JPanel don't accept JButtons ! or i must create the buttons from the JFrame file ?!
so i need to know how to add Jbutton inside Jpanel instead of add Jbutton in JFrame Direct !!,
this is my samples of my codes which contain the problem :
1st file (Alibaba.java)
package alibaba;
import java.awt.Color;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Alibaba extends JFrame {
public Alibaba(){
super("Alibaba");
Intro intro = new Intro();
this.add(intro);
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice device = environment.getDefaultScreenDevice();
device.setFullScreenWindow(this);
}
public static void main(String[] args) {
Alibaba alibaba = new Alibaba();
}
}
2nd file(Intro.java) :
package alibaba;
import javax.swing.JButton;
public class Intro extends javax.swing.JPanel implements Runnable{
Thread _intro_run;
public Intro() {
_intro_run = new Thread(this);
_intro_run.start();
}
#Override
public void run() {
// Here i tried to add a button to the Intro !!!
this.add(this.createbutton("Exit"));
}
public JButton createbutton(String text){
JButton _button = new JButton(text);
return _button;
}
}
So please tell me what is the problem and how to solve it , sorry but iam new to java , new to programming games world ! ,, thank you :)
You have to add the JButton inside the main thread, cross thread Component manipulation is bad.
For example:
public Intro() {
JButton exitButton = new JButton("Exit");
this.add(exitButton);
}
Alternatively, use SwingUtilities.invokeLater(Runnable). For example, in your run method:
#Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
add(createbutton("Exit"));
}
}
}
Based on discussion it seems that you are overriding the paint or paintComponent methods. You need to call super in them, like:
void paint(Graphics g) {
super.paint(g);
// do other stuff to g
}
In addition, it is a bad sign that you have a JPanel that implements Runnable. In Java, all UI work (here you are using Swing components) is done from the Event Dispatching Thread - having an actual Swing component (your Intro class is a JPanel) Runnable flies in the face of that.
Suggestions:
Anytime you add a new component to a container, you have to tell the layout managers to layout the new and existing components. This is done by calling revalidate() on the JPanel receiving the button. You also should call repaint() on the JPanel after this.
You shouldn't do any of this in a background thread.
Most important read the Swing tutorials as they will tell you all of this and more.