Java making a 'dot/pixel' In swing/awt - java

I want to know how to make a dot/pixel at a certain x,y co-ordinate on my JFrame.
Anyone know some simple code for this?

I have created a small example program:
public class Test extends JFrame {
public Test() {
this.setPreferredSize(new Dimension(400, 400));
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
#Override
public void paint(Graphics g) {
super.paint(g);
// define the position
int locX = 200;
int locY = 200;
// draw a line (there is no drawPoint..)
g.drawLine(locX, locY, locX, locY);
}
public static void main(String[] args) {
Test test = new Test();
}
}
You could also use the update or paintComponents method which would be much nicer. But then you have to make sure, that it gets called. If you have problems and it does not get called you could use the following solution: Why is paint()/paintComponent() never called?

Best compromise between simplicity and usefulness would probably be to extend JPanel, and override paintComponent( Graphics ). Then place that panel in your JFrame (with an appropriate layout. There are some usage notes here: http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JComponent.html#paintComponent%28java.awt.Graphics%29

see
void update(Graphics g)
method of JFrame class.
graphics API ( like draw point, draw line, draw arc, etc ) are in Graphics class.
EDIT: http://www.javadb.com/drawing-a-line-using-java-2d-graphics-api

Ask yourself if your really want to extend JFrame or JPanel. If you decide that you don't then you could create a basic JComponent. You may have varying success with this depending on what layout manager you use.
public class PixelComponent extends JComponent
{
private Color color;
public PixelComponent(Color color)
{
super();
this.color = color;
}
public PixelComponent()
{
this(Color.BLACK);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(color);
g.fillRect(0, 0, 1, 1);
}
}

Send the Graphics Reference and axis x and y to make a pixel:
private void doPixel(Graphics g, int x, int y){
g.fillRect(x, y, 1, 1);
}

Related

Draw and redraw on a canvas in swing

I know there's no direct replacement for java.awt.Canvas in swing, and I know I'm supposed to use a JPanel and override paintComponent, for example like so:
public void paintComponent(Graphics g) {
g.setColor(Color.black);
g.drawOval(0, 0, 100, 100);
}
And this would draw a black circle on the JPanel when it is created. The problem I have is that I want a dynamic canvas: I want to be able to draw things in response to user input, and redraw continuously, not just once when the application starts. An example would be having a moving object on a canvas, that would need to be redrawn at a rate of say 60 frames per second. How could I achieve this without using AWT components?
EDIT: what I mean is, in an actual canvas, I'd be able to arbitrarily call, say, drawOval anywhere in my code, and that would draw an oval on the canvas; is this doable with JPanel?
Store the information to be drawn (e.g. a Shape or a group of them) and call repaint() from a Swing Timer. Each time the paintComponent(..) method is called, first call the super(..) method to erase the previous drawings, then iterate the list of shapes, move them if necessary, and draw each one.
Here's one way to do it:
public class Renderer extends JComponent implements ActionListener {
private int x;
public Renderer() {
Timer timer = new Timer(1000/60, this);
timer.start();
x = 0;
}
#Override
public void paintComponent(Graphics g) {
super.paint(g);
// drawing code
g.setColor(Color.black);
g.drawOval(x, 0, 100, 100);
}
private void update() {
this.x++;
}
#Override
public void actionPerformed(ActionEvent e) {
update();
repaint();
}
}
Now just add this to your component (JPanel or whatever):
comp.add(new Renderer());

JFrame not displaying anything

I cannot seem to get a rectangle to be displayed in the JFrame. Per the parameters of this project, I have to have this class implement the Icon interface. When I run the code as is, I get the JFrame, but nothing shows up inside. It should display a black square. I'm assuming the problem has something to do with how I am initializing the graphics instance variable. I don't have much experience working with GUI graphics, so I'm not entirely clear on how to do this correctly.
And yes, I do know that the getIconWidth and getIconHeight methods are redundant since I am using constants, but I have to have these methods in order to implement the interface.
public class MugDisplay extends JFrame implements Icon {
private int width;
private int height;
private JPanel panel;
private Graphics graphics;
private static final int ICON_WIDTH = 100;
private static final int ICON_HEIGHT = 100;
public MugDisplay() {
this.configureGui();
this.panel = new JPanel();
this.panel.setLayout(new BorderLayout());
this.add(this.panel, BorderLayout.CENTER);
this.graphics = this.getGraphics();
int xPos = (this.panel.getWidth() - this.getIconWidth()) / 2;
int yPos = (this.panel.getHeight() - this.getIconHeight()) / 2;
this.paintIcon(this.panel, this.graphics, xPos, yPos);
}
#Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
g2.fillRect(x, y, ICON_WIDTH, ICON_HEIGHT);
}
#Override
public int getIconWidth() {
return ICON_WIDTH;
}
#Override
public int getIconHeight() {
return ICON_HEIGHT;
}
private void configureGui() {
this.setPreferredSize(new Dimension(600, 600));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(new BorderLayout());
this.pack();
this.setVisible(true);
}
}
In the interest of having a MCVE, here is the driver class that calls this class.
public class Main {
public static void main(String[] args) {
MugDisplay md = new MugDisplay();
md.setVisible(true);
}
}
this.graphics = this.getGraphics() is not how custom painting works in Swing. What you should do is create a panel, override its paintComponent method, make the call to super, and then do your painting. For instance:
panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int xPos = ...
paintIcon(this, g, xPos, yPos);
}
}
Calling getGraphics will provide you with a short-lived Graphics object that can soon become invalid, which is why you should opt for overriding paintComponent instead, which will always give you a usable Graphics object. See Performing Custom Painting.
On a separate note, it looks like you're calling setVisible(true) before you're finished adding the necessary components to the JFrame. To ensure that your components show up, call setVisible(true) after adding them all to the frame.

