java statusbar resize corner (handle) - java

I try to make a window with a resize handle at the bottom right.
So far I managed to detect the mouse hover and dragging.
The mouse cursor is changing to resize cursor successfully.
But the actually resize operation I'm unsure how to solve.
The Idea I testet at first place is to just setsize on parent when dragging on resize handle.
It works, but then the window get's resize immediately, that's not how the standard resize looks.
The standard resize is a transparent window with white border (may be different on different systems and look and feel).
Is it possible to trigger/use the built in resize mechanism?
Below you have a sample code.
Thanks!
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class main extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
main frame = new main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public class StatusBar extends JPanel implements MouseListener, MouseMotionListener {
private Polygon resizeCorner = new Polygon();
private int offsetX;
private int offsetY;
private Dimension offsetSize;
private Cursor resizeCursor = new Cursor(Cursor.SE_RESIZE_CURSOR);
private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR);
public StatusBar() {
super();
setPreferredSize(new Dimension(200,40));
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
private void createResizeHandle() {
resizeCorner.reset();
resizeCorner.addPoint(getWidth()-2, getHeight()-2);
resizeCorner.addPoint(getWidth()-40, getHeight()-2);
resizeCorner.addPoint(getWidth()-2, getHeight()-40);
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2;
g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2.setColor(Color.red);
createResizeHandle();
g2.drawPolygon(resizeCorner);
}
#Override
public void mouseDragged(MouseEvent e) {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
int width = (int) (this.offsetSize.getWidth() - this.offsetX + e.getXOnScreen());
int height = (int) (this.offsetSize.getHeight() - this.offsetY + e.getYOnScreen());
this.getRootPane().getParent().setSize(width, height);
createResizeHandle();
}
}
#Override
public void mouseMoved(MouseEvent e) {
if (resizeCorner.contains(e.getX(), e.getY())) {
setCursor(resizeCursor);
} else {
setCursor(defaultCursor);
}
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent e) {
if (resizeCorner.contains(e.getX(), e.getY())) {
this.offsetX = e.getXOnScreen();
this.offsetY = e.getYOnScreen();
this.offsetSize = this.getRootPane().getParent().getSize();
}
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
public main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JLabel lblNewLabel = new JLabel("New label");
StatusBar bar = new StatusBar();
contentPane.add(lblNewLabel, BorderLayout.NORTH);
contentPane.add(bar, BorderLayout.SOUTH);
}
}

