I want to call another applet by clicking a button; the old applet will then be closed or reloaded to the new applet.
My Action Listener doesn't have anything yet.
public class ConImage extends JApplet implements ActionListener {
Button btn;
Applet second;
public void init()
{
setSize(1600,900);
setLayout(null);
btn=new Button("Replace with other applet");
add(btn);
btn.addActionListener(this);
}
public void paint(Graphics g)
{
super.paint(g);
btn.setLocation(100, 100);
btn.setSize(100, 50);
}
public void actionPerformed(ActionEvent e)
{ second=null;
second= getAppletContext().getApplet("SecondClass");
if (second!=null)
{
if(e.getSource()==Time)
{
SecondClass ma= (SecondClass) second;
}
}
}
}
I'm pretty sure this isn't possible because of Java's security system. The best way to so it is to have a master class, which has an array of JApplet. On that master applet I would create a method that sets the visible applet from the array, calls init() and when a render is requested call paint() of that applet.
Like so:
public class MasterApplet extends JApplet {
private int index = 0;
private JApplet[] applets;
public void init(){
JApplet appletA = new AppletA();
JApplet appletB = new AppletB();
applets = new JApplet[]{appletA, appletB};
setViewing(index);
}
public void paint(Graphics g){
applets[index].paint(g);
}
public void setViewing(int idex){
index = idex;
applets[idex].init();
revalidate();
repaint();
}
Pretty much if you want to change the applet add it to the array of applets, and then call setViewing() with the index of that applet.
Related
How do I override a paintComponent method with response to a state change?
Error message: void is an invalid type for the variable paintComponent
public class MyContainer extends Container {
public void paintComponent(Graphics m){
m.drawArc(100,100,100,100,100,100);
m.setColor(Color.green);
m.fillArc(100,100,100,100,100,100);
}
public static void main(String[] args){
Container y = new Container();
JFrame x = new JFrame();
JPanel gg = new JPanel();
x.add(y);
x.setTitle(" Shape Changer");
x.setBounds(100,50,500,300);
x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x.getContentPane().add(new ContentPanel());
x.getContentPane().add(new ContnetPanel());
x.setContentPane(new ContnetPanel());
x.setVisible(true);
}
static class ContentPanel extends JPanel{
private Graphics g;
private JPanel ss;
public void paint(Graphics g){
g.drawArc(100,100,100,100,100,100);
g.fillRect(100, 100,100,100);
}
public ContentPanel(){
}
}
static class ContnetPanel extends JPanel implements ActionListener, ChangeListener{
JComboBox comboerbox;
class appres {
public void paint(Graphics h){
h.drawRect(100,100,100,100);
h.setColor(Color.red);
h.fillRect(100,100,100,100);
}
}
public ContnetPanel(){
comboerbox = new JComboBox();
comboerbox.addItem("Red Square");
comboerbox.addItem("Blue Square");
comboerbox.addItem("Green Square");
comboerbox.setSelectedIndex(1);
add(comboerbox);
setLayout(new GridLayout(2,1));
}
#Override
protected void paintComponent(Graphics h){
super.paintComponent(h);
h.drawArc(100,100,100,100,100,100);
h.setColor(Color.blue);
h.fillArc(100,100,100,100,100,100);
repaint();
}
int yy = 0;
public void actionPerformed(ActionEvent evt){
switch(comboerbox.getSelectedIndex()){
case 0:yy=0;
case 1: yy=1;
case 2: yy=2;
}
}
//evt.getSource()==comboerbox
public void stateChanged(ChangeEvent evt){
if(evt.getSource()==comboerbox){
#Override
protected void paintComponent(Graphics h){
super.paintComponent(h);
h.drawArc(100,100,100,100,100,100);
h.setColor(Color.blue);
h.fillArc(100,100,100,100,100,100);
repaint();
}
}
else
{
System.out.println("DONE");
}
}
}
}
Of course, the paintComponent method isn't a variable. How would I override paintComponent here? Or is a better way to change the shape with response to state change? That would be great too!
Thanks in advance, love you guys!
In your last question: How do I make the superclass go beyond just the content pane? you were given a link to the Swing tutorial for some Swing basics.
Well there is also a section on Custom Painting for you to read. You can then download the example and play with it to understand how painting works.
Basically the Container class doesn't have a paintComponent() method so you should not be trying to do custom painting in that class.
If you want to change a painting property, then you need to add a method to your class to change the state of the property and then invoke repaint() on itself.
So from the tutorial example in Step 3 you can see how the moveSquare(...) method changes the state of the class and then invokes repaint().
Note you should never invoke repaint() in the paintComponent() method since this will cause the painting to be continually rescheduled.
I have a loop that creates a series of JButtons. This code is buried deep inside a class that is primarily concerned with multi-threading, so it uses Executors, Callables, Futures, etc. I'm trying to keep this class fairly encapsulated, so I want to move the work of setting up the JButton to its own class. This is the body of my loop where it creates a single button. It works just fine:
JButton imageButton = new JButton(new ImageIcon(image));
imageButton.setMinimumSize(imageSize);
imageButton.setPreferredSize(imageSize);
imageButton.setMaximumSize(imageSize);
imageButton.setVisible(true);
imageButton.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(java.awt.event.MouseEvent mouseEvent) {
// do a bunch of stuff }
}
#Override
public void mouseMoved(java.awt.event.MouseEvent mouseEvent) {}
});
imagesPanel.add(imageButton);
This is only going to get messier, so here is my attempt to move it to a separate class:
ImageButton imageButton = new ImageButton(image, imageSize);
imageButton.addMouseMotionListener();
imagesPanel.add(imageButton);
And this is my class:
public class ImageButton extends JButton {
JButton button;
static final long serialVersionUID = 1;
public ImageButton(Image image, Dimension imageSize) {
button = new JButton(new ImageIcon(image));
button.setMinimumSize(imageSize);
button.setPreferredSize(imageSize);
button.setMaximumSize(imageSize);
button.setVisible(true);
}
public void addMouseMotionListener() {
button.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(java.awt.event.MouseEvent mouseEvent) {
// do a bunch of stuff
}
#Override
public void mouseMoved(java.awt.event.MouseEvent mouseEvent) {}
});
}
}
This all compiles without error, for whatever that is worth. The buttons layout in their proper sizes and proper places. However, the images do not appear (the buttons are blank) and the mouse listener is not functioning. Can anyone see what I am doing wrong and how to make this work?
Your ImageButton class is wrong. You're holding an unnecessary instance to JButton inside.
So, the implementation should be:
public class ImageButton extends JButton {
static final long serialVersionUID = 1;
public ImageButton(Image image, Dimension imageSize) {
super(new ImageIcon(image));
this.setMinimumSize(imageSize);
this.setPreferredSize(imageSize);
this.setMaximumSize(imageSize);
this.setVisible(true);
}
public void addMouseMotionListener() {
this.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(java.awt.event.MouseEvent mouseEvent) {
// do a bunch of stuff
}
#Override
public void mouseMoved(java.awt.event.MouseEvent mouseEvent) {}
});
}
}
This way, you're setting the parameters to the class instead to a member, and all instances of ImageButton will have the same configuration.
You extending JButton AND you create another JButton inside your class.
Probably you wanted to do something like this:
public static class ImageButton extends JButton {
JButton button; // Remove me
static final long serialVersionUID = 1;
public ImageButton(Image image, Dimension imageSize) {
super(new ImageIcon(image));
setMinimumSize(imageSize);
setPreferredSize(imageSize);
setMaximumSize(imageSize);
setVisible(true);
// Dont see why there should be separate method for the addMouseMotionListeners
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(java.awt.event.MouseEvent mouseEvent) {
// do a bunch of stuff
}
#Override
public void mouseMoved(java.awt.event.MouseEvent mouseEvent) {}
});
}
}
Help me to create a class file which consists of JButton and JSlider and Java Graphics.
I tried a lot of methods but not working in netbeans 7.2: Jpanel, Jcomponent, paint(), paintComponent().
Can any one give me a class file for example to create that one?
My code is here:
package floating;
import designs.*;
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame
{
String frame_name;
boolean START,PASS;
int SPEED=1;
JSlider jSlider1 = new javax.swing.JSlider();
JSeparator js=new JSeparator();
JToggleButton jToggleButton1 = new javax.swing.JToggleButton("START");
JToggleButton jToggleButton2 = new javax.swing.JToggleButton("PASS");
Test(String a)
{
JFrame jf=new JFrame(a);
Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
jf.setSize(dim.width,dim.height-30);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
js.setOrientation(SwingConstants.VERTICAL);
js.setForeground(Color.red);
js.setLocation(dim.width/2,0);
js.setPreferredSize(dim);
js.setSize(10,dim.height);
jf.add(js);
jSlider1.setLocation(dim.width-300,20);
jSlider1.setSize(250,50);
jSlider1.setToolTipText("Set to Seconds");
jSlider1.setMinimum(1);jSlider1.setMaximum(5);jSlider1.setMajorTickSpacing(1);jSlider1.setMinorTickSpacing(1);jSlider1.setValue(1);
jSlider1.setPaintLabels(true);
jSlider1.setPaintTicks(true);
jSlider1.setPaintTrack(true);
jSlider1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jSlider1MouseClicked(evt);
}
});
jf.add(jSlider1);
jToggleButton1.setLocation((dim.width/2)+30,25);
jToggleButton1.setSize(100,30);
jToggleButton1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jToggleButton1ItemStateChanged(evt);
}
});
jToggleButton2.setLocation((dim.width/2)+50+100,25);
jToggleButton2.setSize(100,30);
jToggleButton2.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jToggleButton2ItemStateChanged(evt);
}
});
jf.add(jToggleButton1);
jf.add(jToggleButton2);
jf.setLayout(null); \\if layout is null the only all buttons and slider at positions and showing in JFrame
jf.setVisible(true);
}
public void jToggleButton1ItemStateChanged(java.awt.event.ItemEvent evt)
{
if(jToggleButton1.getActionCommand()=="START")
{
System.out.printf(jToggleButton1.getText());
jToggleButton1.setText("STOP");
this.START=true;
System.out.println(this.START);
}
else
{
System.out.printf(jToggleButton1.getText());
jToggleButton1.setText("START");
this.START=false;
System.out.println(this.START);
}
}
public void jToggleButton2ItemStateChanged(java.awt.event.ItemEvent evt)
{
if( jToggleButton2.getActionCommand()=="PASS")
{
System.out.printf(jToggleButton2.getText());
jToggleButton2.setText("RESUME");
this.PASS=true;
System.out.println(" "+this.PASS);
}
else
{
System.out.printf(jToggleButton2.getText());
jToggleButton2.setText("PASS");
this.PASS=false;
System.out.println( " " +this.PASS);
}
}
private void jSlider1MouseClicked(java.awt.event.MouseEvent evt)
{
this.SPEED=jSlider1.getValue();
System.out.println(SPEED);
}
public static void main(String args[])
{
Test a=new Test("Test");
}
public void paint(Graphics g) // for example but not shwowing in JFrame.
{
g.setColor(Color.red);
RRectangle a=new RRectangle(60,100,250,190,60,60);
a.drawShape(g);
System.out.println(a);
}
}
Your class extends JFrame, but then within your class you create an instance of JFrame and you add all the components to this instance of JFrame and make this frame visible. The extended class is never used or displayed.
So the paint() method that you override does nothing.
you should NOT be extending JFrame.
custom painting is done by overriding the paintComponent() method of a JPanel and then you add the panel to the frame
I gave you a link to the Swing tutorial in my comment above. Read the section on Custom Painting for a working example.
I'm making my first Applet. I have a JPanel which creates a Swing GUI and performs CPU intensive tasks (repainting a Component 60Hz). My Applet displays this JPanel on event dispatching thread. here is an abstraction of the problem. Normally I would launch the applet from an html document instead of having a main method. This program puts about a 40% load on my CPU.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class TestApplet extends JApplet {
TestPanel tp;
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
private void createGUI() {
//Create and set up the content pane.
tp = new TestPanel();
tp.setOpaque(true);
setContentPane(tp);
}
public static void main(String[] args) {
JFrame f = new JFrame("Fish Tank");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JApplet ap = new TestApplet();
ap.init();
f.add("Center", ap);
f.pack();
f.setVisible(true);
}
}
class TestPanel extends JPanel{
public TestTank tt = new TestTank();
public TestPanel() {add(tt);}
public void stop() {tt.stop();}
public void start() {tt.start();}
}
class TestTank extends Component implements ActionListener{
private javax.swing.Timer timer;
TestTank(){
timer = new javax.swing.Timer(17, this);
timer.setCoalesce(true);
timer.start();
}
public Dimension getPreferredSize(){
return new Dimension(900, 700);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Dimension size = getSize();
g2.setPaint(new GradientPaint(0,0,Color.RED,900, 0,Color.WHITE));
g2.fill(new Rectangle2D.Float(0,0,size.width,size.height));
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public void stop(){timer.stop();}
public void start(){timer.start();}
}
My question: How do I suspend and resume execution of the JPanel (FishTankPanel) when the user switches tabs or minimizes the browser? I want the Applet to stop using the CPU when the user can't see what it is doing. I need to capture browser events in order to execute tp.stop() in the applet. I have tried to execute them with window event listeners in the JPanel, and by overriding the start() and stop() methods in the Applet. I have been unsuccessful. Any suggestions or solutions would be appreciated.
I would do as Dave said and use the JApplet override start and stop methods to call your GUI methods. For instance, see changes in code:
public class TestApplet extends JApplet {
TestPanel tp;
public void init() {
// ... no change
}
private void createGUI() {
// ... no change
}
#Override
public void stop() {
if (tp != null) {
tp.stop();
}
}
#Override
public void start() {
if (tp != null) {
tp.start();
}
}
}
class TestTank extends Component implements ActionListener {
private javax.swing.Timer timer;
// ... no change
public void stop() {
timer.stop();
System.out.println("stop");
}
public void start() {
timer.start();
System.out.println("start");
}
}
It seems you might need to leverage some JS for this. E.G. use the JS shown in this answer to explicitly call the applet start() & stop() methods on focus & blur detection respectively.
The solution for my problem was to use javascript to implement the Page Visibility API. I then called the appropriate Java methods from within the javascript script.
I have made an applet name ParentApplet.java whose task is to create a child frame
Child frame coding is defined in ChildFrame.java
ParentApplet.java
public class ParentApplet extends Applet {
ChildFrame frame;
private static int time = 0;
#Override
public void start() {
frame.setVisible(true);
}
#Override
public void stop() {
frame.setVisible(false);
}
#Override
public void init() {
frame = new ChildFrame("Child");
this.setSize(400, 400);
}
#Override
public void paint(Graphics g) {
g.drawString("Child's Info : " + (++time), 50, 100);
g.drawString(frame.getMessage(), 400, 100);
System.out.println(frame.getMessage().isEmpty() ? "Empty" : frame.getMessage());
}
}
ChildFrame.java
public class ChildFrame extends Frame {
private String mess = "";
public ChildFrame(String title) {
super(title);
addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter(this));
setSize(300, 500);
}
public String getMessage() {
return mess;
}
public void setMessage(String mess) {
this.mess = mess;
(new ParentApplet()).repaint();
System.out.println("Click");
}
}
MyMouseAdapter.java
public class MyMouseAdapter extends MouseAdapter {
ChildFrame frame;
public MyMouseAdapter(ChildFrame frame) {
this.frame = frame;
}
#Override
public void mouseClicked(MouseEvent e) {
frame.setMessage("Mouse Cliked in Child");
}
}
MyWindowAdapter.java
public class MyWindowAdapter extends WindowAdapter {
ChildFrame frame;
public MyWindowAdapter(ChildFrame frame) {
this.frame = frame;
}
#Override
public void windowClosing(WindowEvent we) {
frame.setVisible(false);
}
}
Now i am unable to reach the paint method again even after calling the repaint method from the ChildFrame class. Please suggest me whether i have done something wrong or some thing i need to understand.
Thanks in advance
Gagandeep Singh
The answer to your question is basically "you don't do that".
The Applet's paint() method is responsible for painting the contents of the actual applet component-- i.e. the visible component that appears in the web page. Your ChildFrame should then have a separate paint() method to paint itself (or in fact, would usually have a Canvas added to it, and that Canvas in turn has its own paint() method).
(Remember that in Java a "Frame" is effectively a "window"-- i.e. a standalone window that opens separately to the web page.)
You can call repaint() on whatever component from wherever you like. This will eventually lead to that component's paint() method being called. In your particular example, you shouldn't call "new ParentApplet()" -- you don't want to call repaint() on some randomly created new applet, but rather on the single already existing one. So change this by passing a reference to your applet into the constructor of ChildFrame which ChildFrame can then hold as an instance variable and re-use when needed:
public class ChildFrame extends Frame {
private String mess = "";
private final ParentApplet parentApplet;
public ChildFrame(ParentApplet applet, String title) {
super(title);
this.parentApplet = applet;
addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter(this));
setSize(300, 500);
}
...
public void setMessage(String mess) {
this.mess = mess;
parentApplet.repaint();
}
}
I must admit that so far, it's not immediately obvious why you would have a setMessage() on a separate frame whose purpose is to set the message displayed in the applet. Why not put the setMessage() method on the applet in that case? But maybe you have another reason for doing it your way that isn't apparent so far.