I want to draw a recangle on a JPanel. Am able to draw with the following code.
public class DrawingColor extends JFrame
{
public static void main(String[] args)
{
DrawingColor d = new DrawingColor();
}
public DrawingColor()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new MyComponent());
setSize(400,400);
setVisible(true);
}
public class MyComponent extends JComponent
{
#Override
public void paint(Graphics g)
{
int height = 200;
int width = 120;
g.setColor(Color.red);
g.drawRect(10, 10, height, width);
g.setColor(Color.gray);
g.fillRect(11, 11, height, width);
g.setColor(Color.red);
g.drawOval(250, 20, height, width);
g.setColor(Color.magenta);
g.fillOval(249, 19, height, width);
}
}
}
But getContentPane().add(new MyComponent());
Instead of this statement,I need to add one base panel to the frame. On the base panel I want to add the MyComponent panel.
JPanel basePanel = new JPanel();
basePanel = new MyComponent();
getContentPane().add(basePanel);
If I do like this, the rectangle is not getting visible. any idea?
And also I need to change the size of the rectangle at runtime. is it possible?
1) for Swing JComponent you have to use paintComponent() instead of paint() method
2) your JComponent doesn't returns PreferredSize
for example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ComponentEvent;
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() {
CustomComponents cc = new CustomComponents();
/*cc.addComponentListener(new java.awt.event.ComponentAdapter() {
#Override
public void componentResized(ComponentEvent event) {
setSize(Math.min(getPreferredSize().width, getWidth()),
Math.min(getPreferredSize().height, getHeight()));
}
});*/
add(cc, BorderLayout.CENTER);
CustomComponents cc1 = new CustomComponents();
add(cc1, BorderLayout.EAST);
pack();
// enforces the minimum size of both frame and component
setMinimumSize(getSize());
//setMaximumSize(getMaximumSize());
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 Dimension getMaximumSize() {
return new Dimension(800, 600);
}
#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);
}
}
Since you wanted to change the Dimensions of your Rectangle at run time, try this code for that :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RectangleTest extends JFrame {
private int x;
private int y;
private static JButton buttonFullSize;
private static JButton buttonHalfSize;
public RectangleTest() {
x = 0;
y = 0;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel basePanel = new JPanel();
basePanel.setLayout(new BorderLayout());
final MyComponent component = new MyComponent(400, 400);
component.setOriginAndSize(0, 0, 100, 100);
buttonFullSize = new JButton("DRAW FULL SIZE");
buttonFullSize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
component.setOriginAndSize(x++, y++,
(basePanel.getHeight() / 4), (basePanel.getWidth() / 4));
}
});
buttonHalfSize = new JButton("DRAW HALF SIZE");
buttonHalfSize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
component.setOriginAndSize(x++, y++,
(basePanel.getHeight() / 8), (basePanel.getWidth() / 8));
}
});
basePanel.add(buttonHalfSize, BorderLayout.PAGE_START);
basePanel.add(component, BorderLayout.CENTER);
basePanel.add(buttonFullSize, BorderLayout.PAGE_END);
setContentPane(basePanel);
pack();
setVisible(true);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RectangleTest();
}
});
}
}
class MyComponent extends JComponent {
private int x;
private int y;
private int width;
private int height;
private int compWidth;
private int compHeight;
MyComponent(int w, int h) {
this.compWidth = w;
this.compHeight = h;
}
public void setOriginAndSize(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
repaint();
}
#Override
public Dimension getPreferredSize() {
return (new Dimension(compWidth, compHeight));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(getBackground());
g.fillRect(x, y, width, height);
g.setColor(Color.RED);
g.drawOval(x, y, width, height);
g.setColor(Color.MAGENTA);
g.fillOval(x, y, width, height);
}
}
I had tried drawing a square and circle, dynamically varying the size at runtime....attaching the complete code ..if it helps.
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
import java.*;
import java.awt.Canvas;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class DisplayCanvas extends Canvas
{
static boolean clip = false;
static boolean clipfurther = false;
static boolean isReset = false, isSlider = false;
int w, h;
static int wi = 300, hi = 300;
public DisplayCanvas()
{
//setSize(300, 300);
setBounds(20, 40, 300, 300);
setBackground(Color.white);
}
public void paint(Graphics g)
{
Graphics2D g2=(Graphics2D) g;
w = getSize().width;
h = getSize().height;
if(clip)
{
// Ellipse2D e = new Ellipse2D.Float(w/4.0f,h/4.0f,w/2.0f,h/2.0f);
Rectangle2D r = null;
if(isSlider)
{
r = new Rectangle2D.Float((w)/(4.0f), (h)/(4.0f), wi/2.0f, hi/2.0f);
// isSlider=false;
}
else
r = new Rectangle2D.Float(w/4.0f, h/4.0f, wi/2.0f, hi/2.0f);
//g2.setClip(e);
System.out.println("Width : "+ wi +" Height : "+ hi);
g2.setClip(r);
System.out.println(g2.getClipBounds());
if(shape.selectedcolor == "red")
{
g2.setColor(Color.red);
}
else if(shape.selectedcolor == "blue")
{
g2.setColor(Color.BLUE);
}
else if(shape.selectedcolor == "yellow")
{
g2.setColor(Color.yellow);
}
//g2.setColor(Color.RED);
g2.fillRect(0, 0, w, h);
}
else if(clipfurther)
{
//Rectangle r = new Rectangle(w/4, h/4, w/4, h/4);
Ellipse2D r = new Ellipse2D.Float(w/4.0f, h/4.0f, wi/2.0f, hi/2.0f);
g2.clip(r);
//g2.setColor(Color.green);
//g2.setColor(Color.getColor(shape.selectedcolor));
if(shape.selectedcolor == "red")
{
g2.setColor(Color.red);
}
else if(shape.selectedcolor == "blue")
{
g2.setColor(Color.BLUE);
}
else if(shape.selectedcolor == "yellow")
{
g2.setColor(Color.yellow);
}
g2.fillRect(0, 0, w, h);
}
}
}
class RadioListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == shape.circle)
{
shape.selectedcolor = shape.selectedcolor_reset;
System.out.println("Inside circle "+ shape.selectedcolor_reset);
System.out.println("2222222222");
DisplayCanvas.clip = true;
DisplayCanvas.clipfurther = false;
shape.canvas.repaint();
}
if (e.getSource() == shape.square)
{
shape.selectedcolor = shape.selectedcolor_reset;
System.out.println("333333333333333");
DisplayCanvas.clip = false;
DisplayCanvas.clipfurther = true;
shape.canvas.repaint();
}
}
}
class shape extends JFrame implements ActionListener
{
static String fname;
static JPanel panel, draw;
static Container contentpane, draw_pane;
static JFrame frame;
static JLayeredPane layer, draw_layer;
static JTextField user;
static JButton reset, cancel;
static JLabel file1, file2;
static JTextField text1;
static JRadioButton circle, square;
static JInternalFrame iframe, errmessage;
static JComboBox colors;
static JEditorPane sqc;
static JScrollPane scroller;
static JSlider slider;
String colors_array[]={"...", "red", "blue", "yellow"};
static DisplayCanvas canvas;
static String selectedcolor, selectedcolor_reset;
shape()
{
canvas=new DisplayCanvas();
panel= new JPanel();
panel.setBounds(20,20,250,140);
//panel.setLayout(new FlowLayout(10, 10, 10));
panel.setLayout(null);
contentpane = getContentPane();
contentpane.add(canvas);
//draw_pane=getContentPane();
layer = new JLayeredPane();
layer.setBounds(50,245,300,205);
layer.setForeground(Color.blue);
draw_layer = new JLayeredPane();
draw_layer.setBounds(200, 200, 80, 30);
draw_layer.setForeground(Color.BLACK);
draw = new JPanel();
draw.setBounds(20, 20, 250, 300);
draw.setLayout(null);
reset = new JButton("RESET");
reset.setBounds(360, 60, 100, 25);
circle = new JRadioButton("Square");
circle.setBounds(400, 100, 100, 40);
circle.setActionCommand("encryption");
square = new JRadioButton("Circle");
square.setBounds(330,100, 60, 40);
square.setActionCommand("decryption");
colors = new JComboBox(colors_array);
colors.setBounds(405, 140, 80, 30);
colors.setVisible(true);
file1 = new JLabel(" Select Color :");
file1.setBounds(320, 130, 150, 50);
//defining the Button Group for the Radio Buttons
ButtonGroup group = new ButtonGroup();
group.add(circle);
group.add(square);
cancel = new JButton("Exit");
cancel.setBounds(365, 250, 85, 25);
file2 = new JLabel("SIZE :");
file2.setBounds(336, 180, 150, 50);
setslider(0, 100, 100, 25, 5);
slider.setBounds(386, 190, 100, 50);
slider.setVisible(true);
panel.add(file2);
panel.add(layer);
panel.add(circle);
panel.add(square);
panel.add(colors);
panel.add(slider);
panel.add(file1);
panel.add(reset);
panel.add(cancel);
//panel.add(new CircleDraw());
//draw.add(draw_layer);
// draw_pane.add(draw);
contentpane.add(panel);
// contentpane.add(draw);
// contentpane.add(scroller);
RadioListener radio = new RadioListener();
circle.addActionListener(radio);
square.addActionListener(radio);
reset.addActionListener(this);
cancel.addActionListener(this);
colors.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JComboBox cb = (JComboBox)ae.getSource();
selectedcolor = (String)cb.getSelectedItem();
System.out.println(selectedcolor);
selectedcolor_reset = selectedcolor;
System.out.println("SELECTED "+ cb.getSelectedIndex());
canvas.repaint();
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== cancel)
{
System.exit(0);
}
if (e.getSource() == reset)
{
System.out.println("111111111");
DisplayCanvas.clip = true;
DisplayCanvas.clipfurther = false;
DisplayCanvas.isReset = true;
shape.selectedcolor = "...";
System.out.println(" PREVIOUS " + selectedcolor_reset);
DisplayCanvas.hi = DisplayCanvas.wi = 300;
canvas.repaint();
}
}
public class SliderListener implements ChangeListener
{
public SliderListener()
{
}
public void stateChanged(ChangeEvent e)
{
JSlider slider = (JSlider)e.getSource();
System.out.println(slider.getValue());
DisplayCanvas.wi = slider.getValue() * 3;
DisplayCanvas.hi = DisplayCanvas.wi;
DisplayCanvas.isSlider = true;
canvas.repaint();
}
}
public void setslider(int min,int max,int init,int mjrtk,int mintk)
{
slider = new JSlider(JSlider.HORIZONTAL, min, max, init);
slider.setPaintTicks(true);
slider.setMajorTickSpacing(mjrtk);
slider.setMinorTickSpacing(mintk);
slider.setPaintLabels(true);
slider.addChangeListener((ChangeListener) new SliderListener());
}
}
public class display
{
static JFrame frame;
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// TODO code application logic here
frame=new shape();
frame.setBounds(380, 200, 500, 400);
frame.setTitle("SHAPE AND COLOR");
frame.setVisible(true);
}
}
Related
This is my 1st question here. I'm trying to build a White Page adjustable by zoom. It's inside a JScrollPane, so the size of the JScrollPane's ScrollBars are adjustable in the Dimension of that JPanel.
I want to adjust the size of those ScrollBars as the Size of the page (variables width and height in the code) + 2 borderSize, so the full size is equal the Page + margin of a borderSize around it. It works if zoom = 1.0.
If zoom < 1.0, the scroll bar is smaller than the Page and cut a piece of it. If zoom > 1 the Dimension size is way bigger than the page, leaving a huger border on its right and down corners, bigger than the borderSize.
How do I do this?
PS: I'm started learning java by myself, in the Quarantine last year, never had a teacher, just the internet, so any critics or suggestions, please, tell me.
Here's the JPanel's code:
package test;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowStateListener;
import java.awt.geom.AffineTransform;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import javax.swing.JSlider;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
public class Main2 {
private MyPanel mp = new MyPanel();
private JFrame frame;
private JSlider zoomSlider = new JSlider();
private JLabel zoomLabel = new JLabel("Zoom: XXX");
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main2 window = new Main2();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Main2() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 619, 403);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SpringLayout springLayout = new SpringLayout();
frame.getContentPane().setLayout(springLayout);
springLayout.putConstraint(SpringLayout.SOUTH, zoomSlider, 40, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.EAST, zoomSlider, -115, SpringLayout.EAST, frame.getContentPane());
zoomSlider.setValue(100);
zoomSlider.setSnapToTicks(true);
zoomSlider.setPaintTicks(true);
zoomSlider.setMaximum(200);
zoomSlider.setMinorTickSpacing(5);
zoomSlider.setMinimum(5);
springLayout.putConstraint(SpringLayout.NORTH, zoomSlider, 0, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.WEST, zoomSlider, 0, SpringLayout.WEST, frame.getContentPane());
frame.getContentPane().add(zoomSlider);
JScrollPane scrollPane = new JScrollPane(mp);
springLayout.putConstraint(SpringLayout.NORTH, scrollPane, 10, SpringLayout.SOUTH, zoomSlider);
springLayout.putConstraint(SpringLayout.WEST, scrollPane, 10, SpringLayout.WEST, frame.getContentPane());
springLayout.putConstraint(SpringLayout.SOUTH, scrollPane, -10, SpringLayout.SOUTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.EAST, scrollPane, -10, SpringLayout.EAST, frame.getContentPane());
frame.getContentPane().add(scrollPane);
springLayout.putConstraint(SpringLayout.NORTH, zoomLabel, 10, SpringLayout.NORTH, frame.getContentPane());
springLayout.putConstraint(SpringLayout.WEST, zoomLabel, 6, SpringLayout.EAST, zoomSlider);
frame.getContentPane().add(zoomLabel);
frame.addWindowStateListener(new WindowStateListener() {
#Override
public void windowStateChanged(WindowEvent arg0) {
// TODO Auto-generated method stub
mp.draw();
}
});
zoomSlider.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
int temp = (zoomSlider.getValue())-zoomSlider.getValue()%5;
setZoom(temp);
mp.draw();
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
int temp = (zoomSlider.getValue())-zoomSlider.getValue()%5;
setZoom(temp);
mp.draw();
}
});
mp.addMouseWheelListener(new MouseWheelListener() {
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
if (e.getPreciseWheelRotation() < 0) {
setZoom(zoomSlider.getValue()- 5);
} else {
setZoom(zoomSlider.getValue()+ 5);
}
// zoom += e.getPreciseWheelRotation();
if (mp.getZoom()*100 < 10) {
setZoom(10);
}
mp.draw();
}
});
AdjustmentListener adj = new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
setZoom(zoomSlider.getValue());
mp.draw();
}
};
scrollPane.getVerticalScrollBar().addAdjustmentListener(adj);
scrollPane.getHorizontalScrollBar().addAdjustmentListener(adj);
}
public void setZoom(int n) {
mp.setZoom(n);
zoomSlider.setValue(n);
zoomLabel.setText("Zoom: "+mp.getZoom()+"x");
}
}
class MyPanel extends JPanel{
private static final long serialVersionUID = -716735372803790424L;
int borderSize=28;
int zoom=100;
int height = 3565;
int width = 2537;
int widthz, heightz;
public MyPanel() {
setBackground(Color.DARK_GRAY);
}
#Override
public Dimension getPreferredSize() {
int a, b;
String temp;
Float x, y;
x=(getZoom()*width); //Size of the page adjusted by zoom
y=(getZoom()*height);
temp = x.toString();
String temp1[] = temp.split("\\."); // converted to string to convert it to int
a = Integer.valueOf(temp1[0])+2*borderSize; //that value + 2 BorderSize
temp = y.toString();
String temp2[] = temp.split("\\.");
b = Integer.valueOf(temp2[0])+2*borderSize;
return new Dimension (a,b);
}
#Override
public void paintComponent (Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d = putZoom(g2d);
g2d.setColor(Color.WHITE);
g2d.fillRect(this.getX(),this.getY(), width, height);
g2d.setColor(Color.BLACK);
g2d.drawRect(this.getX()+borderSize,this.getY()+borderSize,width-2*borderSize,height-2*borderSize);
g2d.dispose();
}
public Graphics2D putZoom(Graphics2D g) {
AffineTransform at = new AffineTransform();
at.translate(borderSize,borderSize); // put the page a borderSize from the upper-left corner
at.scale(getZoom(),getZoom()); //adjust the page as zoom
Graphics2D g2d = g;
g2d.setTransform(at);
return g2d;
}
public void draw() { //this method is to update the draw from the main
repaint();
}
public Float getZoom() {
return Float.valueOf(zoom)/100;
}
public void setZoom(int zom) { //this method is to update Zoom from the main
zoom=zom;
String zoomheight []= (String.valueOf(getZoom()*height)).split("\\.");
heightz = Integer.valueOf(zoomheight[0]);
String zoomwidth []= (String.valueOf(getZoom()*width)).split("\\.");
widthz = Integer.valueOf(zoomwidth[0]);
}
public int getZoomInt() {
return this.zoom;
}
}
Zoom(values from 0.1 to 2.0).
How can i improve this? Also, i have no idea how to update the JScrollPane's scrollbars together with the zoom.Thanks for the help.
UPDATE: i've created a minimal reproducible exemple.
Introduction
I started working on this before you updated your question. I used a zoom percentage rather than a zoom factor.
I created the following GUI and set the initial state to 30 percent.
I made the inner JPanel a checkerboard so you can more easily see the zoom. I modified your initial values so the inner JPanel would represent an 8 1/2 x 11 piece of paper at 50 pixels per inch.
Here's the same GUI at 100 percent.
Here's the same GUI at 10 percent.
Explanation
I created a JFrame and a control JPanel to hold the JSlider. I used a GridLayout to create the control JPanel.
I created an inner JPanel to hold the drawing and a display JPanel that holds the JScrollPane. I made the display JPanel proportionate to the size of the inner JPanel so I wouldn't have any stretching issues.
Getting the GUI to revalidate / repaint turned out to be the biggest challenge. I wound up having to invalidate the JScrollPane, both JScrollBars, and the display JPanel. I also had to reset the JScrollBars to zero each time I changed the zoom percentage.
Code
Here's the complete runnable code. I made all of the classes inner classes so I could post this as one code block.
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class ZoomJPanelGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new ZoomJPanelGUI());
}
private int zoomPercentage = 30;
private DisplayPanel displayPanel;
private JFrame frame;
#Override
public void run() {
frame = new JFrame("Zoom JPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createControlPanel(), BorderLayout.BEFORE_FIRST_LINE);
this.displayPanel = new DisplayPanel(zoomPercentage);
frame.add(displayPanel.getPanel(), BorderLayout.AFTER_LAST_LINE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createControlPanel() {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15));
JLabel label = new JLabel("Zoom Percentage");
label.setFont(panel.getFont().deriveFont(Font.BOLD, 24f));
panel.add(label);
JSlider slider = new JSlider(
JSlider.HORIZONTAL, 10, 100, zoomPercentage);
slider.setFont(panel.getFont().deriveFont(16f));
slider.setMajorTickSpacing(30);
slider.setMinorTickSpacing(5);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent event) {
JSlider slider = (JSlider) event.getSource();
if (!slider.getValueIsAdjusting()) {
zoomPercentage = (int) slider.getValue();
displayPanel.setZoomPercentage(zoomPercentage);
displayPanel.repaint();
frame.pack();
}
}
});
panel.add(slider);
return panel;
}
public class DisplayPanel {
private InnerPanel innerPanel;
private final JPanel panel;
private JScrollPane scrollPane;
private int zoomPercentage;
public DisplayPanel(int zoomPercentage) {
this.zoomPercentage = zoomPercentage;
this.panel = createDisplayPanel();
}
private JPanel createDisplayPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
this.innerPanel = new InnerPanel(zoomPercentage);
scrollPane = new JScrollPane(innerPanel);
scrollPane.setPreferredSize(new Dimension(475, 600));
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
public void setZoomPercentage(int zoomPercentage) {
this.zoomPercentage = zoomPercentage;
innerPanel.setZoomPercentage(zoomPercentage);
}
public JPanel getPanel() {
return panel;
}
public void repaint() {
innerPanel.repaint();
scrollPane.invalidate();
JScrollBar hScrollBar = scrollPane.getHorizontalScrollBar();
JScrollBar vScrollBar = scrollPane.getVerticalScrollBar();
hScrollBar.setValue(0);
vScrollBar.setValue(0);
hScrollBar.invalidate();
vScrollBar.invalidate();
panel.invalidate();
}
}
public class InnerPanel extends JPanel {
private static final long serialVersionUID = 1L;
private int maximumBorderSize = 25;
private int maximumCellSize = 50;
private int maximumHeight = 5500;
private int maximumWidth = 4250;
private int zoomPercentage;
public InnerPanel(int zoomPercentage) {
this.zoomPercentage = zoomPercentage;
}
public void setZoomPercentage(int zoomPercentage) {
this.zoomPercentage = zoomPercentage;
}
#Override
public Dimension getPreferredSize() {
int width = maximumWidth * zoomPercentage / 100;
int height = maximumHeight * zoomPercentage / 100;
return new Dimension(width, height);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int borderSize = maximumBorderSize * zoomPercentage / 100;
paintBackground(g2d);
paintBorder(g2d, borderSize);
paintCheckerboard(g2d, borderSize);
}
private void paintBackground(Graphics2D g2d) {
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, getWidth(), getHeight());
}
private void paintBorder(Graphics2D g2d, int borderSize) {
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(3f));
g2d.drawRect(borderSize, borderSize, getWidth() - 2 * borderSize,
getHeight() - 2 * borderSize);
}
private void paintCheckerboard(Graphics2D g2d, int borderSize) {
int cellSize = maximumCellSize * zoomPercentage / 100;
int width = maximumWidth - maximumBorderSize * 2 - 2;
int height = maximumHeight - maximumBorderSize * 2 - 2;
int cellWidth = width / maximumCellSize;
int cellHeight = height / maximumCellSize;
boolean isBlue = true;
int x = borderSize;
int y = borderSize;
int heightRemainder = height - cellHeight * cellSize;
for (int i = 0; i < cellHeight; i++) {
int widthRemainder = width - cellWidth * cellSize;
for (int j = 0; j < cellWidth; j++) {
if (isBlue) {
g2d.setColor(Color.BLUE);
} else {
g2d.setColor(Color.YELLOW);
}
isBlue = !isBlue;
g2d.fillRect(x, y, cellSize, cellSize);
x += cellSize;
if (widthRemainder > 0) {
x++;
widthRemainder--;
}
}
// isBlue = !isBlue;
x = borderSize;
y += cellSize;
if (heightRemainder > 0) {
y++;
heightRemainder--;
}
}
}
}
}
I've finally did it. Started by not using transformation for scaling it, but making a new draw with the size zoomed, adapting all sizes in the method setSizes(), and adjusting the Dimension by those sizes.
(Just changed this class)
class MyPanel extends JPanel{
private static final long serialVersionUID = -716735372803790424L;
int borderSize=28;
int zoom=100;
int height = 3565;
int width = 2537;
int widthz, heightz;
int maxHeight, maxWidth; //max size of draw
int maxAreaHeight, maxAreaWidth; //max size of area
public MyPanel() {
setBackground(Color.DARK_GRAY);
}
#Override
public Dimension getPreferredSize() {
setSizes();
return new Dimension (maxAreaWidth,maxAreaHeight);
}
#Override
public void paintComponent (Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d= createBase(g2d);
}
public void draw() { //this method is to update the draw from the main
repaint();
}
public Float getZoom() {return Float.valueOf(zoom)/100;}
public void setZoom(int zom) {zoom=zom;}
public int getZoomInt() {return this.zoom;}
public void setSizes () {
widthz= width*getZoomInt()/100;
heightz=height*getZoomInt()/100;
maxHeight = heightz+2*borderSize;
maxWidth = widthz +2*borderSize;
maxAreaHeight = this.getY()+maxHeight;
maxAreaWidth = this.getX()+maxWidth;
if (this.getSize() != new Dimension(maxAreaWidth, maxAreaHeight)) {
this.setSize(maxAreaWidth, maxAreaHeight);
}
}
public Graphics2D createBase(Graphics2D g2d) {
Graphics2D g = g2d;
setSizes();
g.setColor(Color.WHITE);
g.fillRect(this.getX()+borderSize,this.getY()+borderSize, widthz, heightz);
g.setColor(Color.BLACK);
g.drawRect(this.getX()+borderSize+borderSize*zoom/100,this.getY()+borderSize+borderSize*zoom/100,widthz-2*borderSize*zoom/100,heightz-2*borderSize*zoom/100);
return g;
}
}
Thanks for all the help.
I am attempting to use jsliders to allow a user to pinpoint the origin of a circle to be drawn on a canvas. I am using a button to show and hide the circle. I am using paint on an inner jpanel so that paint will not write over components. However, the coordinates inside the jpanel are different than the coordinates for the entire frame. So, it is very difficult for me to get the coordinates of the jslider and then translate it to the jpanel to draw the circle. Is there an easy way to figure this out without a ton of guess and check? I am also using the custom layout miglayout. I have included the code for my GUI class as well as my custom JPanel I made so I could mess with the paint method.
public class CircleGUI extends JFrame implements ActionListener {
private MigLayout layout = new MigLayout();
private CustomPanel innerpanel;
private JSlider x,y;
private JColorChooser colorpick;
private JButton state;
private boolean bstate;
CircleGUI() {
initialize();
}
private void initialize() {
Border blackline = BorderFactory.createLineBorder(Color.black);
bstate = false;
x = new JSlider(JSlider.HORIZONTAL,650,325);
x.setPaintTicks(true);
x.setPaintLabels(true);
x.setPreferredSize(new Dimension(650,0));
y = new JSlider(JSlider.HORIZONTAL,650,325);
y.setPaintTicks(true);
y.setPaintLabels(true);
y.setInverted(true);
y.setOrientation(JSlider.VERTICAL);
y.setPreferredSize(new Dimension (0,600));
colorpick = new JColorChooser();
state = new JButton("Show");
state.addActionListener(e -> {
if(!bstate) {
int positionx = x.getValue() - 80;
int positiony = y.getValue();
Color c = colorpick.getColor();
innerpanel.setColor(c);
innerpanel.setX(positionx);
innerpanel.setY(positiony);
innerpanel.repaint();
state.setText("Hide");
bstate = true;
} else {
Color transparent = new Color(0,0,0,0);
innerpanel.setColor(transparent);
innerpanel.repaint();
state.setText("Show");
bstate = false;
}
});
JPanel outerpanel = new JPanel(layout);
innerpanel = new CustomPanel();
innerpanel.setPreferredSize(new Dimension(600,600));
innerpanel.setBorder(blackline);
outerpanel.add(x,"wrap");
outerpanel.add(y,"split 2");
outerpanel.add(innerpanel);
outerpanel.add(state,"wrap");
outerpanel.add(colorpick);
this.setSize(1000, 1000);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(outerpanel);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
public class CustomPanel extends JPanel implements ActionListener {
private Color c;
private int x;
private int y;
public CustomPanel() {
c = null;
}
#Override
public void actionPerformed (ActionEvent e) {
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(c);
g2.fill(new Ellipse2D.Double(x, y, 100, 100));
}
public void setColor(Color c) {
this.c = c;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
Your problem is you are trying to make a one-to-one mapping between the value of the JSlider and the coordinate in your CustomPanel. You should use the JSlider value as a percentage, i.e. minimum value zero and maximum value 100. If you want the circle to appear in the middle of the CustomPanel so you place both JSliders in their mid-points, i.e. both at 50%. Then you calculate 50% of the corresponding dimension to get the coordinate. If the width of CustomPanel is 600, then 50% of 600 is 300 so positionx needs to be 300.
The only thing I changed in your code is the calculation of positionx and positiony.
import java.awt.Color;
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 java.awt.geom.Ellipse2D;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.border.Border;
import net.miginfocom.swing.MigLayout;
public class CircleGUI extends JFrame implements ActionListener {
private MigLayout layout = new MigLayout();
private CustomPanel innerpanel;
private JSlider x,y;
private JColorChooser colorpick;
private JButton state;
private boolean bstate;
CircleGUI() {
initialize();
}
private void initialize() {
Border blackline = BorderFactory.createLineBorder(Color.black);
bstate = false;
// x = new JSlider(JSlider.HORIZONTAL, 650, 325);
x = new JSlider(0, 100, 10);
x.setPaintTicks(true);
x.setPaintLabels(true);
x.setPreferredSize(new Dimension(650, 0));
// y = new JSlider(JSlider.HORIZONTAL, 650, 325);
y = new JSlider(0, 100, 10);
y.setPaintTicks(true);
y.setPaintLabels(true);
y.setInverted(true);
y.setOrientation(JSlider.VERTICAL);
y.setPreferredSize(new Dimension(0, 600));
colorpick = new JColorChooser();
state = new JButton("Show");
state.addActionListener(e -> {
if (!bstate) {
int positionx = Math.round(x.getValue() / 100.0f * innerpanel.getSize().width) - 50;
int positiony = Math.round(y.getValue() / 100.0f * innerpanel.getSize().height) - 50;
Color c = colorpick.getColor();
innerpanel.setColor(c);
innerpanel.setX(positionx);
innerpanel.setY(positiony);
innerpanel.repaint();
state.setText("Hide");
bstate = true;
}
else {
Color transparent = new Color(0, 0, 0, 0);
innerpanel.setColor(transparent);
innerpanel.repaint();
state.setText("Show");
bstate = false;
}
});
JPanel outerpanel = new JPanel(layout);
innerpanel = new CustomPanel();
innerpanel.setPreferredSize(new Dimension(600, 600));
innerpanel.setBorder(blackline);
outerpanel.add(x, "wrap");
outerpanel.add(y, "split 2");
outerpanel.add(innerpanel);
outerpanel.add(state, "wrap");
outerpanel.add(colorpick);
this.setSize(1000, 1000);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(outerpanel);
}
#Override
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
CircleGUI cg = new CircleGUI();
cg.setVisible(true);
});
}
}
class CustomPanel extends JPanel implements ActionListener {
private Color c;
private int x;
private int y;
public CustomPanel() {
c = null;
}
#Override
public void actionPerformed(ActionEvent e) {
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(c);
g2.fill(new Ellipse2D.Double(x, y, 100, 100));
}
public void setColor(Color c) {
this.c = c;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
In my code i generate randoms integer between 0 and 60 and i draw lines based on these.
I just want my lines fit the ordinate vertical line without touching my randoms integer... I guess it's kind of a mathematics problem but i'm really stuck here!
Here's my code first:
Windows.java:
public class Window extends JFrame{
Panel pan = new Panel();
JPanel container, north,south, west;
public JButton ip,print,cancel,start,ok;
JTextArea timeStep;
JLabel legend;
double time=0;
double temperature=0.0;
Timer chrono;
public static void main(String[] args) {
new Window();
}
public Window()
{
System.out.println("je suis là");
this.setSize(1000,400);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setTitle("Assignment2 - CPU temperature");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new JPanel(new BorderLayout());
north = new JPanel();
north.setLayout(new BorderLayout());
ip = new JButton ("New");
north.add(ip, BorderLayout.WEST);
print = new JButton ("Print");
north.add(print,BorderLayout.EAST);
JPanel centerPanel = new JPanel();
centerPanel.add(new JLabel("Time Step (in s): "));
timeStep = new JTextArea("0.1",1,5);
centerPanel.add(timeStep);
start = new JButton("OK");
ListenForButton lForButton = new ListenForButton();
start.addActionListener(lForButton);
ip.addActionListener(lForButton);
print.addActionListener(lForButton);
centerPanel.add(start);
north.add(centerPanel, BorderLayout.CENTER);
west = new JPanel();
JLabel temp = new JLabel("°C");
west.add(temp);
container.add(north, BorderLayout.NORTH);
container.add(west,BorderLayout.WEST);
container.add(pan, BorderLayout.CENTER);
this.setContentPane(container);
this.setVisible(true);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==start)
{
time=Double.parseDouble(timeStep.getText());
System.out.println(time);
chrono = new Timer((int)(1000*time),pan);
chrono.start();
}
if(e.getSource()==ip)
{
JPanel options = new JPanel();
JLabel address = new JLabel("IP Address:");
JTextField address_t = new JTextField(15);
JLabel port = new JLabel("Port:");
JTextField port_t = new JTextField(5);
options.add(address);
options.add(address_t);
options.add(port);
options.add(port_t);
int result = JOptionPane.showConfirmDialog(null, options, "Please Enter an IP Address and the port wanted", JOptionPane.OK_CANCEL_OPTION);
if(result==JOptionPane.OK_OPTION)
{
System.out.println(address_t.getText());
System.out.println(port_t.getText());
}
}
if(e.getSource()==print)
{
chrono.stop();
}
}
}
}
Panel.java:
public class Panel extends JPanel implements ActionListener {
int rand;
int lastrand=0;
ArrayList<Integer> randL = new ArrayList<>();
ArrayList<Integer> tL = new ArrayList<>();
int lastT = 0;
Color red = new Color(255,0,0);
Color green = new Color(0,200,0);
Color blue = new Color (0,0,200);
Color yellow = new Color (200,200,0);
int max=0;
int min=0;
int i,k,inc = 0,j;
int total,degr,moyenne;
public Panel()
{
super();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(1.8f));
g2.drawLine(20, 20, 20, this.getHeight()-50);
g2.drawLine(20, this.getHeight()-50, this.getWidth()-50, this.getHeight()-50);
g2.drawLine(20, 20, 15, 35);
g2.drawLine(20, 20, 25, 35);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-45);
g2.drawLine(this.getWidth()-50, this.getHeight()-50, this.getWidth()-65, this.getHeight()-55);
g.drawString("10", 0, this.getHeight()-85);
g.drawString("20", 0, this.getHeight()-125);
g.drawString("30", 0, this.getHeight()-165);
g.drawString("40", 0, this.getHeight()-205);
g.drawString("50", 0, this.getHeight()-245);
g2.drawString("Maximum: ", 20, this.getHeight()-20);
g2.drawString(Integer.toString(max), 80, this.getHeight()-20);
g2.drawString("Minimum: ", 140, this.getHeight()-20);
g2.drawString(Integer.toString(min), 200, this.getHeight()-20);
g2.drawString("Average: ", 260, this.getHeight()-20);
g2.drawString(Integer.toString(moyenne), 320, this.getHeight()-20);
g2.setColor(red);
g2.drawLine(500, this.getHeight()-25, 540, this.getHeight()-25);
g2.setColor(new Color(0,0,0));
g2.drawString(": Maximum", 560, this.getHeight()-20);
g2.setColor(blue);
g2.drawLine(640, this.getHeight()-25, 680, this.getHeight()-25);
g2.setColor(new Color(0,0,0));
g2.drawString(": Minimum", 700, this.getHeight()-20);
g2.setColor(green);
g2.drawLine(780, this.getHeight()-25, 820, this.getHeight()-25);
g2.setColor(new Color(0,0,0));
g2.drawString(": Average", 840, this.getHeight()-20);
if(!randL.isEmpty()){
g2.setColor(red);
g2.drawLine(15, this.getHeight()-50-max, this.getWidth()-50,this.getHeight()-50-max);
g2.setColor(blue);
g2.drawLine(15, this.getHeight()-50-min, this.getWidth()-50,this.getHeight()-50-min);
g2.setColor(green);
g2.drawLine(15, this.getHeight()-50-moyenne, this.getWidth()-50,this.getHeight()-50-moyenne);
}
for(i = 0; i<tL.size(); i++){
int temp = randL.get(i);
int t = tL.get(i);
g2.setColor(new Color(0,0,0));
g2.drawLine(20+t, this.getHeight()-50-temp, 20+t, this.getHeight()-50);
// Ellipse2D circle = new Ellipse2D.Double();
//circle.setFrameFromCenter(20+t, this.getHeight()-50, 20+t+2, this.getHeight()-52);
}
for(j=0;j<5;j++)
{
inc=inc+40;
g2.setColor(new Color(0,0,0));
g2.drawLine(18, this.getHeight()-50-inc, 22, this.getHeight()-50-inc);
}
inc=0;
}
#Override
public void actionPerformed(ActionEvent e) {
rand = (int)(Math.random() * (60));
lastT += 80;
randL.add(rand);
tL.add(lastT);
Object obj = Collections.max(randL);
max = (int) obj;
Object obj2 = Collections.min(randL);
min = (int) obj2;
if(!randL.isEmpty()) {
degr = randL.get(k);
total += degr;
moyenne=total/randL.size();
}
k++;
if(randL.size()>=12)
{
randL.removeAll(randL);
tL.removeAll(tL);
lastT = 0;
k=0;
degr=0;
total=0;
moyenne=0;
}
repaint();
}
}
And here it what i gives me :
Sorry it's a real mess!
Any thoughts ?
Thanks.
You need to stop working with absolute/magical values, and start using the actual values of the component (width/height).
The basic problem is a simple calculation which takes the current value divides it by the maximum value and multiples it by the available width of the allowable area
int length = (value / max) * width;
value / max generates a percentage value of 0-1, which you then use to calculate the percentage of the available width of the area it will want to use.
The following example places a constraint (or margin) on the available viewable area, meaning all the lines need to be painted within that area and not use the entire viewable area of the component
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DrawLine {
public static void main(String[] args) {
new DrawLine();
}
public DrawLine() {
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 {
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int margin = 20;
int width = getWidth() - (margin * 2);
int height = getHeight() - (margin * 2);
int x = margin;
for (int index = 0; index < 4; index++) {
int y = margin + (int)(((index / 3d) * height));
int length = (int)(((index + 1) / 4d) * width);
g2d.drawLine(x, y, x + length, y);
}
g2d.dispose();
}
}
}
Task: There are 2 labels which connect with each other by line, user must be able to move each of the labels with mouse and the connection between lables must move accordingly.
Here is my code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class BackgroundJPanel extends JPanel {
BackgroundJPanel() {
this.setBounds(0, 0, 200, 200);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(0, 0, 198, 198);
g.setColor(Color.black);
g.drawRect(0, 0, 198, 198);
}
}
class LinkJPanel extends JPanel {
JLabel[] labels = null;
LinkJPanel(JLabel[] labelsIn) {
labels = labelsIn;
this.setBounds(0, 0, 200, 200);
this.setOpaque(false);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(labels[0].getX(), labels[0].getY(),
labels[1].getX(), labels[1].getY());
}
}
class LabelJPanel extends JPanel {
AllPanel allPanel = null;
LabelJPanel(AllPanel allPanelIn) {
allPanel = allPanelIn;
this.setOpaque(false);
JLabel[] labels = allPanel.labels;
labels[0] = new JLabel("11");
this.add(labels[0]);
labels[1] = new JLabel("22");
this.add(labels[1]);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
this.addMouseMotionListener(myMouseAdapter);
this.addMouseListener(myMouseAdapter);
}
class MyMouseAdapter extends MouseAdapter {
JLabel labelToMove = null;
int startDeltaX = -1;
int startDeltaY = -1;
JLabel whichLabel(MouseEvent e) {
for (JLabel label : allPanel.labels) {
int deltaX = e.getX() - label.getX();
int deltaY = e.getY() - label.getY();
if ((deltaX >= 0)
&& (deltaX < label.getPreferredSize().width)
&& (deltaY >= 0)
&& (deltaY < label.getPreferredSize().height)) {
return label;
}
}
return null;
}
#Override
public void mousePressed(MouseEvent e) {
labelToMove = whichLabel(e);
if (labelToMove != null) {
startDeltaX = labelToMove.getX() - e.getX();
startDeltaY = labelToMove.getY() - e.getY();
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (labelToMove != null) {
updateLocation(e);
}
}
#Override
public void mouseReleased(MouseEvent e) {
labelToMove = null;
}
public void updateLocation(MouseEvent e) {
int newXCoord = e.getX() + startDeltaX;
int newYCoord = e.getY() + startDeltaY;
labelToMove.setBounds(newXCoord, newYCoord,
labelToMove.getPreferredSize().width,
labelToMove.getPreferredSize().height);
//allPanel.backgroundJPanel.repaint();
allPanel.linkJPanel.repaint();
}
}
}
class AllPanel extends JPanel {
BackgroundJPanel backgroundJPanel = null;
LinkJPanel linkJPanel = null;
LabelJPanel labelJPanel = null;
JLabel[] labels = null;
AllPanel() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(200, 200));
labels = new JLabel[2];
backgroundJPanel = new BackgroundJPanel();
this.add(backgroundJPanel);
linkJPanel = new LinkJPanel(labels);
this.add(linkJPanel);
labelJPanel = new LabelJPanel(this);
this.add(labelJPanel);
this.setComponentZOrder(backgroundJPanel, 2);
this.setComponentZOrder(linkJPanel, 1);
this.setComponentZOrder(labelJPanel, 0);
}
}
class MyFrame extends JFrame {
MyFrame() {
this.setTitle("Test");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(new AllPanel());
this.pack();
this.setVisible(true);
this.setResizable(false);
}
}
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MyFrame();
}
});
}
}
I use 3 JPanel - one for background, one for draw connection line, one for drawing 2 labels. JPanel for drawing labels has MouseMotion and Mouse listeners. When some mouse action appears code check which one of the label must be move and then change that label coordinates and repaint JPanel with connection line.
All work fine until I try also repaint JPanel with background. If I uncomment the line
//allPanel.backgroundJPanel.repaint();
after action JLabels and line start disappeare.
Can someone explane why this happen?
I'm stuck with a problem considering my Display class, which extends Canvas.
A single thread is running within the very same class.
In this thread, the repaint method is called.
However, while the thread works fine, the paint method is never called!
Here's my code (I left out everything unrelated):
package display;
public final class Display extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
private Frame frame;
private GraphicsEnvironment ge;
private GraphicsDevice gd;
public BDisplay() {
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gd = ge.getDefaultScreenDevice();
frame = new Frame();
//frame.setUndecorated(true);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
frame.add(this);
frame.setLayout(null);
//gd.setFullScreenWindow(frame);
}
#Override
public final void paint(Graphics g) {
//THIS METHOD IS NEVER CALLED
System.out.println("Paint method was called!");
super.paint(g);
//...
}
#Override
public synchronized void run() {
while (isRunning()) {
//THIS LOOP WORKS FINE.
this.repaint();
}
}
}
It has nothing to do with some missing functions like isRunning().
They exist, i just left those out.
I never stumbled across a problem like this before,
although I haven't done anything with SWING or AWT for some time now.
Can anyone help?
The thread loop works fine,
but the repaint just doesn't seem to get scheduled...
You're realizing the JFrame before you add the component (i.e. Canvas, and previously JPanel).
Try this
public BDisplay() {
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gd = ge.getDefaultScreenDevice();
frame = new Frame();
frame.setResizable(false);
frame.add(this);
//frame.setLayout(null); // Why are you using a null layout?
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
EDIT
By the way, I'd recommend using a JPanel instead of a Canvas since it's not recommended that you mix heavy and light components. For more detail, see Mixing heavy and light components.
and now ??? by using javax.swing.Timer
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AnimationJPanel extends JPanel {
private static final long serialVersionUID = 1L;
private int cx = 0;
private int cy = 150;
private int cw = 20;
private int ch = 20;
private int xinc = 1;
private int yinc = 1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
AnimationJPanel panel = new AnimationJPanel();
panel.setPreferredSize(new Dimension(400, 300));
panel.animate();
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public AnimationJPanel() {
setLayout(new BorderLayout());
JLabel label = new JLabel("This is an AnimationJPanel");
label.setForeground(Color.RED);
label.setHorizontalAlignment(SwingConstants.CENTER);
add(label);
setBackground(Color.BLACK);
setForeground(Color.RED);
setOpaque(true);
}
public void animate() {
new Timer(15, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Rectangle oldCircle = new Rectangle(cx - 1, cy - 1, cw + 2, ch + 2);
cx += xinc;
cy += yinc;
if (cx >= getWidth() - cw || cx <= 0) {
xinc *= -1;
}
if (cy >= getHeight() - ch || cy <= 0) {
yinc *= -1;
}
repaint(oldCircle);
repaint(cx - 1, cy - 1, cw + 2, ch + 2);
}
}).start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(cx, cy, cw, ch);
}
}
or
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class AnimationBackground {
public AnimationBackground() {
Random random = new Random();
JFrame frame = new JFrame("Animation Background");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
final MyJPanel panel = new MyJPanel();
panel.setBackground(Color.BLACK);
for (int i = 0; i < 50; i++) {
Star star = new Star(new Point(random.nextInt(490), random.nextInt(490)));
star.setColor(new Color(100 + random.nextInt(155), 100 + random.nextInt(155), 100 + random.nextInt(155)));
star.setxIncr(-3 + random.nextInt(7));
star.setyIncr(-3 + random.nextInt(7));
panel.add(star);
}
panel.setLayout(new GridLayout(10, 1));
JLabel label = new JLabel("This is a Starry background.", JLabel.CENTER);
label.setForeground(Color.WHITE);
panel.add(label);
JPanel stopPanel = new JPanel();
stopPanel.setOpaque(false);
stopPanel.add(new JButton(new AbstractAction("Stop this madness!!") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
panel.stopAnimation();
}
}));
panel.add(stopPanel);
JPanel startPanel = new JPanel();
startPanel.setOpaque(false);
startPanel.add(new JButton(new AbstractAction("Start moving...") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
panel.startAnimation();
}
}));
panel.add(startPanel);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
AnimationBackground animationBackground = new AnimationBackground();
}
});
}
class Star extends Polygon {
private static final long serialVersionUID = 1L;
private Point location = null;
private Color color = Color.YELLOW;
private int xIncr, yIncr;
static final int WIDTH = 500, HEIGHT = 500;
Star(Point location) {
int x = location.x;
int y = location.y;
this.location = location;
this.addPoint(x, y + 8);
this.addPoint(x + 8, y + 8);
this.addPoint(x + 11, y);
this.addPoint(x + 14, y + 8);
this.addPoint(x + 22, y + 8);
this.addPoint(x + 17, y + 12);
this.addPoint(x + 21, y + 20);
this.addPoint(x + 11, y + 14);
this.addPoint(x + 3, y + 20);
this.addPoint(x + 6, y + 12);
}
public void setColor(Color color) {
this.color = color;
}
public void move() {
if (location.x < 0 || location.x > WIDTH) {
xIncr = -xIncr;
}
if (location.y < 0 || location.y > WIDTH) {
yIncr = -yIncr;
}
translate(xIncr, yIncr);
location.setLocation(location.x + xIncr, location.y + yIncr);
}
public void setxIncr(int xIncr) {
this.xIncr = xIncr;
}
public void setyIncr(int yIncr) {
this.yIncr = yIncr;
}
public Color getColor() {
return color;
}
}
class MyJPanel extends JPanel {
private static final long serialVersionUID = 1L;
private ArrayList<Star> stars = new ArrayList<Star>();
private Timer timer = new Timer(20, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Star star : stars) {
star.move();
}
repaint();
}
});
public void stopAnimation() {
if (timer.isRunning()) {
timer.stop();
}
}
public void startAnimation() {
if (!timer.isRunning()) {
timer.start();
}
}
#Override
public void addNotify() {
super.addNotify();
timer.start();
}
#Override
public void removeNotify() {
super.removeNotify();
timer.stop();
}
MyJPanel() {
this.setPreferredSize(new Dimension(512, 512));
}
public void add(Star star) {
stars.add(star);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (Star star : stars) {
g.setColor(star.getColor());
g.fillPolygon(star);
}
}
}
}