Im working with eclipse.
My Code:
import javax.swing.JApplet;
import java.awt.*;
public class Einstein extends JApplet
{
public void pain(Graphics page)
{
page.drawRect(60,60,40,40); // Square
page.drawString("Out of clutter, find simplicity. " , 110, 70);
}
}
The rectangle and text does not shown in the applet.
what could be the problem?
public void pain(Graphics page) - interesting choice of naming...
I believe the method you're looking for is paint
#Override
public void paint(Graphics g) {
super.paint(g);
//...
}
Make sure you call super.paint before performing any custom painting, otherwise you could end up with a bunch of nasty paint artefacts.
Having said that. Consider using a custom component, extending from JPanel for example, and override it's paintComponent method instead, then add this component to your applet.
You gain the benefit of the double buffering support of Swing for free and the freedom to move you component to another container, like a JFrame or other container for example, making it far more re-usable
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 am kinda new to java and would like to invoke a graphical method in ActionEvent, for instance let's say I would like a square to be drawn when button b is pressed? Will appreciate any help thanks:
package Mst;
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class Cours2_2 extends Applet implements ActionListener {
Button a,b,c;
public void init(){
setBackground(Color.pink);
a= new Button("KIRMIZI");
a.addActionListener(this);
add(a);
b= new Button("BEYAZ");
b.addActionListener(this);
add(b);
c= new Button("SARI");
c.addActionListener(this);
add(c);
}
public void paint(Graphics g){
g.drawString("s", 5, 5);
}
public void actionPerformed(ActionEvent e){
String s= e.getActionCommand();
if(s.equals("KIRMIZI")){
setBackground(Color.red);
}
if(s.equals("BEYAZ")){
setBackground(Color.white);
}
if(s.equals("SARI")){
setBackground(Color.yellow);
}
drawStrings(t);
}
public void drawStrings(Graphics t) {
t.setColor(Color.yellow);
t.fillRect(0, 0, 75 ,75);
}
}
I would like to know if I should create this square which I want drawn when a button is pressed as a method or a function. Thanks
Avoid Applet, if you "really" have to, use JApplet instead. Having said that, you should start with JPanel and override it's paintComponent method instead (and make sure you call super.paintComponent before doing any custom painting. Take a look at Painting in AWT and Swing and Performing Custom Painting for more details.
Generally speaking, painting in AWT/Swing is passive, that is, when the system "decides" something needs to be updated, it will then be painted. This means that you (generally) have little control over when something will be painted. You make suggestions, but it's update to the system to decide what and when something is painted.
You paint methods should paint the current state of the component. This means that you will need to provide some information and logic that the paint methods can use to make decisions about what to paint. For example, you could have a flag, which is changed by the ActionListener, which calls repaint on your component and when the component is painted, you would test the state of this flag and make decisions on what should be done (like drawing a square for example).
A more complicated approach might use a List and take advantage of the Shape API, adding or removing shapes to the List which the paint method would then be able to iterate over and paint
Have a look at Collections Trail and
2D Graphics for more details
Hello everyone I am quite new to applets in java and was wondering why my oval was not moving up the screen when I press the up key. I said repaint in the paint method and nothing is happening
Any Ideas? (Please don't be rude I am new to applets so...)
package mypackage;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.applet.*;
public class gameapplet extends Applet {
int charecterx = 500;
int charectery = 250;
public void init(){
addKeyListener(new AL());
setSize(1000,1000);
setBackground(Color.RED);
}
public void paint(Graphics g){
//Paint Method
g.setColor(Color.BLACK);
g.fillOval(charecterx,charectery,100,100);
repaint();
}
public class AL extends KeyAdapter
{
public void keyPressed (KeyEvent e)
{
int keyCode = e.getKeyCode();
//If Statements To see if user is moving
if(keyCode == e.VK_UP)
{
if(charecterx <= 0)
{
charecterx = 0;
}
else
{
charecterx--;
}
}
}
public void keyRealesed(KeyEvent e){
}
}
}
You're main problem comes down to two main issues...
1- You are using a KeyListener
KeyListeners are notorious for being problematic in that they only respond to keystrokes when the component they are registered to are focusable AND have focus.
2- You never call repaint from within the keyPressed method to request that the applet be repainted.
You should avoid Applet as it is woefully out of date and generally not used by many people anymore. Instead use JApplet, in fact, I would recommend avoiding applets altogether until you understand the API better
Don't call setSize on an applet, the size of applet is defined by the html tag it is created from.
Don't call repaint or anything that might call repaint from within any paint method
Don't override paint, it's too easy to break the paint chain (which you have) and for top level containers like Applet, isn't double buffered. In fact AWT generally isn't double buffered, which will cause flickering when the component is repainted. Instead, you should use something like a JPanel and override it's paintComponent method
Don't use KeyListener, it has too many issues with focus. Instead, make use of the Key Bindings API which provides you with more control and a much more reusable API
Take a look at:
Creating a GUI With JFC/Swing
Performing Custom Painting
Painting in AWT and Swing
For more details
It depends on the version of your jdk.
In jdk1.6 I would use this
invalidate();
validate();
repaint();
In jdk 1.7 I would use
revalidate();
repaint();
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'm trying to completely disable all painting and refreshing on a portion of a JFrame. I got the desired effect on the entire JFrame by simply overriding public void paint(Graphics) like so:
import javax.swing.*;
class Test extends JFrame {
Test () {
setBounds(20,20, 100,100);
setVisible(true);
}
//This disables all painting and refreshing ON A JFRAME.
//Just doing this on a JPanel doesn't work.
public void paint (Graphics g) {}
public static void main (String[] args)
{ new Test(); }
}
I want this same effect, but only on a particular region of the JFrame. I want to be able to add GUI components like normal to the rest of the frame. I've tried disabling double buffering (using JPanel's constructor) and overriding the following methods (extending both JPanel and JComponent) like so:
public class DontRefresh extends JComponent/JPanel {
public void paint (Graphics g) {}
public void paintComponent (Graphics g) {}
public void repaint () {}
public void update (Graphics g) {}
public void updateUI () {}
}
and i also tried disabling refresh via:
DontRefresh component = new DontRefresh();
RepaintManager.currentManager(component).markCompletelyClean(component);
but nothing worked.
Well, without knowing exactly what you're doing I would recommend you have a "filler panel" (just a JPanel you don't do anything with) in the space you don't want anything to appear and then have other panels for everything else.
So say you have a JFrame. If you wanted the top right corner to never display anything, you could fill the JFrame with 4 JPanels, one in each corner (or 3 with one on the left, one in the top right corner and one in the bottom right corner). Then put all you swing components in the other panels. I don't know if this will accomplish your purpose, but I'm not totally certain what you're purpose is, so that's the best I can do :) I hope it helps!