My custom component cannot be painted - java

I'm trying to create a class(called Stock) which can be identified as a Component--and let me use Listener on it.
However, it is not painted unless you specify (not a good idea!) to paint it in panel.paint().
The program runs as this:
JFrame frame = new JFrame ("..");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
final Stock theStock=new Stock();
JPanel primary = new JPanel();
primary.setPreferredSize(new Dimension(500,500));
primary.add(theStock);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
The Stock will not be painted unless primary(JPanel) is overriden so that there is a specification calling the stock to draw:
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.black);
g.drawRect(x-2, y-2, 74, 124);
}
Here's my code--I guess the problem may happen because I did not override anything else than paint method inherited from Component.
**********Modified to be testable, please see below**
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class Stock extends Component{
private int x; //the position for image
private int y;//position for image
public Stock() {
x=285;
y=280;
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.black);
g.drawRect(x-2, y-2, 74, 124);
}
public void works(){
JFrame frame = new JFrame ("..");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
final Stock theStock=new Stock();
JPanel primary = new JPanel(){
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
theStock.paint(g);
}
};
primary.setPreferredSize(new Dimension(500,500));
primary.add(theStock);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
public void doesNotWork(){
JFrame frame = new JFrame ("..");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
final Stock theStock=new Stock();
JPanel primary = new JPanel();
primary.setPreferredSize(new Dimension(500,500));
primary.add(theStock);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
Stock a = new Stock();
a.works();
//a.doesNotWork();
}
}
p.s.1. I'm not using JComponent because JComponent has more functionalities than I need to use. Component, as from which Container and Button inherit, should work well.
p.s.2. Even you use JComponent you get the same result. Code below.
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class Stock extends JComponent{
private int x; //the position for image
private int y;//position for image
public Stock() {
x=285;
y=280;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawRect(x-2, y-2, 74, 124);
}
public void works(){
JFrame frame = new JFrame ("..");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
final Stock theStock=new Stock();
JPanel primary = new JPanel(){
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
theStock.paint(g);
}
};
primary.setPreferredSize(new Dimension(500,500));
primary.add(theStock);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
public void doesNotWork(){
JFrame frame = new JFrame ("..");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
final Stock theStock=new Stock();
JPanel primary = new JPanel();
primary.setPreferredSize(new Dimension(500,500));
primary.add(theStock);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
Stock a = new Stock();
//a.works();
a.doesNotWork();
}
}

Your problem is one of layouts, size and preferredSize. Since you're adding a your Stock Component to a FlowLayout using JPanel, the Component will size itself at its preferred size which is 0, 0. If you gave the JPanel a different layout, say
primary.setLayout(new BorderLayout());
and then added your Stock object, it would fill the primary JPanel and it would paint itself.
Other options include setting your Stock objects preferredSize, or even overriding its getPreferredSize() method so that it's large enough:
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}

Related

Java&Swing: why the componenet isn't added dynamically?

