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().
Related
I am trying to make a drawOval moving by using the two buttons that I set to be North and East so the ball will move between the JButtons, at the center.
Why does not appear at the panel?
Also I am thinking using a function that make this x=x+; and y=y+1 when I pressed left or right.
I do not figure out what can I do.
So this is the code I made:
public class Main extends JFrame implements ActionListener {
JButton left;
JButton right;
JPanel p;
Main(){
JButton left = new JButton("left");
left.addActionListener(this);
left.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
//The first way I think is better to make it move.
}
});
JButton right = new JButton("right");
right.addActionListener(this);
Panel p = new Panel();
p.setLayout(new BorderLayout());
p.add("West",left);// to the left
p.add("East",right);//to the right
Container c = getContentPane();
c.add(p);
}
public static void main(String[] args) {
Main f=new Main();
f.setTitle("Heracles");
f.setSize(500, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true); //this is the window
}
public void paintComponent (Graphics g) {
super.paintComponents(g);
Graphics2D g1=(Graphics2D) g;
g.drawOval(3, 5, 45, 46); // The ball
g.fillOval(20, 30, 40, 40);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
To understand why it's not working, you need to understand how the paint system actually works
Just by looking at this snippet it should be obvious something is wrong.
public class Main extends JFrame implements ActionListener {
//...
public void paintComponent (Graphics g) {
super.paintComponents(g);
//...
}
}
You've declare a method called paintComponent but are calling the super method paintComponents (note the s at the end).
Further, when ever you "think" you're overriding a method, you should make use of the #Override attribute, this will cause a compiler error when you've done something wrong
public class Main extends JFrame implements ActionListener {
//...
#Overrride
public void paintComponent (Graphics g) {
super.paintComponents(g);
//...
}
}
The above code will now fail to compile, as JFrame doesn't declare a paintComponent method.
As a general rule, you should avoid extending directly from JFrame (or other top level containers), they are compound components and have a complex hierarchy and functionality.
A better place to start might be with a JPanel
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
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.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
JButton left;
JButton right;
JPanel paintPane;
public TestPane() {
JButton left = new JButton("left");
left.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
}
});
JButton right = new JButton("right");
right.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
paintPane = new PaintPane();
setLayout(new BorderLayout());
add(left, BorderLayout.WEST);
add(right, BorderLayout.EAST);
add(paintPane);
}
}
public class PaintPane extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g1 = (Graphics2D) g;
g1.drawOval(3, 5, 45, 46); // The ball
g1.fillOval(20, 30, 40, 40);
}
}
}
You should take the time to have a look at Painting in Swing and Performing Custom Painting for more details.
Some other concepts you might like to take the time to learn:
Single Responsibility Principle - a class should do one thing and do it well
Observer Pattern - This typically represent in Swing as the listener API
Model-View-Controller - this encompasses the above and defines different layers of responsibility for different parts of the program, it will helper you understand the basic structure of Swing as well
Also I am thinking using a function that make this x=x+; and y=y+1 when I pressed left or right.
Ok, so this is where the "model" part of the MVC will play it's part.
So lets start by defining the basic properties we expect the model to support...
public interface ShapeModel {
public Point getPoint();
public void addChangeListener(ChangeListener listener);
public void removeChangeListener(ChangeListener listener);
}
Here is supports a Point to act as the location and a ChangeListener to act as the observer pattern, which will notify interested parties that the state of the model has changed.
Why start with a interface? As a general concept, you should always prefer to code to interface instead of implementation. In this case, one aspect of the interface which hasn't been defined is, how does the Point get updated? That's of little interest to most parties who want to work with the model, they just want to know when it changes, the mutation of the model can be expressed either directly via the implementation or a "mutable" interface which extends from the this interface
Next, we define a default implementation...
public class DefaultShapeModel implements ShapeModel {
private Point point = new Point(40, 40);
private List<ChangeListener> listeners = new ArrayList<>(25);
#Override
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
fireStateChanged();
}
protected void fireStateChanged() {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
#Override
public void addChangeListener(ChangeListener listener) {
listeners.add(listener);
}
#Override
public void removeChangeListener(ChangeListener listener) {
listeners.remove(listener);
}
}
This does define how the paint is to be updated.
Finally, we update the TestPane and PaintPane to support the model...
public class TestPane extends JPanel {
JButton left;
JButton right;
JPanel paintPane;
private DefaultShapeModel model;
public TestPane() {
model = new DefaultShapeModel();
JButton left = new JButton("left");
left.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
Point p = model.getPoint();
p.x--;
if (p.x > 0) {
p.x = 0;
}
model.setPoint(p);
}
});
JButton right = new JButton("right");
right.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Point p = model.getPoint();
p.x++;
if (p.x + 40 > paintPane.getWidth()) {
p.x = paintPane.getWidth() - 40;
}
model.setPoint(p);
}
});
paintPane = new PaintPane(model);
setLayout(new BorderLayout());
add(left, BorderLayout.WEST);
add(right, BorderLayout.EAST);
add(paintPane);
}
}
public class PaintPane extends JPanel {
private ShapeModel model;
public PaintPane(ShapeModel model) {
this.model = model;
this.model.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
repaint();
}
});
}
public ShapeModel getModel() {
return model;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void paintComponent(Graphics g) {
super.paintComponents(g);
Graphics2D g1 = (Graphics2D) g;
Point p = getModel().getPoint();
g1.fillOval(p.x, p.y, 40, 40);
g1.setColor(Color.WHITE);
g1.drawOval(p.x, p.y, 40, 40);
}
}
Why does not appear at the panel?
To display graphic you created, use follow these steps,
Remove paintComponent method and replace it with below code..
public JComponent createOvel() {
return new JComponent() {
#Override
protected void paintComponent(Graphics g) {
Graphics2D g1 = (Graphics2D) g;
g.drawOval(3, 5, 45, 46); // The ball
g.fillOval(20, 30, 40, 40);
}
};
}
Then call it in Main() constructor,
p.add("Center", createOvel());
This will display the graphic you created.
I have added a keylistener to try and get a shape to move right when I press the right arrow key. But it isn't working. I don't really know how to use keylistner that well. Can someone help me.
This is the code:
package walkingman;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class WalkingMan extends JPanel implements KeyListener{
int x = 0;
int y = 0;
#Override
public void paint(Graphics g){
super.paint(g);
g.fillOval(x, y, 150, 150);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame ("Walking Man");
frame.setSize(1080,720);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
WalkingMan game = new WalkingMan();
frame.add(game);
while (true){
game.repaint();
game.keyPressed(e);
}
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
x++;
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
}
There are a few issues with your code
You never add the KeyListener to the panel.
A KeyListener for a JPanel would only work if it is focusable & also focused.
Override paintComponent instead of paint.
Call setVisible at the end of the method.
Get rid of the whole while-loop, it'll only cause problems.
Use KeyBindings instead of KeyListeners.
Fixed code without key bindings:
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class WalkingMan extends JPanel implements KeyListener {
int x = 0;
int y = 0;
#Override
public void paintComponent(Graphics g) { // Overide paintComponent, not paint
super.paintComponent(g);
g.fillOval(x, y, 150, 150);
}
public WalkingMan() { // Class Constructor
setFocusable(true); // KeyListeners only work if the component is focusable
addKeyListener(this); // Add the KeyListener implemented by this class to the instance
}
public void createAndShowGUI() {
JFrame frame = new JFrame("Walking Man");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
WalkingMan game = new WalkingMan();
frame.add(game);
frame.setSize(1080, 720);
frame.setVisible(true); // Call setVisible after adding the components
game.requestFocusInWindow(); // Request focus for the panel
}
public static void main(String[] args) throws InterruptedException {
new WalkingMan().createAndShowGUI();
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
x++;
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
}
Set frame well before it is displayed And remove the while loop which is still running.
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame ("Walking Man");
frame.setSize(1080,720);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
WalkingMan game = new WalkingMan();
frame.add(game);
frame.setVisible(true);//Call visible method here
}
Why not restructure your code in a much clear way like this
import javax.swing.*;
import java.awt.*;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class WalkingMan extends JFrame{
EmilsKeyClass keyBoard = new EmilsKeyClass();
public WalkingMan (){
add(keyBoard,BorderLayout.CENTER);
keyBoard.addKeyListener(new KeyAdapter(){
#Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode()== KeyEvent.VK_ENTER){
x++;
repaint();
}
}
});
keyBoard.setFocusable(true);
}
public static void main(String [] args){
WalkingMan frame = new WalkingMan ();
frame.setTitle("Walking Man");
frame.setSize(1080,720);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class EmilsKeyClass extends JPanel{
int x = 0;
int y = 0;
public EmilsKeyClass(){
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
super.paint(g);
g.fillOval(x, y, 150, 150);
//your code
}
}
}
Hey I am trying to make a basic launcher and for the design I got an image. I want to make the exit button to be shown over the launcher image so you can see it. I dont know how I do it so I need help with it. Here is my code:
package launcher;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
/**
*
* #author Daniel <Skype: daniel.gusdal>
*
* Current Date: 2. feb. 2014 Current Time: 21:46:52
* Project: 742 client. File Name: Launcher.java
*
*/
public class Launcher extends JFrame {
/**
* Generated serialVersionUID
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
static Point mouseDownCompCoords;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mouseDownCompCoords = null;
final Launcher frame = new Launcher();
frame.setResizable(true);
frame.setUndecorated(true);
frame.setBackground(new Color(0, 255, 0, 0));
frame.setVisible(true);
frame.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {
mouseDownCompCoords = null;
}
public void mousePressed(MouseEvent e) {
mouseDownCompCoords = e.getPoint();
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
});
frame.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
Point currCoords = e.getLocationOnScreen();
frame.setLocation(currCoords.x
- mouseDownCompCoords.x, currCoords.y
- mouseDownCompCoords.y);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Launcher() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 841, 593);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel Design = new JLabel("New label");
Design.setIcon(new ImageIcon(getClass().getResource("Launcher3.png")));
Design.setBounds(-158, -22, 1047, 592);
contentPane.add(Design);
ImageIcon img = new ImageIcon(getClass().getResource(
"Playnow.png"));
final JButton Playnow = new JButton(img);
Playnow.setBackground(null);
Playnow.setOpaque(false);
Playnow.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
Playnow.setIcon(new ImageIcon(getClass().getResource(
"PlaynowHover.png")));
}
#Override
public void mouseClicked(MouseEvent e) {
Playnow.setIcon(new ImageIcon(getClass().getResource(
"PlaynowHover.png")));
System.out.println(Playnow.getIcon());
}
#Override
public void mouseExited(MouseEvent e) {
Playnow.setIcon(new ImageIcon(getClass().getResource(
"Playnow.png")));
}
});
Playnow.setBounds(258, 442, 301, 46);
contentPane.add(Playnow);
final JButton Exit = new JButton();
Exit.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(Exit.getIcon());
System.exit(0);
}
});
Exit.setIcon(new ImageIcon(Launcher.class.getResource("Exit.png")));
Exit.setOpaque(false);
Exit.setBounds(766, 59, 21, 21);
contentPane.add(Exit);
}
}
Don't set bounds. Learn to use Layout Managers.
Paint the image on a JPanel instead of using a JLabel
Put the JButton on the JPanel. Give that JPanel a GridBadLayout
Override the getPreferredSize() of the JPanel.
To switch between images you can use a flag like boolean icon1, icon2, icon3;. and repaint the JPanel the mouseXxx. Something like this
public void mouseClicked(MouseEvent e) {
icon1 = true;
icon2 = false;
icon3 = false;
imagePanel.repaint();
}
....
protected void paintComponent(Graphics g) {
if (icon1) {
g.drawImage(image1, .....);
}
if (icon2) { ... }
if (icon3) { ... }
}
pack() your frame.
Use Java naming convention. variables start with lower case letters.
Here's an example
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.*;
import java.util.logging.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class TestButtonOverImage {
public TestButtonOverImage() {
JFrame frame = new JFrame("Test Card");
frame.add(new ImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestButtonOverImage();
}
});
}
public class ImagePanel extends JPanel {
BufferedImage img;
public ImagePanel() {
setLayout(new GridBagLayout());
add(new JButton("StackOverflow Button"));
try {
img = ImageIO.read(new URL("http://d8u1nmttd4enu.cloudfront.net/designs/logo-stackoverflow-logo-design-99designs_447080~36d200d82d83d7b2e738cebd2a48de07180cef3a_largecrop"));
} catch (MalformedURLException ex) {
Logger.getLogger(TestButtonOverImage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TestButtonOverImage.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 100, 100, 300, 300, this);
}
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
}
}
I making a Java Applet that save on an image what user paint in a JPanel. When i save on the output image i have only the background of the JPanel, lines has drawed by user disappear. Any tips to fix it? In this code line has drawed by the program, but the bug remains.
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class MarkPen extends Applet implements ActionListener, AdjustmentListener, MouseListener, MouseMotionListener {
private int x = 0;
private int y = 0;
private int prevx = 0;
private int prevy = 0;
private JPanel drawPanel = new JPanel();
private JButton saveButton = new JButton("SaveImage");
public void init()
{
setLayout(new BorderLayout());
drawPanel.setBackground(Color.red);
drawPanel.addMouseMotionListener(this);
drawPanel.addMouseListener(this);
drawPanel.add(new Comp());
drawPanel.setDoubleBuffered(true);
add(drawPanel, "Center");
saveButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
BufferedImage image = new BufferedImage(drawPanel.getWidth(), drawPanel.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = image.createGraphics();
drawPanel.paint(graphics2D);
try{
ImageIO.write(image,"jpeg", new File("C:/.../Example.jpeg"));
}
catch(Exception ex){
ex.printStackTrace();
}
}
});
add(saveButton, "South");
}
public void setGraphicalDefaults(MouseEvent e){}
public class Comp extends JComponent{
public void paintComponent(Graphics g) {
g = drawPanel.getGraphics();
g.setColor(Color.black);
g.drawLine(0,0,100,100);
}
}
public void mouseDragged(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void actionPerformed(ActionEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseMoved(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void adjustmentValueChanged(AdjustmentEvent arg0){}
}
Thanks to yours help i solved it, i post the working code below.
WORKING CODE:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
public class MarkPen extends JApplet {
private static final long serialVersionUID = 1L;
public static class DrawPanel extends JPanel {
private static final long serialVersionUID = 1L;
private List<Point> points = new ArrayList<Point>();
public DrawPanel() {
setBackground(Color.WHITE);
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
points.add(e.getPoint());
repaint();
}
});
addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent e){
Point p = null;
points.add(p);
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
#Override
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
Point p1 = null;
Point p2 = null;
g.setColor(Color.black);
for (Point p : points) {
p2 = p1;
p1 = p;
if (p1 != null && p2 != null) {
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
}
}
protected void initUI() {
setLayout(new BorderLayout());
JButton saveButton = new JButton("SaveImage");
JButton clearButton = new JButton("Clear");
final DrawPanel drawPanel = new DrawPanel();
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new BorderLayout());
setSize(1000, 305);
add(drawPanel, "Center");
saveButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
BufferedImage image = new BufferedImage(drawPanel.getWidth(), drawPanel.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = image.createGraphics();
drawPanel.paint(graphics2D);
try{
ImageIO.write(image,"png", new File("C:/.../Desktop/Example.png"));
}
catch(Exception ex){
ex.printStackTrace();
}
}
});
clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
drawPanel.points.clear();
repaint();
}
});
buttonsPanel.add(clearButton, BorderLayout.WEST);
buttonsPanel.add(saveButton, BorderLayout.EAST);
add(buttonsPanel, BorderLayout.SOUTH);
validate();
}
#Override
public void init() {
super.init();
try {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
initUI();
}
});
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
your issue is by usage of drawPanel.getGraphics();,
this methods can creates temparary object for Save JPanel into Image, not for displaying an Image in JPanel
override getPreferredSize in public class Comp extends JComponent{
drawImage inside paintComponent
use super.paintComponent in the case that you want to replace current painting
for example
class Comp extends JComponent {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bi, 0, 0, this);
}
}
it's first time i use BufferedImage and i have problem to understand how it works
See Custom Painting Approaches. The DrawOnImage example is the one that uses a BufferedImage, although it doesn't hurt to understand the other example as well.
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.