Transparency not working in java

I have an image, with a complete transparent background. However when I draw this image, ingame, it has a kind of shade to it, and I have no clue why. I would like to get that out of there. Does anyone have an idea? I don't have the reputation to post images of it apparently... So I'll try to give some more information.
I have the Color.DARK_GRAY as background, and when I draw the image, you see a lighter gray square around it.
Then when I draw a couple of these images ontop of eachother, that square gets lighter and lighter.
If I draw the image ontop of another image however, this effect does not occur.
Here I load the image
public BlackChip() {
this.value = 500;
this.url = "res/images/poker/blackchip.png";
this.file = new File(url);
BufferedImage bi;
try {
bi = ImageIO.read(file);
this.image = bi;
} catch (IOException e) {
e.printStackTrace();
}
}
Here I draw the image
public void renderChip(Chip chip, int x, int y) {
g.drawImage(chip.getImage(), x, y, null);
}
Here I call that method
public void render() {
screen.renderBackground(Color.DARK_GRAY);
pokertable.render(Game.width / 2 - pokertable.getImage().getWidth(null) / 2, 50);
screen.renderChip(cs.getWhiteChip(), 380, 310);
screen.renderChip(cs.getRedChip(), 430, 310);
screen.renderChip(cs.getGreenChip(), 480, 310);
screen.renderChip(cs.getBlueChip(), 530, 310);
screen.renderChip(cs.getBlackChip(), 580, 310); //this one is it
}
link to the images:
https://drive.google.com/file/d/0Bz-4pfUssUeHRWkxaUhodWNILWc/edit?usp=sharing
Well... this doesn't work either because i need 10 reputation to post more then 1 link
you can see the effect on this link, it's the image with full transparent background, drawn multiple times.
I can't tell if this is the exact cause of the problem, because you haven't provided a MCVE but this method
public void renderChip(Chip chip, int x, int y) {
g.drawImage(chip.getImage(), x, y, null);
}
Just looks wrong. All custom painting should be done within the context of the provided Graphics object in the overridden paintComponent method. If you have not overriden paintComponent in a JPanel or a JComponent then you are likely not painting correctly. You may be doing something like
public class SomePanel extends JPanel {
private Graphics g;
public SomePanel() {
g = getGraphics();
}
}
Which is completely wrong. You should instead be doing something like
public class SomePanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// do painting here
}
}
You Classes can then have it's own render method that takes a Graphics object as an argument. Then can be called in the paintComponent method. Maybe something like
public class Chip {
private JComponent imageObserver;
private BufferedImage chipImage;
int x, y;
public Chip(BufferedImage chipImage, int x, int y, JComponent imageObserver){
this.chipImage;
this.x = x;
this.y = y;
this.imageObserver = imageObserver;
}
public void renderChip(Graphics g) {
g.getImage(chipImage, x, y, imageObserver);
}
}
And your panel
public class SomePanel extends JPanel {
private List<Chip> chips;
public SomePanel() {
chips = new ArrayList<Chip>();
// add new Chips
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Chip chip: chips) {
chip.renderChip(g);
}
}
}

