paintComponent not Running [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Basically, I'm trying to do a test on my GUI to make sure it will paint.
Here are my classes:
Game
public class Game {
private static GUI gui = new GUI();
private static int[][] pixels = new int[10][10];
public static void main(String[] args) {
}
public void startGame() {
System.out.print("start");
gui.setGameFrame();
}
public static GUI getGUI() {
return gui;
}
public static int[][] getGraphics() {
return pixels;
}
}
GUI
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class GUI extends JPanel {
private static Game game = new Game();
private static JPanel panel = new JPanel();
private static JFrame frame = new JFrame();
final private static int FRAME_HEIGHT = 500;
final private static int FRAME_WIDTH = 500;
//Board size 25x25px
final private static int PIXEL_SIZE = 20;
public GUI () {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setAttributes();
makeMenu();
}
});
}
public static void setAttributes() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("");
frame.setBackground(Color.black);
frame.setVisible(true);
}
private static void makeMenu() {
JButton start = new JButton("Start");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
game.startGame();
}
});
panel.add(start);
frame.add(panel);
frame.pack();
}
public void setGameFrame() {
panel.removeAll();
frame.getContentPane().add(Game.getGUI());
frame.setTitle("Snake v0.1");
frame.setSize(getPreferredSize());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(5, 5, 10, 10);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(FRAME_WIDTH, FRAME_HEIGHT);
}
public void paintGraphics() {
int[][] pixels = Game.getGraphics();
}
}
I've attempted to debug it, but cannot trace why it isn't functioning.
I believe it's something to do with:
frame.getContentPane().add(Game.getGUI());
But I'm not certain.

Me: "What's the purpose of the Game class? Why not just run everything from the Gui class? "
You: "because further code will involve logic and event handling, and sending these events to the GUI class for updating."
Think of the Game as your data model. Use the Game class for only data and data manipulation and keep all the GUI procedures in your GUI class. Just create an instance of the Game class in your GUI class. Run the program from your GUI class, i.e. have the main method in your GUI class. and run the invokeLater from the main method.

I copied and pasted your code directly into Netbeans, and it seems to be working.
On mine there seems to be some graphical object covering the top left of the white rectangle, which is why it didn't show up initially.
Try changing your fillRect() function to fill a larger area.
This worked for me:
g.fillRect(5, 5, 100, 100);

Related

Failed to make my own drawing widget on java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I have stucked to 4 lines of code.
They supposed to let me create my own widget.
But it seems that the main method is missing.
I have tried to write a main class on my-own and create an object in paintComponent() method with no luck.
I know that i am not supposed to call the method myself, but when i run the program i get the error Main method not found in class....
Can someone please explain me how this works or give me a link to read?
Here is the simple code that I tried:
import javax.swing.*;
import java.awt.*;
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.orange);
g.fillRect(20, 50, 100, 100);
}
}
Try this simple code, it should be helpful to you:
import javax.swing.*;
import java.awt.*;
public class MyDrawPanel extends JPanel {
private static final int WIDE = 300;
private static final int HIGH = 200;
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(20, 50, 100, 100);
}
public MyDrawPanel() {
setBackground(Color.white);
// Set a initial size for the program window
this.setPreferredSize(new Dimension(WIDE, HIGH));
}
private void display() {
// Some statements to let the JFrame appear in a good way
JFrame f = new JFrame("MyDrawPanel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
// Main method is called when the program is runned
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MyDrawPanel().display();
}
});
}
}
Output:
If you are new to java, I would suggest to just give 4-5 days on Tutorials | Javatpoint.
Java rule is that the java file name should match the class name containing main method.
So a simple code of main method:
class Simple {
public static void main(String args[]) {
System.out.println("Hello Java");
}
}
In this case this code should be in Simple.java file.