The following is my code.
I think click the button, at least, a Color.CYAN block will be added into MainPanel, but it doesn't.
Could you please tell me how to achieve that? Thanks.
public class TestFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
final TestFrame mainFrame = new TestFrame();
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainFrame.setVisible(true);
});
}
public TestFrame() throws HeadlessException {
setTitle("Frame");
setSize(new Dimension(1000, 800));
final JPanel mainPanel = new JPanel();
final JButton button = new JButton("Test");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
mainPanel.add(new Unit());
}
});
mainPanel.add(button);
mainPanel.revalidate();
add(mainPanel);
}
class Unit extends JComponent {
public Unit() {
setSize(new Dimension(100, 100));
setBackground(Color.CYAN);
}
#Override
protected void paintComponent(Graphics g) {
final Graphics2D g2D = (Graphics2D) g;
g2D.drawString("Hello World", 10, 10);
}
}
}
Your Unit JComponent is likely being added to mainPanel in the ActionListener and thus the GUI, but it has no preferred size and so per the FlowLayout used by JPanels, it will size to [0, 0]. FlowLayouts (and most layout managers) do not respect a component's size but rather its preferredSize. Also, revalidate() and repaint() need to be called on the container (mainPanel) after Unit has been added so that the layout managers can do their laying out of components and to allow the OS to clear dirty pixels.
To solve this, give it a preferred size, preferably by overriding public Dimension getPreferredSize() but by calling setPreferredSize(...) if you must, and by calling revalidate() and repaint() after adding the component to the container.
Better still, add the component to the container using a CardLayout tutorial, but hide it by also adding an empty JLabel, again using a CardLayout, and then display the hidden component by calling CardLayout.show(...) from within ActionListener.
Side note: don't forget the super method within your painting method:
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // add this ****
final Graphics2D g2D = (Graphics2D) g;
g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2D.setFont(UNIT_FONT);
g2D.drawString("Hello World", textX, textY);
}
else you break the painting chain and may see unwanted artifacts or other problems
e.g.,
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestFrame extends JFrame {
private CardLayout cardLayout = new CardLayout();
private JPanel cardPanel = new JPanel(cardLayout);
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
final TestFrame mainFrame = new TestFrame();
mainFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
});
}
public TestFrame() throws HeadlessException {
setTitle("Frame");
setPreferredSize(new Dimension(1000, 800));
final JPanel mainPanel = new JPanel(new BorderLayout());
final JButton button = new JButton("Test");
button.addActionListener(e -> {
cardLayout.next(cardPanel);
});
JPanel btnPanel = new JPanel();
btnPanel.add(button);
mainPanel.add(btnPanel, BorderLayout.PAGE_END);
mainPanel.add(cardPanel);
add(mainPanel);
cardPanel.add(new JLabel(), "Foo");
cardPanel.add(new Unit(), Unit.class.getCanonicalName());
}
static class Unit extends JPanel {
private static final int PREF_W = 100;
private static final int PREF_H = 100;
private static final Font UNIT_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 60);
public Unit() {
setBackground(Color.CYAN);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
final Graphics2D g2D = (Graphics2D) g;
g2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2D.setFont(UNIT_FONT);
g2D.drawString("Hello World", 360, 350);
}
}
}

Painted component bigger than frame

I am using the same numbers to set the size of my frame as I am to paint the rectangle, yet the graphics are larger than my JFrame. Why is this?
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] arguments) {
Test test = new Test();
JFrame frame = new JFrame();
DrawPane contentPane = test.new DrawPane();
frame.setContentPane(contentPane);
frame.setSize(300, 400);
frame.setVisible(true);
}
private class DrawPane extends JPanel {
#Override
protected void paintComponent(Graphics g) {
g.setColor(Color.YELLOW);
g.fillRect(0, 0, 300, 400);
}
}
}
It's because of border. And it's a good example why you shouldn't explicitly determine size for your JFrame. Instead calling setSize override getPreferredSize method from your JPanel:
private class DrawPane extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.fillRect(0, 0, 300, 400);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
}
Then call pack for your JFrame instead setSize and your JFrame will adjust it's size according to its content.

Java - Graphics - adding another shape on JPanel

I've got a class that makes a JFrame and adds a panel on it
and the second one extends the JPanel and paints on it
The first one (JFrame)
class MyWindow {
void qwe() {
JFrame frame = new JFrame("qwe");
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
panel.setLayout(null);
frame.add(panel);}}
and the second one (JPanel)
class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
g.drawRect(50,50,90,70);
}
public void addShape() {
Graphics g = this.getGraphics();
Graphics2D gg = (Graphics2D) g;
gg.drawString("qwe",20,20);}}
how can i add a String on the JPanel by using the addShape() method ?
As a concrete example of #camickr's point, note that MyPanel already override's paintComponent(), so you can pass a reference to the Graphics context to addShape(). Additionally,
Be sure to invoke super.paintComponent(g).
Override getPreferredSize() to establish the component's preferred size.
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyWindow {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MyWindow().qwe();
}
});
}
void qwe() {
JFrame frame = new JFrame("qwe");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel panel = new MyPanel();
panel.setLayout(null);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class MyPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(50, 50, 90, 70);
addShape(g);
}
public void addShape(Graphics g) {
g.drawString("qwe", 20, 20);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
}
}
Don't use the getGraphics() method of your component to do custom painting. This type of painting is only temporary and will be lost the next time Swing determines the component needs to be painted.
Custom painting should always be done in the paintComponent() method of your component.
See Custom Painting Approaches for the two commons was to do what you want.