lots of small mistakes, starts with correct naming for ClassName ... end with usage java reserved words for class/void/method's name(s)
minor changes (now it works for me), with one my mistake against Swing rules, I set there setPreferredSize(new Dimension(400, 300));, lets childrens returns PreferredSize for Container
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class MyToolBar extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public class StatusBarX extends JPanel implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;
private Polygon resizeCorner = new Polygon();
private int offsetX;
private int offsetY;
private Dimension offsetSize;
private Cursor resizeCursor = new Cursor(Cursor.SE_RESIZE_CURSOR);
private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR);
public StatusBarX() {
super();
setPreferredSize(new Dimension(200, 40));
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
private void createResizeHandle() {
resizeCorner.reset();
resizeCorner.addPoint(getWidth() - 2, getHeight() - 2);
resizeCorner.addPoint(getWidth() - 40, getHeight() - 2);
resizeCorner.addPoint(getWidth() - 2, getHeight() - 40);
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2;
g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setColor(Color.red);
createResizeHandle();
g2.drawPolygon(resizeCorner);
}
#Override
public void mouseDragged(MouseEvent e) {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
int width = (int) (this.offsetSize.getWidth() - this.offsetX + e.getXOnScreen());
int height = (int) (this.offsetSize.getHeight() - this.offsetY + e.getYOnScreen());
this.getRootPane().getParent().setSize(width, height);
createResizeHandle();
}
}
#Override
public void mouseMoved(MouseEvent e) {
if (resizeCorner.contains(e.getX(), e.getY())) {
setCursor(resizeCursor);
} else {
setCursor(defaultCursor);
}
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent e) {
if (resizeCorner.contains(e.getX(), e.getY())) {
this.offsetX = e.getXOnScreen();
this.offsetY = e.getYOnScreen();
this.offsetSize = this.getRootPane().getParent().getSize();
}
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
public MyToolBar() {
JLabel lblNewLabel = new JLabel("New label");
StatusBarX bar = new StatusBarX();
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
contentPane.add(lblNewLabel, BorderLayout.NORTH);
contentPane.add(bar, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(100, 100);
setPreferredSize(new Dimension(400, 300));
add(contentPane);
pack();
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
MyToolBar frame = new MyToolBar();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}

The standard resize is a transparent window with white border (may be different on different systems and look and feel).
When using Windows XP the standard is to resize top level components (frame, dialog etc) immediately. It doesn't matter what the LAF is.
In general other components don't have resizing functionality built in. The only exception to this that I can think of is JInternalFrame. In this case is does support the "outline" resizing of a component.
So if you want to add this type of functionality to your component then you would need to look at the internal frame UI to find the resizing code.
I would guess that the code would display a Glass Pane when dragging starts and then do the outline custom painting on the Glass Plane. Then on mouseReleased the frame size would be changed.
In case you are interested, Component Resizing shows how I do resizing for any component. It does immediate resizing, not outline resizing.

Related

Is there a way to move mouse coordinates to the title of the JFrame?

Got method paint() to draw mouse coordinates in JFrame in coordinates x=20, y=20. Is there a way to move rendering mouse coordinates to the title of the JFrame? Try to use jFrame.setTitle() but it want String as parametr.
jFrame.setTitle(g.drawString("Coordinates x:" + xCord + " y" + yCord, 20, 20)) not work.
Here is my code:
private static void paint() {
JComponent jComponent = new JComponent() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Font font = new Font("Comic Sans MS", Font.BOLD, 20);
g.setFont(font);
g.drawString("Coordinates x:" + xCord + " y" + yCord, 20, 20);
}
};
jFrame.add(jComponent);
jFrame.addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
xCord = e.getX();
yCord = e.getY();
jComponent.repaint();
}
});
}
Here's a simple example of a GUI that updates the title of the JFrame.
I just updated the title String with the coordinates from the mouseMoved method of the MouseMOtionListener.
Here's the runnable, contained, example.
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MouseCoordinatesTitle implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new MouseCoordinatesTitle());
}
private JFrame frame;
private String title;
public MouseCoordinatesTitle() {
this.title = "Coordinates: ";
}
#Override
public void run() {
frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(600, 400));
panel.addMouseMotionListener(new PositionListener());
return panel;
}
public void updateJFrameTitle(Point point) {
StringBuilder builder = new StringBuilder(title);
builder.append("X: ");
builder.append(point.x);
builder.append(", Y: ");
builder.append(point.y);
frame.setTitle(builder.toString());
}
public class PositionListener implements MouseMotionListener {
#Override
public void mouseMoved(MouseEvent event) {
Point point = event.getPoint();
updateJFrameTitle(point);
}
#Override
public void mouseDragged(MouseEvent event) {
}
}
}

custom JPanel not updating

the code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PaintWindow {
private JFrame frame;
private aJPanel panel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PaintWindow window = new PaintWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PaintWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new aJPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.stam();
}
});
frame.getContentPane().add(btnNewButton, BorderLayout.NORTH);
frame.setBounds(100, 100, 450, 300);
frame.setVisible(true);
}
public class aJPanel extends JPanel {
private static final long serialVersionUID = 8874943072526915834L;
private Graphics g;
public aJPanel() {
super();
System.out.println("Constructor");
}
public void paint(Graphics g) {
super.paint(g);
System.out.println("paint");
g.fillRect(10, 10, 10, 10);
this.g = g;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("paintComponent");
g.fillRect(20, 20, 20, 20);
this.g = g;
}
public void stam() {
System.out.println("stam");
this.g.fillRect(40, 40, 40, 40);
this.repaint();
}
}
}
what I want to do is paint custom shapes (lines, rectangles etc) after the user clicks a button or triggers a mouse event. but calling aJPanel.stam() does not show the rectangle its supposed to. I am fairly new to JPanel. any suggestions?
First of all:
class names should start with a capital letter
class names should be descriptive.
"aJPanel" does not follow either of the above.
but calling aJPanel.stam() does not show the rectangle its supposed to
See Custom Painting Apporoaches for the two common ways to do dynamic painting:
Add objects to a List and iterate the List to paint all the objects
Paint directly to a BufferedImage and then paint the BufferedImage
The examples add the Rectangle by dragging the mouse, but you can easily add Rectangles by just invoking the addRectangle(...) method when you click a button.