Java setBackground() confusion

I'm new to the Java swing library and I'm currently having some trouble setting the background of my JFrame.
I have read jframe-setbackground-not-working-why and the link inside it, but it doesn't seem to fit here.
Here is my codes:
public class Board extends JPanel{
public enum pointType{
EMPTY,
CARRIER,
BALL;
}
private class Point{
int x;
int y;
pointType type;
public void paint (Graphics2D g2){
// color changes depends on pointType
g2.setColor(Color.WHITE);
g2.fillOval(x,y,25,25);
}
}
Point[][] myBoard;
public Board(){
//constructor, myBoard = 2d List of points
}
//.. other methods and class variables
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D) g;
for(int k =HEIGHT; k>=0; k--){
for(int i=WIDTH; i>=0; i--){
// call paint method for each points on board
myBoard[i][k].print(g2);
}
}
}
public static void main(String[] args){
Board board = new Board();
JFrame myFrame = new Jframe("Game");
myFrame.add(board);
board.setBackground(Color.YELLOW);
myFrame.setVisible(true);
mtFrane.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
My code successfully prints all the points according to their pointType, but the board color is not set correctly (still default background).
So here are the questions:
1) How should I set the background correctly?
2) I feel that my code is not using JPanels/JFrames/Graphics together correctly, if that's the case, any suggestions on how I improve my code structures?
Use paintComponent() instead of paint()
public class Board extends JPanel{
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
...
}
}
For more info have a look at below posts:
Difference between paint() and paintcomponent()?
paint() vs. paintComponent(): A Resolution
The default paintComponent() method in JPanel uses the background color stored in the JPanel's instance variable; however, your overridden paintComponent() method doesn't make use of the instance variable and so changing it with setBackground() won't do anything.
If you want to stick with overriding the paintComponent() method, you should draw a box filling the entire area of the JPanel with the color which you want inside the paintComponent() method.
The new paintComponent() method for Board would look like this:
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.YELLOW);
g2.fillRect(0, 0, getWidth(), getHeight()); // Fill in background
// Do everything else
for(int k =HEIGHT; k>=0; k--){
for(int i=WIDTH; i>=0; i--){
// call paint method for each points on board
myBoard[i][k].print(g2);
}
}
}

A method in a class meant to create a shape, doesn't do so

I made a class that creates a blank JFrame.
Then I created another class, which I added as an instance to the JFrame.
This class has a method, MakeRect, that is supposed to make a rectangle on the panel.
I know you could do this by simply adding g.fillRect(120,120,120,120) to paintComponent(), without another method.
But I'm curious to know why calling another method to do the job doesn't work.
It gives me 'NullPointerException'. Thanks for the help
import java.util.*;
import java.awt.*;
import java.awt.Event.*;
import javax.swing.*;
public class DrawingPanel extends JPanel {
Graphics g;
public void paintComponent(Graphics g){
super.paintComponent(g);
makeRect();
}
public void makeRect(Graphics g){
g.fillRect(120,120,120,120);
}
}
EDIT: Thanks, I got my answer and it works. Added the Graphics g arguement to makeRect().
Is it possible to calls makeRect() from a different class?
All you need to do is pass the reference to the Graphics object into makeRect, at the moment you are referring to a member variable that you never initialize.
public void paintComponent(Graphics g){
super.paintComponent(g);
makeRect(g);
}
public void makeRect(Graphics g){
g.fillRect(120,120,120,120);
}
If you want to be able to modify the drawing from another object, you can't directly draw the rectangle as that only happens in paintComponent. Instead what you do is:
int x, y, width, height;
public void setRect(int x, int y, int width, int height) {
this.x = x; // Save the dimensions of the rectangle
this.y = y;
this.width = width;
this.height = height;
repaint(); //Tell swing this class needs redrawing
}
public void paintComponent(Graphics g){
super.paintComponent(g);
makeRect(g);
}
public void makeRect(Graphics g){
g.fillRect(x,y,width,height); // Use the saved parameters to draw with
}
The value of g in your makeRect is going to be null
You should avoid maintaining a reference to any graphics context you did not create yourself.
Instead, allow makeRect to accept a reference to Graphics
public void paintComponent(Graphics g){
super.paintComponent(g);
makeRect(g);
}
public void makeRect(Graphics g){
g.fillRect(120,120,120,120);
}

Categories

Resources