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 8 years ago.
Improve this question
I've looked around a little, and I was surprised that I couldn't find a way to draw and fill a parallelogram with java swing. Is there a easy way to do that?
Thanks for your help in advance.
All (or at least most) drawing in swing is done by subclassing JPanel and overriding the paintComponent method. So it will start like this:
public class MyPanel extends JPanel{
#Override
public void paintComponent(Graphics g){
//Drawing stuff....
}
}
From here, you're going to want to create a Parallelogram Shape, and fill it. The simplest implementation of Shape for your use is Path2D.
public class MyPanel extends JPanel{
private Path2D.Double parallelogram;
public MyPanel(){
parallelogram = new Path2D.Double();
parallelogram.moveTo(0,0);
parallelogram.lineTo(50,0);
parallelogram.lineTo(100,50);
parallelogram.lineTo(50,50);
parallelogram.closePath();
setPreferredSize(new Dimension(100, 100));
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLACK);
g2d.fill(parallelogram);
}
}
Then create an instance of this panel and add it to a JFrame:
public static void main(String[] args){
JFrame f = new JFrame();
f.add(new MyPanel(), BorderLayout.CENTER);
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Suggestions:
Create a Shape using a Path2D object,
start your parallelogram using its moveTo(...) method
Continue drawing lines using its lineTo(...) methods.
Draw in the paintComponent(Graphics g) method override of a JPanel.
In this method cast the Graphics object into a Graphics2D object.
Then call fill(yourShape) passing in your Path2D object.
Related
I am new to Java and I am trying to add print-preview in my J-frame, I tried a PrintPreview class found on given below link. But problem with this class is after creating an object to PrintPreview class it is asking for (Frame, canvas, page). In frame I pass this for my current frame, and in page "A4"
but for convas I didn't getting what to pass in constructor of PrintPreview.
I opened convas2D class for which convas is referring but can't find any help?
Code Source:
If you'd like a better help, try submitting your code but see if that piece of code help you:
class MyCanvas extends Canvas {
public MyCanvas () {
setBackground (Color.GRAY);
setSize(300, 300);
}
public void paint (Graphics g) {
Graphics2D g2;
g2 = (Graphics2D) g;
g2.drawString ("It is a custom canvas area", 70, 70);
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am new to java and I want to draw circle and rectangle by using java code. I did write code for that purpose and tried at my own. But on Panel is appearing and shapes are not appearing.
Code of "MyPanel" is given below
import javax.swing.*;
import java.awt.*;
public class MyPanel extends JPanel{
public void painComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.drawRect(20,20,20,20);
g2.setColor(Color.blue);
g2.fillOval(50,20,20,20);
g2.drawString("Hello World", 120, 50);
}//end painComponent
}//end test class
Cdoe of driver class "Test" is given below.
import javax.swing.*;
import java.awt.*;
public class Test{
JFrame f;
MyPanel p;
public Test(){
f = new JFrame();
Container c = f.getContentPane();
c.setLayout(new BorderLayout());
p = new MyPanel();
c.add(p, BorderLayout.CENTER);
f.setSize(400,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//end of constructor
public static void main(String args[]){
Test t = new Test();
}
}
And as per my knowledge when frame becomes visible through the paintChildren() method then panel should become visible
Also to become visible panel will call paintComponent() method which will do your custom drawing, but it seems like panel is not calling paintComponent().
Your method in MyPanel is called painComponent :-).
That is why the method from the base class is called, your method does not override any method from JPanel.
You are doing some spelling mistake. Method inside “MyPanel” is painComponent() rather paintComponent()
“t” is missing from your prototype that is why your program was not able to override paintComponent() in MyPanel class.
So all you have to do is that just update your code and replace with “paintComponent();”
Complete class code is given below,
import javax.swing.*;
import java.awt.*;
public class MyPanel extends JPanel{
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.drawRect(20,20,20,20);
g2.setColor(Color.blue);
g2.fillOval(50,20,20,20);
g2.drawString("Hello World", 120, 50);
}//end painComponent
}//end test class
I have tested this code it works fine.
In MyPanel class, the method name should be paint, instead of painComponent.
It is an overridden method, hence, the name matters.
Please change the name of the method to "paint" and try.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
say at first rectangle and then a line for example
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Canvas;
import javax.swing.JComponent;
import javax.swing.JFrame;
//class MyCanvas extends JComponent {
class MyCanvas extends Canvas {
public void paint(Graphics g) {
g.fillRect(20, 20, 500, 500);
}
}
class Linie extends MyCanvas {
public void paint(Graphics g) {
g.setColor(new Color(0, 255, 0));
g.drawLine(30, 40, 300, 100);
}
}
public class LinieUndRec {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(100, 100, 800, 800);
window.getContentPane().add(new MyCanvas());
window.getContentPane().add(new Linie());
window.setVisible(true);
}
}
this code draws only a line
how to draw a rectangle and a line
In your implementation of the Linie class, you're providing code for the paint method. This replaces the code of the paint method on the MyCanvas class, because Linie extends MyCanvas.
So, when you call paint() on an instance of Linie only the code in the Linie.paint() method is run, not both. If you want it to run both, add do this:
class Linie extends MyCanvas {
public void paint(Graphics g) {
super.paint(g); // This will draw the rectangle from the parent class,
// then render the line below
g.setColor(new Color(0,255,0));
g.drawLine(30,40, 300, 100);
}
}
As a side note, even though the code above should work, type inheritance isn't meant to solve this kind of problem. I'm just trying to provide an answer to the code as provided.
If you really want to draw a rectangle followed by a line, then call .paint() on an object that represents a rectangle, then call .paint() on an object that represents a line, one after the other. What you have here is...well, really bad code (that's okay if you're new to Java - we were all new once). You're using inheritance to accomplish what would be done by just calling two .paint() commands after each other.
Also as #Durandal points out, you can use a single canvas to do all drawings. You don't need one canvas per drawing operation. Think of a Canvas as a surface you can draw on, like a piece of paper or, well, like a painter's canvas. And think of the drawing operations as instructions of what to do in order to construct a painting. Generally speaking, you must draw things in the background first, followed by things in the foreground. The result is that drawing that happens first is covered up by drawing that happens later.
I want add JScrolpane to JPanel, but that not appears. In JLabel works fine and its very easy. I am using JPanel beacuse I'll add some image proccessing stuff to my program. There is my code:
public void draw(){
panel=new JPanel(){
protected void paintComponent(Graphics g){
Graphics g2 = g.create();
g2.drawImage(image, 0, 0, this);
g2.dispose();
}
};
panel.setBorder(BorderFactory.createEtchedBorder());
panel.setPreferredSize(new Dimension(400, 330));
s=new JScrollPane(panel);
s.setPreferredSize(new Dimension(400,285));
this.getContentPane().add(s,BorderLayout.CENTER);
add(panel);
revalidate();
repaint();
}
s=new JScrollPane(panel);
s.setPreferredSize(new Dimension(400,285));
this.getContentPane().add(s,BorderLayout.CENTER);
add(panel); // ****** ????????????
revalidate();
repaint();
}
You're adding the JPanel to the GUI not the JScrollPane, so you really shouldn't expect to see any scrollpanes if they've not been added anywhere.
Solution: Add your JScrollPane, s, that holds the JPanel to the GUI, not JPanel itself.
You dont honor the paint chain, call super.paintComponent(g) as first call in overridden paintComponent method. i.e
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
//draw here
}
or visual artifacts may occur.
Also note the #Override annotation which should be used with overridden methods in order to gain the advantage of compiler checking that we overrode the method correctly.
There is no need for getContentPane().add(..) simply call add on JFrame instance as add(..) along with remove(..) and setLayout(..) have been forward to the JFrames contentPane
Also not a good idea to go extending JFrame for nor reason, simply create an instance and use that i.e:
JFrame frame=new JFrame("Title here");
...
frame.add(..);
...
frame.pack();
frame.visible(true);
Also draw onto the Graphics object passed into paintComponent g dont go creating your own in paintComponent. Unless of course you're doing if for the reason #HFOE mentioned in below comment :).
No need for this parameter in drawImage(..) unless your JPanel implements on ImageObserver or the image may not be fully loaded when painting occurs. Simply use null.
And just for the cherry on top use some Graphics2D and RenderHints as seen here. This will allow for a better quality image to be drawn and text.
I got it! The main reason for me was no-layout manager and no-declarated size of this. There is my code:
public void draw(){
panel=new JPanel(new BorderLayout()){
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(img, 0, 0, null);
}
};
panel.setBounds(0, 0, img.getWidth(), img.getHeight());
panel.setPreferredSize(new Dimension(img.getWidth(),obraz.getHeight()));
JScrollPane scrolls=new JScrollPane(panel,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(scrolls);
validate();
repaint();
}
But if someone will want copy this code in the future, there is one thing to be known- a size of Jpanel isn't refreshing (it's always one size of first opened image), but I have scrolsl and I am satisfied for now ;). Thanks a lot for everyone.
The problem comes because I overwrite the paintComponent method of a jPanel, so when I repaint all the objets are hidden till I focus them.
I need to overwrite the paintComponent method cause it's the only one answer I'd found in internet to change the background image of a jFrame.
So firstly I create a jPanel class:
public class JPanelFondoPrincipal extends javax.swing.JPanel {
public JPanelFondoPrincipal(){
this.setSize(800,500);
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Dimension tamanio = getSize();
ImageIcon imagenFondo = new ImageIcon(getClass().getResource("/images/fondo_principal.png"));
g.drawImage(imagenFondo.getImage(),0,0,tamanio.width, tamanio.height, null);
setOpaque(false);
}
}
And in my jPanelForm:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
JPanelFondo p = new JPanelFondo();
this.add(p);
validate();
p.repaint();
}
I'd already tried to add all my Objets (labels, textFields...) to a new Panel so I can add it after repaint, and set all the objets visibles manually but everything is still invisible.
Many thanks, I need to finish the app in 6 days and I'm getting crazy by the minute
EDIT: SOLVED THANKS TO CARDLAYOUT
don't add / remove JPanels or its contents on runtime, use CardLayout instead
your JPanelFondo p = new JPanelFondo(); doesn't corresponding somehow with public class JPanelFondoPrincipal extends javax.swing.JPanel {
for better help sooner edit your question with an SSCCE,
Swing programs should override paintComponent() instead of overriding paint().
http://java.sun.com/products/jfc/tsc/articles/painting/
And you should call super.paintComponent(g); first in overriden paintComponent();
public void paintComponent(Graphics g){
super.paintComponent(g);
Dimension tamanio = getSize();
ImageIcon imagenFondo = new ImageIcon(getClass().getResource("/images/fondo_principal.png"));
g.drawImage(imagenFondo.getImage(),0,0,tamanio.width, tamanio.height, null);
setOpaque(false);
}
Here's the proper way to handle painting onto JPanel component.