Java - Creating PNG/Textlogo and drawing it to JFrame

I'm trying to print a string that the user can enter to a textbox, to a JFrame.
My problem is that the paintComponent method is never being called. Why?
PNGCreatorWindow Class:
public class PNGCreatorWindow {
private JFrame frame;
private JTextField txtText;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PNGCreatorWindow window = new PNGCreatorWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PNGCreatorWindow() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 678, 502);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txtText = new JTextField();
txtText.setBounds(121, 13, 216, 22);
frame.getContentPane().add(txtText);
txtText.setColumns(10);
JButton btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnGenerate.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
GeneratePNGImage();
}
});
btnGenerate.setBounds(436, 6, 183, 36);
frame.getContentPane().add(btnGenerate);
JPanel panel = new JPanel();
panel.setBounds(107, 151, 338, 160);
frame.getContentPane().add(panel);
}
protected void GeneratePNGImage() {
PNGImage img = new PNGImage(txtText.getText());
frame.getContentPane().add(img);
frame.getContentPane().validate();
frame.getContentPane().setVisible(true);
frame.repaint();
}
}
PNGImage Class:
public class PNGImage extends JComponent {
private String text;
public PNGImage(String text){
this.text = text;
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.red);
g2.drawString(this.text, 100,100);
g2.fillRect(50, 50, 1000, 1000);
}
}
I made a few changes to your code to get it to draw the text on the JPanel.
I put the JTextField and the JButton inside of a control panel (JPanel) and set a layout manager (FlowLayout) for the control panel. You should always use a layout manager for laying out Swing components.
I defined the image panel (PNGImage) as part of the laying out of the Swing components. First, you lay all of the Swing components out. Then, you change their state.
I removed the mouse adapter and just used an action listener on the JButton. The action listener works with the mouse.
In the PNGImage class, I added a setter, so I could pass the text to the class later, after the user typed the text in the JTextField.
I added a call to setPreferredSize so that I could set the size of the drawing canvas. I removed all other sizing, and used the pack method of JFrame to make the JFrame the appropriate size to hold the Swing components.
I added a null test to paintComponent, so that the text would only be drawn when there was some text to draw.
Here's the code. I put all the code in one module to make it easier to paste.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class PNGCreatorWindow {
private JFrame frame;
private JTextField txtText;
private PNGImage imagePanel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new PNGCreatorWindow();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PNGCreatorWindow() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
txtText = new JTextField(10);
controlPanel.add(txtText);
JButton btnGenerate = new JButton("Generate");
btnGenerate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
generatePNGImage();
}
});
controlPanel.add(btnGenerate);
imagePanel = new PNGImage();
frame.getContentPane().add(controlPanel, BorderLayout.NORTH);
frame.getContentPane().add(imagePanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
protected void generatePNGImage() {
imagePanel.setText(txtText.getText());
imagePanel.repaint();
}
public class PNGImage extends JPanel {
private static final long serialVersionUID = 602718701626241645L;
private String text;
public PNGImage() {
setPreferredSize(new Dimension(400, 300));
}
public void setText(String text) {
this.text = text;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (this.text != null) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.drawString(this.text, 100, 100);
}
}
}
}
Edited to add an action listener that saves the contents of a JPanel as a .png file:
package com.ggl.crossword.controller;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import com.ggl.crossword.view.CrosswordFrame;
public class CreateImageActionListener implements ActionListener {
private CrosswordFrame frame;
private JPanel panel;
public CreateImageActionListener(CrosswordFrame frame,
JPanel panel) {
this.frame = frame;
this.panel = panel;
}
#Override
public void actionPerformed(ActionEvent event) {
writeImage();
}
public void writeImage() {
FileFilter filter =
new FileNameExtensionFilter("PNG file", "png");
JFileChooser fc = new JFileChooser();
fc.setFileFilter(filter);
int returnValue = fc.showSaveDialog(frame.getFrame());
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (!file.getAbsolutePath().endsWith(".png")) {
file = new File(file.getAbsolutePath() + ".png");
}
RenderedImage image = createImage(panel);
try {
ImageIO.write(image, "png", file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private BufferedImage createImage(JPanel panel) {
int w = panel.getWidth();
int h = panel.getHeight();
BufferedImage bi = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
panel.paint(g);
g.dispose();
return bi;
}
}

move image from one panel to another

I have Code where I can move image.
Everything works well.
here I have only one ImagePanel (children of JPanel) on the frame.
Questions:
I need to drag and drop image from one JPanel to another JPanel.
Then I need to move dragged image to current panel.
Can you give me an example code, please?
class ImagePanel extends JPanel {
int x, y;
BufferedImage image;
ImagePanel() {
setBackground(Color.white);
setSize(450, 400);
addMouseMotionListener(new MouseMotionHandler());
Image img = getToolkit().getImage("C:\\2.png");
MediaTracker mt = new MediaTracker(this);
mt.addImage(img, 1);
try {
mt.waitForAll();
} catch (Exception e) {
System.out.println("Image not found.");
}
image = new BufferedImage(img.getWidth(this), img.getHeight(this),BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
g2.drawImage(img, 0, 0, this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(image, x, y, this);
}
class MouseMotionHandler extends MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
public void mouseMoved(MouseEvent e) {
}
}
}
I need to do that code, with this following design. I need to add image with some layout (I don't need to done this with Point pixels). or how to add image with some layout? for example Grid bag layout. I don't need Points (x,y). because I need to add another components too.
public class DragAndDrop {
private JFrame frame;
/* .. another component here .. */
private JPanel leftPanel; // here is my image
public JPanel rightContentPanel; // destination of dragable image
public static void main(String[] args) {
DragAndDrop window = new DragAndDrop();
}
public DragAndDrop() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout(0, 0));
leftPanel = new leftPanel();
/* add components to left panel */
rightContentPanel = new rightPanel();
/* add component to right panel */
frame.getContentPane().add(rightContentPanel, BorderLayout.CENTER);
frame.getContentPane().add(leftPanel, BorderLayout.WEST);
frame.setVisible(true);
frame.setResizable(false);
}
}
class leftPanel extends JPanel {
/ ... /
}
class rightPanel extends JPanel{
/ ... /
}
There's probably any number of ways to achieve what you want. You could use the glass pane or JXLayer or you could stop treating the two panels as separate elements and more like they were just windows into a large virtual space.
This example basically treats the parent component as the "virtual space" into which the two image panes are windows.
They both share the same image and image location details. They, individual, convert the image location (which is in virtual coordinates) to local coordinates and draw as much of the image as would appear on them...
Mouse control is maintained by the parent. This greatly simplifies the process, as it can notify both the panels simultaneously
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class CrossImage {
public static void main(String[] args) {
new CrossImage();
}
public CrossImage() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
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 BufferedImage img;
private ImagePane left;
private ImagePane right;
private Point imagePoint;
public TestPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridLayout(0, 2, 10, 10));
left = new ImagePane();
right = new ImagePane();
imagePoint = new Point(10, 10);
left.setImageLocation(imagePoint);
right.setImageLocation(imagePoint);
try {
img = ImageIO.read(new File("Background.jpg"));
left.setImage(img);
right.setImage(img);
} catch (IOException ex) {
ex.printStackTrace();
}
add(left);
add(right);
MouseAdapter mouseHandler = new MouseAdapter() {
private Point delta;
#Override
public void mousePressed(MouseEvent e) {
Point origin = e.getPoint();
Rectangle bounds = new Rectangle(imagePoint, new Dimension(img.getWidth(), img.getHeight()));
if (bounds.contains(origin)) {
delta = new Point(origin.x - imagePoint.x, origin.y - imagePoint.y);
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (delta != null) {
imagePoint = e.getPoint();
imagePoint.translate(-delta.x, -delta.y);
left.setImageLocation(imagePoint);
right.setImageLocation(imagePoint);
}
}
#Override
public void mouseReleased(MouseEvent e) {
delta = null;
}
};
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
}
}
public class ImagePane extends JPanel {
private Image image;
private Point imageLocation;
public ImagePane() {
setBorder(new LineBorder(Color.DARK_GRAY));
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(this), image.getHeight(this));
}
public void setImage(Image image) {
this.image = image;
repaint();
}
public void setImageLocation(Point imageLocation) {
this.imageLocation = imageLocation;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null && imageLocation != null) {
Point p = SwingUtilities.convertPoint(getParent(), imageLocation, this);
g.drawImage(image, p.x, p.y, this);
}
}
}
}