Problems with java graphics [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Can anyone give me some information what did I do wrong? Program runs but drowing a rectangle or anything else doesnt work. There is just empty space on the middle. I tried open the program from terminal and eclipse on kubuntu 15 and windows. Always with the same result.
I m just starting my adventure with java so please be patient.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyGUI {
JFrame frame;
JLabel label;
public static void main(String[] args)
{
MyGUI gui = new MyGUI();
gui.go();
}
public void go()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton labelButton = new JButton("Change label");
labelButton.addActionListener(new LabelListener());
JButton colorButton = new JButton("Change color");
colorButton.addActionListener(new ColorListener());
label = new JLabel("LABEL");
DrawSmth2 drawPanel = new DrawSmth2();
frame.getContentPane().add(BorderLayout.SOUTH, colorButton);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.getContentPane().add(BorderLayout.EAST, labelButton);
frame.getContentPane().add(BorderLayout.WEST, label);
frame.setSize(680,480);
frame.setVisible(true);
}
class LabelListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
label.setText("DONE");
}
}
class ColorListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
frame.repaint();
}
}
public class DrawSmth2 extends JPanel{
public void PaintComponent(Graphics g)
{
g.setColor(Color.blue);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
}
Java is case-sensitive which means that PaintComponent is not the same as paintComponent. To avoid such problems always add #Override annotation to methods you want to override (if you are not overriding existing method compiler will inform you about it - more info: When do you use Java's #Override annotation and why?).
Also don't forget to call super.paintComponent(g); at start of your own implementation of paintComponent to let Swing perform standard operations needed to properly paint this component.
Just add gloabal variable count;
int count=0;
class ColorListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
count++;
frame.repaint();
}
}
public class DrawSmth2 extends JPanel{
public void paintComponent(Graphics g)
{
if(count%2==1)
g.setColor(Color.blue);
g.fillRect(0, 0, getWidth(), getHeight());
}
}

Java: having trouble calling a method from one class into another

