I am writing this code so that it will add JPanels and will change the background color when clicked. The code in the class that runs the JFrame class is:
import javax.swing.*;
public class project9Driver {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Project9 w=new Project9();
w.setVisible(true);
w.setSize(900, 900);
}
}
The Project9 class is:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class Project9 extends JFrame implements MouseListener{
JPanel panes[]=new JPanel[64];
public void Project9(){
JFrame mainFrame=new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container mainBox=mainFrame.getContentPane();
mainBox.setLayout(new GridLayout(8,8));
mainBox.addMouseListener(this);
for(int i=0;i<=63;i++){
panes[i].setBackground(Color.WHITE);
mainBox.add(panes[i]);
}
}
public void paint(Graphics g){
super.paintComponents(g);
}
public void mouseClicked(MouseEvent e) {
for(int i=0;i<=64;i++){
if(e.getSource()==panes[i]){
Random xR=new Random();
Random yR=new Random();
Random zR=new Random();
int x=xR.nextInt(255),y=yR.nextInt(255),z=zR.nextInt(255);
panes[i].setBackground(new Color(x,y,z));
}
}
}
}
Whenever I try to run the program, it comes up with an empty GUI window. What am I missing?
Project9 is a Frame, and you're creating another Frame inside of Project9 and you're not showing it, and becouse of that, just Project9 (w) is draw on screen, but it doesn't have anything.
You have to use "this" instead of another frame.
public class Project9 extends JFrame implements MouseListener{
JPanel panes[]=new JPanel[64];
public void Project9(){
//JFrame mainFrame=new JFrame(); delete this.
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container mainBox= this.getContentPane();
Three answer all point out different problems with your code.
You should start with a proper working example. The TopLevelDemo.java code from the Swing tutorial on Using Top Level Containers will show you the basics and the proper way to create GUI components.
You should not even be extending JFrame. It is important that all components are created on the Event Dispatch Thread which is why the invokeLater() code is used in the tutorial.
Use the tutorial for examples of using all Swing components. Other example will show you how to extend JPanel for a more complex GUI. You don't need to extend JFrame.
The original problem I noticed with the code is:
public void paint(Graphics g){
super.paintComponents(g);
}
Don't override the paint() method. There is no reason to do this!
The paint() method is for painting and you are not doing any custom painting.
First problem is this that you are using constructor Project9 w=new Project9();
and in class Project9 you are defining method public void Project9(){ you should remove void keyword.
public Project9(){
//JFrame mainFrame=new JFrame(); delete this.
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container mainBox= this.getContentPane();
Related
I wanted to know if it is possible to use/make a function in another Class to draw an image/oval and then call it in the paint public void in our main Class.
If I have
public class Trydraw{
public void drawrcircle(Graphics g){
g.setColor(Color.RED);
g.drawOval(0, 0, 20,20);
g.fillOval(0,0,20,20);
}
}
And then call it here this way
import java.awt.GridLayout;
import javax.swing.*;
import java.awt.*;
public class Display extends JPanel{
public static void main(String[]haha){
JFrame frame = new JFrame();
frame.setSize(800, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void paint(Graphics g){
super.paint(g);
Trydraw l = new Trydraw();
l.drawrcircle(g);
}
}
Thanks for your future help.
Yes you can, if I get your question correctly.
Your sample code works for me if I add
frame.add(new Display());
to the end of your
public static void main(String[] haha)
method.
With your snippet the paint(g) method will never be called, because it will be executed with the initialization of the JPanel which will be initialized with the initialization the Display class (because of inheritance).
You probably want to create an instance of Display, which automatically initializes the JPanel with the overridden paint(g) method, thus the new Operator.
As the constructor of a JPanel returns a JPanel, the constructor of Display returns a type of JPanel as well, which contains the red circle. This JPanel needs to be added with the add method to your original JFrame.
I used a border layout and I put a canvas in the center; where the main game will be, but I can't draw anything to it.
Could anyone point me in the right direction?
import java.awt.*;
import javax.swing.*;
public class TestingGraphics {
public static void main (String[] args) {
GameScene window = new GameScene();
}
}
import java.awt.*;
import javax.swing.*;
public class GameScene extends JFrame {
Canvas gameCanvas;
Graphics Pencil;
JPanel game;
public GameScene() {
game = new JPanel();
add(game);
setTitle("Yet to name this thing.");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameCanvas = new Canvas();
gameCanvas.setPreferredSize(new Dimension(1280, 720));
game.add(gameCanvas);
drawString();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void drawString(Graphics Pencil) {
Pencil.drawString("boo", 100, 100);
}
}
Your problem is that you're making wild guesses on how to draw in Swing and that never works, and your errors include trying to draw directly within a JFrame, trying to call a method without passing in necessary parameters, drawing outside of any painting method.... First and foremost, go to the Swing drawing tutorials which you can find here: Swing Drawing Tutorials -- and read them.
Next, do as they tell you:
Create a class that extends JPanel
Draw in the paintComponent method override of that class, not directly in a JFrame
Be sure to call the super's paintComponent method in your overridden method.
Add your JPanel to a top-level window such as a JFrame
Display the GUI
Done.
I'm a beginner programmer, so I don't know all the vocab, but I understand some of the basics of java.
So I'm trying to Draw in a GUI from the main using another class. I know I'm not being very specific but here's my code, and I'll try to explain what I'm trying to do.
This is my main
import javax.swing.*;
import java.awt.*;
public class ThisMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame theGUI = new JFrame();
theGUI.setTitle("GUI Program");
theGUI.setSize(600, 400);
theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ColorPanel panel = new ColorPanel(Color.white);
Container pane = theGUI.getContentPane();
pane.add(panel);
theGUI.setVisible(true);
}
}
This is my other class
import javax.swing.*;
import java.awt.*;
public class ColorPanel extends JPanel {
public ColorPanel(Color backColor){
setBackground(backColor);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
}
}
I'm trying to use the line
ColorPanel panel = new ColorPanel(Color.white);
Or something like it to use things like
drawRect();
In the main and have it draw in the GUI.
This is the code I used that i think came closest to working
import javax.swing.*;
import java.awt.*;
public class ThisMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame theGUI = new JFrame();
theGUI.setTitle("GUI Program");
theGUI.setSize(600, 400);
theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//I'm trying to draw a string in the JFrame using ColorPanel but i'm Trying to do it from the main
ColorPanel panel = new ColorPanel(){
public void paintComponent(Graphics g){
super.paintComponent(g);
//This is the line I need to work using the ColorPanel in anyway
g.drawString("Hello world!", 20, 20);
};
Container pane = theGUI.getContentPane();
//The errors occur here
pane.add(panel);
theGUI.setVisible(true);
//and on these brackets
}
}
I'm not really sure what exactly you're trying to do (you haven't replied to my comment to your question for clarification), but I would:
Give your ColorPanel a List<Shape>
Give it a public void addShape(Shape s) method that allows outside classes to insert shapes into this List, and then calls repaint()
And in the ColorPanel's paintComponent method, iterate through the List, painting each Shape item using your Graphics2D object.
Note that Shape is an interface, and so your List can hold Ellipse2D objects, Rectangle2D objects, Line2D objects, Path2D objects, and a whole host of other objects that implement the interface. Also, if you want to associate each Shape with a Color, you could store the items in a Map<Shape, Color>.
The reason why you are not able to compile is caused by this line:
ColorPanel panel = new ColorPanel(Color.white);
because the class ColorPanel is not included in the swing library so you have to code it. This code extends JPanel and includes a constructor that takes a Color parameter. The constructor runs when the panel is instantiated and sets its background color:
import javax.swing.*;
import java.awt.*;
public class ColorPanel extends JPanel {
public ColorPanel(Color backColor) {
setBackground(backColor);
}
}
Im currently trying to make my first game and i am having trouble getting the repaint() method to work. I have checked my keyListeners and have confirmed that they are working a ok! The ship that i have created moves but only if i forcibly resize the window by dragging on the sides. If anyone has any tips i would be very greatful!
If you need any more information feel free to ask!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Main extends Canvas implements KeyListener{
public static Ship playerShip = new Ship(150,450,"F5S4-Recovered.png");
public int numberOfEnemies = 0;
public static void createFrame(){
Window frame1 = new Window();
final JPanel pane = new JPanel(){
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 1000, 1000);
g.drawImage(playerShip.image, playerShip.xPos1, playerShip.yPos1, this);
}
};
frame1.add(pane);
}
public void keyTyped(KeyEvent e){System.out.println("KeyTyped");}
public void keyPressed(KeyEvent e){
switch(e.getKeyCode())
{
case KeyEvent.VK_LEFT :
playerShip.xPos1-=2;
break;
case KeyEvent.VK_RIGHT:
playerShip.xPos1+=2;
break;
}
repaint();
}
public void keyReleased(KeyEvent e){}
public static void main(String args[]){
createFrame();
}
}
Window class ----------------------------------------------------------
import javax.swing.*;
public class Window extends JFrame{
public Window()
{
setTitle("Space Game");
setSize(800,800);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addKeyListener(new Main());
setVisible(true);
}
}
Your call to repaint() is repainting the class Canvas, but the painting is done on the JPanel pane. The resizing causes an automatic repaint of the panel. So to fix you want to pane.repaint(), but you can't do that unless you put the panel as a class member, so you can access it from the listener method. Right now, it's currently locally scoped in the createFrame() method.
Also, you should probably add the listener to the panel instead, and not even extend Canvas, since you're not even using it
Other Notes:
Look into using Key Bindings instead of low-level KeyListener
Swing apps should be run from the Event Dispatch Thread (EDT). You can do so by simply wrapping the code in your main in a SwingUtilities.invokeLate(..). See more at Initial Threads
Again, I'll just add, Don't extends Canvas
I have drawn a rectangle using a JPanel
My main objective is to store my Requirement Engineering chapter into a JPanel or a JFrame
import java.awt.*;
import javax.swing.*;
class RequirementEngineering extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent();
g.drawRect(10,10,60,60);
g2.drawString("Feasibility study", 20, 20); //rectangle is my main objective, I will look after the string later
}
public static void main(String[] args)
{
}
}
how do I display the JPanel? I know, JApplet doesn't require a main method, but how do we represent JPanel in main() method?
I have this doubt for long, and other posts are confusing me further, Could I have a direct question
My main question being "How to add JFrame to JPanel" pertaining my current coding
thanks in advance
see if you need to use a Window based app, you can do as:
JPanel customPanel = new RequirementEngineering();
JFrame frame = new JFrame("my window");
frame.getContentPane().add(customPanel );
frame.setSize(300,200);
frame.setVisible(true);
If you need in Applet,
public class JAppletExample extends JApplet {
public void init() {
Container content = getContentPane();
JPanel customPanel = new RequirementEngineering();
content.add(customPanel );
}
And you can run it using appletViewer or in any Web Browser such as IE.