paint method is not being called

I don't know why, but I can't call the method paint(Graphics g) from code. I have MouseListeners:
#Override
public void mouseReleased(MouseEvent e) {
pointstart = null;
}
#Override
public void mousePressed(MouseEvent e) {
pointstart = e.getPoint();
}
and MouseMotionListeners:
#Override
public void mouseMoved(MouseEvent e) {
pointend = e.getPoint();
}
#Override
public void mouseDragged(MouseEvent arg0) {
pointend = arg0.getPoint();
// ==========================================================================
// call repaint:
repaint();
// ==========================================================================
}
and my paint method:
public void paint(Graphics g){
super.paint(g); //here I have my breakpoint in debugger
g.translate(currentx, currenty);
if(pointstart!=null){
g.setClip(chartPanel.getBounds());
g.setColor(Color.BLACK);
g.drawLine(pointstart.x, pointstart.y, pointend.x, pointend.y);
}
}
in the initialize method:
currentx = chartPanel.getLocationOnScreen().x;
currenty = Math.abs(chartPanel.getLocationOnScreen().y - frame.getLocationOnScreen().y);
All in class, which is my work frame, it extends JFrame.
Problem is, that program doesn't call paint method. I checked that in debugger.
I tried do this by paintComponent , without super.paint(g).
And the best is that, that code I copied from my other project, where it works fine.
UPDATE:
This is code which I want to draw line on panel (no matter - panel/chartpanel/etc). And it doesn't paint. I tried do this by paint(Graphics g){super.paint(g) ..... } and it doesn't too. Painting should be aneble after clicking button "line".
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class Window extends JFrame {
private JFrame frame;
public JPanel panelbuttons;
public JPanel panelscrollpane;
public JButton btnLine;
public JToolBar toolBar;
public JScrollPane scrollPane;
public JPanel panel;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Window() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 644, 430);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panelbuttons = new JPanel();
frame.getContentPane().add(panelbuttons, BorderLayout.WEST);
panelbuttons.setLayout(new BorderLayout(0, 0));
toolBar = new JToolBar();
toolBar.setOrientation(SwingConstants.VERTICAL);
panelbuttons.add(toolBar, BorderLayout.WEST);
btnLine = new JButton("line");
btnLine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.addMouseListener(mouselistenerLine);
panel.addMouseMotionListener(mousemotionlistenerLine);
}
});
toolBar.add(btnLine);
panelscrollpane = new JPanel();
frame.getContentPane().add(panelscrollpane, BorderLayout.CENTER);
panelscrollpane.setLayout(new BorderLayout(0, 0));
scrollPane = new JScrollPane(panel);
panel.setLayout(new BorderLayout(0, 0));
scrollPane.setViewportBorder(null);
panelscrollpane.add(scrollPane);
panelscrollpane.revalidate();
}
Point pointstart = null;
Point pointend = null;
private MouseListener mouselistenerLine = new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
System.out.println("I'm in first listener. - mouse Released");
pointstart = null;
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println("I'm in first listener. - mousePressed");
pointstart = e.getPoint();
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
};
private MouseMotionListener mousemotionlistenerLine = new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent e) {
System.out.println("I'm in second listener. - mouseMoved");
pointend = e.getPoint();
}
#Override
public void mouseDragged(MouseEvent arg0) {
System.out.println("I'm in second listener. - mouseDragged");
pointend = arg0.getPoint();
repaint();
}
};
public void paintComponent(Graphics g){
System.out.println("I'm in paintComponent method.");
if(pointstart!=null){
System.out.println("I'm drawing.");
g.setClip(scrollPane.getBounds());
g.setColor(Color.BLACK);
g.drawLine(pointstart.x, pointstart.y, pointend.x, pointend.y);
}
}
}
You are creating two separate instances of JFrame and showing only one.
One instance is created because Window class extends JFrame, and the second is created inside initialize method.
To fix this without a lot of changes in code do this:
private void initialize() {
frame = this;
frame.setBounds(100, 100, 644, 430);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BTW. change paintComponent(Graphic g) to paint(Graphic g) because JFrame is not a JComponent.
In a ChartPanel context, consider one of the org.jfree.chart.annotations such as XYLineAnnotation, illustrated here and here.
Calling repaint() will trigger your paint(Graphics g) method to be called. So, you don't have to explicitly call paint().

Categories