Still trying to grasp how classes and methods work in Java. To experiment, I tried to create a graphics class, with a void draw box method inside. Then, I try to call that method in the main method to try to draw those boxes. I'm getting "cannot be resolved to variable" errors which I believe means the main class can't see my other class for some reason?
Boxymain.java:
import java.awt.*;
import javax.swing.JFrame;
public class Boxymain extends Canvas {
public static void main(String[] args){
BoxyMethod c = new BoxyMethod();
c.drawBox(window, Color.RED, 200, 300);
JFrame win = new JFrame("Boxy Main");
win.setSize(800,600);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Boxymain canvas = new Boxymain();
win.add(canvas);
win.setVisible(true);
}
}
BoxyMethod.java:
import java.awt.*;
import javax.swing.JFrame;
public class BoxyMethod {
public void drawBox(Graphics window, Color c, int x, int y){
window.setColor(c);
window.fillRect(x, y, 100, 100);
window.setColor(Color.WHITE);
window.fillRect(x+10,y+10,80,80);
}
}
Error text: "window cannot be resolves to a variable."
The error message is telling you exactly what is wrong. You're passing in a window variable into the drawBox method, but you don't declare or initialize such a variable in the main method before doing so, and so this cannot be done in Java.
BoxyMethod c = new BoxyMethod();
// *** window variable below is used but never declared prior to use
c.drawBox(window, Color.RED, 200, 300);
More importantly though, you're not doing Swing drawing correctly.
Instead, you should create a class that extends JPanel, give it a paintComponent(Graphics g) method override, and draw in that method. Then place that JPanel in a JFrame and display the JFrame. Please check out the Performing Custom Painting Swing graphics tutorial for more detail on how to do Swing graphics.
As an aside, do not follow that tutorial that you've linked to as it is 30 years out of date.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
public class BoxyTest {
private static void createAndShowGui() {
JFrame frame = new JFrame("Boxy Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new BoxyPanel(200, 300));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class BoxyPanel extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
private int myX;
private int myY;
public BoxyPanel(int myX, int myY) {
this.myX = myX;
this.myY = myY;
}
#Override // so my JPanel will be big enough to see
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
// call super method so that the JPanel can do housekeeping painting
super.paintComponent(g);
g.fillRect(myX, myY, 100, 100);
g.setColor(Color.WHITE);
g.fillRect(myX + 10, myY + 10, 80, 80);
}
}

How to resize frame dynamically with Timer?

I'm trying to resize a window dynamically using a Timer object, but not succeeding... I set the preferred size of the panel in the constructor, which sets the size of the window nicely, though only once. The preferred size changes after the program is initialized, but the window size stays the same. Why? Because the constructor is initialized only once and therefore isn't affected by the size change? If so, how could I get around this to resize the window in real-time?
I know this won't solve the problem in the exercise given in the beginning comments, so please ignore that :-)
/*
* Exercise 18.15
*
* "(Enlarge and shrink an image) Write an applet that will display a sequence of
* image files in different sizes. Initially, the viewing area for this image has
* a width of 300 and a height of 300. Your program should continuously shrink the
* viewing area by 1 in width and 1 in height until it reaches a width of 50 and
* a height of 50. At that point, the viewing area should continuously enlarge by
* 1 in width and 1 in height until it reaches a width of 300 and a height of 300.
* The viewing area should shrink and enlarge (alternately) to create animation
* for the single image."
*
* Created: 2014.01.07
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Ex_18_15 extends JApplet {
// Main method
public static void main(String[] args) {
JFrame frame = new JFrame();
Ex_18_15 applet = new Ex_18_15();
applet.isStandalone = true;
frame.add(applet);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// Data fields
private boolean isStandalone = false;
private Image image = new ImageIcon("greenguy.png").getImage();
private int xCoordinate = 360;
private int yCoordinate = 300;
private Timer timer = new Timer(20, new TimerListener());
private DrawPanel panel = new DrawPanel();
// Constructor
public Ex_18_15() {
panel.setPreferredSize(new Dimension(xCoordinate, yCoordinate));
add(panel);
timer.start();
}
class DrawPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(yCoordinate <= 50) {
yCoordinate++;
xCoordinate++;
}
else if(yCoordinate >= 300) {
yCoordinate--;
xCoordinate--;
}
panel.setPreferredSize(new Dimension(xCoordinate, yCoordinate));
repaint();
}
}
}
You need to re-pack your JFrame to resize it. For instance at the end of your ActionListener:
Window win = SwingUtilities.getWindowAncestor(panel);
win.pack();
A question for you though: Why in heaven's name is your class extending JApplet and not JPanel? Or if it needs to be an applet, why are you stuffing it into a JFrame?
Edit
Regarding your comment:
Wouldn't it usually be extending JFrame not JPanel? I'm stuffing it into a JFrame to allow it to run as an application as well as an applet. That's how 'Introduction to Java Programming' tells me how to do it :p Adding your code at the end of the actionPerformed method didn't do anything for me ;o
Most of your GUI code should be geared towards creating JPanels, not JFrames or JApplets. You can then place your JPanels where needed and desired without difficulty. Your book has serious issues and should not be trusted if it is telling you this.
Edit 2
Works for me:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class ShrinkingGui extends JPanel {
private static final int INIT_W = 400;
private static final int INIT_H = INIT_W;
private static final int TIMER_DELAY = 20;
private int prefW = INIT_W;
private int prefH = INIT_H;
public ShrinkingGui() {
new Timer(TIMER_DELAY, new TimerListener()).start();;
}
public Dimension getPreferredSize() {
return new Dimension(prefW, prefH);
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (prefW > 0 && prefH > 0) {
prefW--;
prefH--;
Window win = SwingUtilities.getWindowAncestor(ShrinkingGui.this);
win.pack();
} else {
((Timer)e.getSource()).stop();
}
}
}
private static void createAndShowGUI() {
ShrinkingGui paintEg = new ShrinkingGui();
JFrame frame = new JFrame("Shrinking Gui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(paintEg);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Swing timers basic functionality [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm new at java graphic design, and I would like you, if possible, to help me with an easy example to help me to get to understand the basic functionality of JFrames, Timers, SwingControllers, and all this stuff. How would you implement the following case:
We have a JFrame with a JPanel inside.
When the execution starts, the JPanel is white, but we want it to change it's colour every two seconds:
public class MiJFrame extends javax.swing.JFrame {
public MiJFrame() {
initComponents();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MiJFrame().setVisible(true);
jPanel1.setBackground(Color.yellow);
jPanel1.setBackground(Color.RED);
}
});
}
// Variables declaration - do not modify
private static javax.swing.JPanel jPanel1;
// End of variables declaration
}
At first, I used the sleep method of a thread object between the setBackgroud() methods but it doesn't work, as it only shows the last change. How would you use here a Timer object?
First of all, whenever you need to change the colour of the said thingy, always set Opaque property to true for the said thingy. Like in your case it's the JPanel so first of all you must use panelObject.setOpaque(true), for some Look And Feels calling this method is a must for background colour changes to take effect.
Do try this code example, regarding the rest :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* #see
* http://stackoverflow.com/q/11036830/1057230
*/
public class ColourTimer
{
private JPanel contentPane;
private Timer timer;
private int counter;
private Color[] colours = {
Color.RED,
Color.WHITE,
Color.BLUE,
Color.DARK_GRAY,
Color.YELLOW,
Color.LIGHT_GRAY,
Color.BLACK,
Color.MAGENTA,
Color.PINK,
Color.CYAN
};
private ActionListener timerAction = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
if (counter == (colours.length - 1))
counter = 0;
contentPane.setBackground(colours[counter++]);
}
};
public ColourTimer()
{
counter = 0;
}
private void displayGUI()
{
JFrame frame = new JFrame("Colour Timer");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = new JPanel();
contentPane.setOpaque(true);
final JButton button = new JButton("STOP");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
if (timer.isRunning())
{
button.setText("START");
timer.stop();
}
else
{
button.setText("STOP");
timer.start();
}
}
});
frame.getContentPane().add(contentPane, BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.PAGE_END);
frame.setSize(300, 200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
timer = new Timer(2000, timerAction);
timer.start();
}
public static void main(String... args)
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new ColourTimer().displayGUI();
}
});
}
}

Categories

Resources