I want to set the background of the JDesktopPane (I add this JDesktopPane directly from the palette into the JFrame)
I try to override the method public void paintComponent (Graphics g) but it's not working
Here is the code:
JDesktop p = new JDesktop();
ImageIcon icon = new ImageIcon("images/Nénuphars6892.jpg");
final Image img = icon.getImage();
img.getScaledInstance(159, 207, Image.SCALE_SMOOTH);
p.principal = new JDesktopPane() {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(img, 0, 0, getSize().width, getSize().height, this);
}
};
p.setVisible(true);
I resolve this problem by adding that on the creation of the JDesktopPane choosing customize code (variable principal) :
principal = new javax.swing.JDesktopPane()
{
ImageIcon icon = new ImageIcon("images/blue_digital_waves_abstract.jpg");
Image image = icon.getImage();
Image newimage = image.getScaledInstance(1500, 1000, Image.SCALE_SMOOTH);
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(newimage, 0, 0, this);
}
}
;
JDesktopPane desktopPane = new JDesktopPane() {
private final ImageIcon image = new ImageIcon("sample.jpg");;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = (desktopPane.getWidth() - image.getIconWidth()) / 2;
int y = (desktopPane.getHeight() - image.getIconHeight()) / 2;
g.drawImage(image.getImage(), x, y, this);
}
};
Related
I'm writing paint on screen program using Java Swing. It working on ubuntu linux. But windows shows black screen instead of transparent panel. I included similar example code. What is wrong in my code?
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Example {
public static final Color COLOR_TRANSPARENT = new Color(0,0,0,0);
public Example() {
Canvas drawArea = new Canvas();
drawArea.setBackground(COLOR_TRANSPARENT);
drawArea.setOpaque(true);
JWindow drawingFrame = new JWindow();
drawingFrame.setBackground(COLOR_TRANSPARENT);
drawingFrame.setContentPane(drawArea);
drawingFrame.pack();
drawingFrame.setSize(640, 460);
drawingFrame.setVisible(true);
drawingFrame.setLocationRelativeTo(null);
drawingFrame.setAlwaysOnTop(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(Example::new);
}
class Canvas extends JPanel{
private Image image;
private Graphics2D g2;
public Canvas() {
super();
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
g2.setPaint(Color.RED);
g2.fillOval(x-10, y-10, 20, 20);
repaint(x-10, y-10, 20, 20);
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image == null){
image = createImage(getWidth(), getHeight());
g2 = (Graphics2D) image.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setBackground(COLOR_TRANSPARENT);
clear();
}
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(image, 0,0, null);
}
public void clear(){
System.out.println("clearing canvas ");
g2.setComposite(AlphaComposite.Clear);
g2.setBackground(COLOR_TRANSPARENT);
g2.setColor(COLOR_TRANSPARENT);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.clearRect(0, 0, getWidth(), getHeight());
g2.setPaint(Color.RED);
g2.setComposite(AlphaComposite.SrcOver);
repaint();
}
}
}
Here is screenshot what I wanted.
Example code updated. Now code should work without any other additional code.
For windows I made a couple of changes:
image = createImage(getWidth(), getHeight());
image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
I used a BufferedImage to you can set the alpha values of the image to be transparent.
//public static final Color COLOR_TRANSPARENT = new Color(0,0,0,0);
public static final Color COLOR_TRANSPARENT = new Color(0,0,0,1);
I made the alpha value non-zero, because a value of zero means the Java application won't receive the MouseEvent because it is passed to the application under the window.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I've been trying to make a shop for my game.
This has been unsuccessful.
I've tried drawComponent, didn't work.
No errors, code executed, but didn't work.
Now i'm trying to do:
private void render() {
Graphics2D g = (Graphics2D) graphics.getGraphics();
/////////////////////
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
/////////////////////
g.dispose();
Graphics2D g2d = (Graphics2D) getGraphics();
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
}
Now i get a NullPointerException on g2d.
I've tried everything.
`Exception in thread "game" java.lang.NullPointerException
at com.johnythecarrot.game.Shop$DrawPane.access$2(Shop.java:123)
at com.johnythecarrot.game.Shop.render(Shop.java:154)
at com.johnythecarrot.game.Game.render(Game.java:75)
at com.johnythecarrot.game.Game.run(Game.java:112)
at java.lang.Thread.run(Unknown Source)`
My goals are to be able to have clickable buttons.
It DID work. But i had to restart almost everytime. Because mostly of the time to code wasn't even executed. So i tried to fix it. Now it's all messed up.
This is the code to it.
(DoubleInt is a part of my library it's nothing more than just x and y. )
public class Shop {
public BuildWindow window;
public static JWindow w;
private int WIDTH = 860, HEIGHT = 440;
private BufferedImage graphics = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
public DrawPane drawPane;
public Shop() {
//window = new BuildWindow().setSize(new DoubleInt(100, 100)).at(wi, he).setTitle("Shop").setOpacity(1).setDragable(false).showEmpty(true);
w = new JWindow();
w.setOpacity(1);
w.setSize(WIDTH, HEIGHT);
w.setLocation(800, 800);
w.setVisible(false);
w.setAlwaysOnTop(true);
//graphics = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
}
private void createShop() {
/***Graphics2D g = (Graphics2D) graphics.getGraphics();
g.setColor(Color.blue);
g.drawString("hey", WIDTH-50, HEIGHT-50);
g.fillRect(0, 0, WIDTH, HEIGHT);*/
}
public class DrawPane extends JPanel {
int width = WIDTH;
int height = HEIGHT;
private ArrayList<Shape> buttons;
private Shape btn1 = new Rectangle2D.Double(20, 60, width/2, height-20);
private Shape btnClose = new Rectangle2D.Double(width-25, 5, 20, 20);
Point wCoords;
Point mCoords;
public DrawPane() {
buttons = new ArrayList<>();
buttons.add(btn1);
buttons.add(btnClose);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
for(Shape s : buttons) {
if(s.contains(e.getPoint())) {
System.out.println("Clicked " + s.getBounds());
if(s == btnClose) {
w.dispose();
}
}
}
}
#Override
public void mousePressed(MouseEvent e) {
mCoords = e.getPoint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
mCoords = null;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
wCoords = e.getLocationOnScreen();
w.setLocation(wCoords.x - mCoords.x, wCoords.y - mCoords.y);
}
});
}
void repaintThis() {
repaint();
}
BufferedImage img = loadImageFrom.LoadImageFrom(Shop.class, "bar.png");
Graphics gb;
/**
* super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.red);
//g.fillRect(0, 0, width, 50);
g.drawImage(img, 0, 0, width, 50, null);
g.setColor(Color.WHITE);
g.drawString("SHOP", 15, 30);
g.drawString("X", width-20, 20);
for(Shape b : buttons) {
g2d.draw(b);
}
System.out.println("Built");
gb = g;
*/
private void render() {
Graphics2D g = (Graphics2D) graphics.getGraphics();
/////////////////////
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
/////////////////////
g.dispose();
Graphics2D g2d = (Graphics2D) getGraphics();
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
}
public void Build() {
Graphics g = gb;
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.red);
//g.fillRect(0, 0, width, 50);
g.drawImage(img, 0, 0, width, 50, null);
g.setColor(Color.WHITE);
g.drawString("SHOP", 15, 30);
g.drawString("X", width-20, 20);
for(Shape b : buttons) {
g2d.draw(b);
}
System.out.println("Built");
}
}
public void render(Graphics2D g) {
drawPane.render();
}
public void addDrawPane() {
drawPane = new DrawPane();
w.add(drawPane);
}
}
If you need access to more code, just ask me.
You should override the paintComponent method like this:
public class DrawPane extends JPanel {
// all your variables and other things
#Override
paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
// Your code goes here, use the g2d
}
}
then if you need to repaint your component, simply call repaint() on it.
I am trying to code a board game in Java.
I have the board which is an image and the pawns which are shapes (for example a rectangle). I want the board to be the background in the JFrame and the pawns to be over the board. I have tried multiple times but either the board covers the shape or only the shape appears. I could join the shape with the image..and create a new image but this is not what i want. Any ideas?
public class Board extends JPanel {
#Override
public void paintComponent(Graphics g) {
try {
BufferedImage img = ImageIO.read(new File("C:\\Users\\i\\Desktop\\j.png"));
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}catch (IOException ex) {
Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And my other class
public class GameGUI extends javax.swing.JFrame {
public GameGUI() {
Board b=new Board();
setContentPane(b);
setSize(600,600);
setTitle("gui");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
}
The class for the player
public class Player extends JPanel{
int xPos = 100, yPos = 100, vwidth = 100, vheight = 100;
Rectangle r = new Rectangle(xPos, yPos, vwidth, vheight);
public Player(){ .....}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
g.setColor(Color.black);
if (fill) {
g.fillRect((int) r.getX(), (int) r.getY(), (int) r.getWidth(), (int) r.getHeight());
}
g2.draw(r);
}
}
I have a JLayeredPane with 4 layers added to it. 1 base layer, which is opaque and three 'transparent' layers (setOpaque(false)).
The problem is that although the panels are drawn onto, with every refresh a gray color is shown. The same thing happens if there is no refresh happening. In other words, instead of showing whatever was drawn onto the base layer, a gray color is shown, I assume this is from one of the layers above.
Here is a SSCCE - I'm not sure if this is short enough but it shows my problem.
public class SSCCE extends JLayeredPane{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setSize(950, 600);
frame.add(new SSCCE());
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// private fields
private boolean drawInitial = true;
private boolean drawn = false;
private JPanel overlay, base, iconPanel, middle;
private BufferedImage baseBuffer, midBuffer, overlayBuffer, iconBuffer;
private boolean updateInit = true;
private Rectangle2D stored = new Rectangle2D.Double(60, 60, 40, 100);
public SSCCE() {
setBorder(new LineBorder(Color.BLACK));
setDoubleBuffered(false);
setOpaque(true);
setSize(new Dimension(950, 600));
setPreferredSize(new Dimension(950, 600));
base = new JPanel();
base.setBackground(new Color(0,0,0,0));
base.setSize(new Dimension(getWidth(), getHeight()));
this.add(base, new Integer(0));
middle = new JPanel();
middle.setSize(new Dimension(getWidth(), getHeight()));
middle.setBackground(new Color(0,0,0,0));
middle.setOpaque(false);
this.add(middle, new Integer(1));
overlay = new JPanel();
overlay.setBackground(new Color(0,0,0,0));
overlay.setOpaque(false);
overlay.setSize(new Dimension(getWidth(), getHeight()));
this.add(overlay, new Integer(2));
iconPanel = new JPanel();
iconPanel.setBackground(new Color(0,0,0,0));
iconPanel.setSize(getWidth(), getHeight());
iconPanel.setOpaque(false);
this.add(iconPanel, new Integer(3));
}
public void update() {
if(updateInit){
checkBuffer();
updateInit = false;
}
drawInfoRect();
drawIcon();
highlightPath(stored);
}
public void render() {
if (drawInitial) {
Graphics2D baseGraphics = (Graphics2D) base.getGraphics();
baseGraphics.drawImage(baseBuffer, 0, 0, null);
}
setResistanceColor((Graphics2D)baseBuffer.getGraphics());
middle.getGraphics().drawImage(midBuffer, 0, 0, null);
iconPanel.getGraphics().drawImage(iconBuffer, 0, 0, null);
drawInfoRect();
base.getGraphics().drawImage(baseBuffer, 0, 0, null);
if (drawn) {
overlay.getGraphics().drawImage(overlayBuffer, 0, 0, null);
}
repaint();
}
// /**
// * draws the appropriate colour
// */
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
update();
render();
}
/**
* sets the appropriate colours according to the resistance
* #param g2
*/
private void setResistanceColor(Graphics2D g2) {
Rectangle2D sp = new Rectangle2D.Double(50,50, 50, 50);
g2.setColor(Color.GREEN);
g2.fill(sp);
g2.setColor(Color.BLACK);
}
/**
* checks if there already exists an image to buffer with
*/
private void checkBuffer() {
if (baseBuffer == null) {
baseBuffer = (new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB));
// background color
Graphics2D g2 = (Graphics2D) baseBuffer.getGraphics();
g2.setColor(Color.decode("#729fcf"));
Rectangle2D rect = new Rectangle2D.Double(0, 0, baseBuffer.getWidth(), baseBuffer.getHeight());
g2.fill(rect);
}
if (midBuffer == null) {
midBuffer = (new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB));
// background color
Graphics2D g2 = (Graphics2D) midBuffer.getGraphics();
g2.setColor(Color.RED);
Rectangle2D rect = new Rectangle2D.Double(0, 0, midBuffer.getWidth(), midBuffer.getHeight());
g2.fill(rect);
}
if (overlayBuffer == null) {
overlayBuffer = (new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB));
}
if (iconBuffer == null) {
iconBuffer = (new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB));
}
}
public void highlightPath(Shape enlighten) {
Area area = new Area();
area.add(new Area(enlighten));
// clearing image before drawing
Graphics2D midBufferG = (Graphics2D) midBuffer.getGraphics();
clearImage(midBufferG);
midBufferG.setColor(Color.white);
// adds a transparent overlay
midBufferG.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.50f));
midBufferG.fill(area);
}
public void drawIcon() {
Graphics2D iconG = (Graphics2D) iconBuffer.getGraphics();
clearImage(iconG);
}
public void drawInfoRect() {
Graphics2D graph = (Graphics2D) overlayBuffer.getGraphics();
Rectangle2D visible = getVisibleRect();
int boxX = (int) (visible.getX() + 50);
int boxY = (int) (visible.getY() + 450);
RoundRectangle2D rect = new RoundRectangle2D.Double(boxX, boxY, 200, 150, 25, 25);
graph.setColor(Color.decode("#729fcf").darker());
graph.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.4f));
graph.fill(rect);
graph.setColor(Color.BLACK);
drawn = true;
}
private void clearImage(Graphics2D graph){
graph.setComposite(AlphaComposite.Clear);
graph.fillRect(0, 0, overlayBuffer.getWidth(), overlayBuffer.getHeight());
graph.setComposite(AlphaComposite.SrcOver);
}
}
It might be some basic mistake I made. Thanks for your help!
One of the previously suggested answers actually solved my question, but for some reason they deleted their answer.
Setting the Background of my panels to setBackground(new
Color(0,0,0,0)); solved my problems.
According to the person that suggested this, the cause of that is the fact that JComponent may or may not draw transparent if not explicitly specified.
Thanks again!
Here is the problem I am currently facing: I want to draw a String on a JPanel using Java2D. The String has to be rotated of a user-defined angle.
Under that String, I also paint the background in a given color to facilitate reading (plenty of other things are drawn on my JPanel).
What I did, in the overridden paint method of my JPanel, is the following:
final Graphics2D g2 = (Graphics2D) g.create();
final int textWidth = g.getFontMetrics().stringWidth(textToDraw);
final int textHeight = g.getFontMetrics().getHeight();
g2.translate(pointToDraw.x, pointToDraw.y);
g2.rotate(angle);
g2.setColor(textBackground);
g2.fillRect(deltaX, -textHeight, textWidth, textHeight);
g2.setColor(drawColor);
g2.setFont(font);
g2.drawString(textToDraw, deltaX, deltaY);
g2.dispose();
This works very well on linux, but on Mac OS X (with Java 1.6), the text is not displayed properly: the text is correctly rotated but after each character, there is a line break.
How can I make it work on both platforms?
I don't think this is the solution you will want, but from everything I've been able to read, there doesn't seem to be a better solution...
The problem seems to be that the Mac is rotating each character, not just the String
Basically, I've cheated. This renders the text to a BufferedImage (you should create the image only when the properties change, unlike me, which I've done it within the paint method) and then rotates the image...
public class RotateText {
public static void main(String[] args) {
new RotateText();
}
public RotateText() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private String textToDraw = "Stack Overflow";
private double angle = 90;
private Color drawColor = Color.BLACK;
public TestPane() {
Timer timer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
angle += 2;
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
final Graphics2D g2 = (Graphics2D) g.create();
FontMetrics fm = g2.getFontMetrics();
int textWidth = fm.stringWidth(textToDraw);
int textHeight = fm.getHeight();
BufferedImage img = new BufferedImage(textWidth, textHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D ig = img.createGraphics();
ig.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
ig.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
ig.setColor(drawColor);
ig.drawString(textToDraw, 0, fm.getAscent());
ig.dispose();
int x = (getWidth() - textWidth) / 2;
int y = (getHeight() - textHeight) / 2;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angle), getWidth() / 2, getHeight() / 2));
g2.drawImage(img, x, y, this);
g2.dispose();
}
}
}