Drawing rectangles on a JPanel

I have a JScrollPane and on top of it I have a JPanel named 'panel1'.
I want some rectangles to be drawn on this JPanel.
I have a class named DrawRectPanel which extends JPanel and does all the drawing stuff.
The problem is that, I tried to draw the rectangles on panel1 by writing the following code :
panel1.add(new DrawRectPanel());
but nothing appeared on panel1
then I tried, just as a test to the class DrawRectPanel :
JFrame frame = new JFrame();
frame.setSize(1000, 500);
Container contentPane = frame.getContentPane();
contentPane.add(new DrawRectPanel());
frame.show();
This worked, and produced the drawings but on a separate JFrame
How can I draw the rectangles on panel1 ?
Thanks in advance.
EDIT :
code for DrawRectPanel
public class DrawRectPanel extends JPanel {
DrawRectPanel() {
Dimension g = new Dimension(400,400);
this.setPreferredSize(g);
System.out.println("label 1");
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("label 2");
g.setColor(Color.red);
g.fillRect(20, 10, 80, 30);
}
}
only label 1 is printed on the screen
still no idea,
for example
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class CustomComponent extends JFrame {
private static final long serialVersionUID = 1L;
public CustomComponent() {
setTitle("Custom Component Graphics2D");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void display() {
add(new CustomComponents());
pack();
// enforces the minimum size of both frame and component
setMinimumSize(getSize());
setVisible(true);
}
public static void main(String[] args) {
CustomComponent main = new CustomComponent();
main.display();
}
}
class CustomComponents extends JComponent {
private static final long serialVersionUID = 1L;
#Override
public Dimension getMinimumSize() {
return new Dimension(100, 100);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
#Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
instead of adding
contentPane.add(new DrawRectPanel());
you should do
contentPane.add(panel1);
Because you already have new DrawRectPanel in panel1. But in your code you are adding another instance of DrawRectPanel in contentPane. And never added panel1 in none of your container.
to fix your problem, change "paintComponent" to "paint" when the window repaints automatically, it should work.

Why does setting the layout to BorderLayout mean the paintComponent is never called

In the following example program, if you set useBorderlayout to true, the paintComponent method is never called - why?!
import javax.swing.*;
import java.awt.*;
public class PaintComponentTest extends JPanel {
private final boolean useBorderLayout;
public PaintComponentTest(boolean useBorderLayout){
this.useBorderLayout = useBorderLayout;
initialiseComponents();
}
public void initialiseComponents(){
setOpaque(true);
setBackground(Color.RED);
if(useBorderLayout){
//this appears to be the offending line:
setLayout(new BorderLayout());
}
final JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.GREEN);
add(panel, BorderLayout.CENTER);
}
#Override
public void paintComponent(Graphics g){
System.out.println("PaintComponentTest.paintComponent");
super.paintComponent(g);
}
public static void main(String [] args){
final boolean useBorderLayout = (args.length == 1 && Boolean.parseBoolean(args[0]));
System.out.println("Running with"+(useBorderLayout?"":"out")+" BorderLayout as layout manager...");
SwingUtilities.invokeLater(new Runnable(){
public void run(){
final JFrame frame = new JFrame("BorderLayout/PaintComponent test");
frame.setPreferredSize(new Dimension(200, 200));
frame.getContentPane().setLayout(new BorderLayout());
final PaintComponentTest componentTest = new PaintComponentTest(useBorderLayout);
frame.getContentPane().add(componentTest);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
Because it doesn't need to. The PaintComponentTest class is a JPanel that has one green JPanel as content. When the BorderLayout is set, the green panel takes up all the space in panel and the PaintComponent method is not needed.
Add this method to your code and you should see it happen:
#Override
public void paintChildren(Graphics g){
System.out.println("PaintComponentTest.paintChildren");
super.paintChildren(g);
}
Because the nested panel covers all the component. Damaged region (to be repainted) is past to the children because the child bounds cover all the damaged region.

Categories

Resources