i want to make a screenshot of the panel that i have created and the code is given below.
Can any body please tell me why i am not getting.thanks
public static final void makeScreenshot(JFrame argFrame)
{
Rectangle rec = argFrame.getBounds();
BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
argFrame.paint(bufferedImage.getGraphics());
try
{
// Create temp file.
File temp = File.createTempFile("C:\\Documents and Settings\\SriHari\\My Documents\\NetBeansProjects\\test\\src\\testscreenshot", ".jpg");
// Use the ImageIO API to write the bufferedImage to a temporary file
ImageIO.write(bufferedImage, "jpg", temp);
//temp.deleteOnExit();
}
catch (IOException ioe) {}
} //
public static void main(String args[])
{
TimeTableGraphicsRunner ts= new TimeTableGraphicsRunner();
for(long i=1;i<1000000000;i++);
ts.makeScreenshot(jf);
System.out.println("hi");
}
The following works for me:
public static void main (String [] args)
{
final JFrame frame = new JFrame ();
JButton button = new JButton (new AbstractAction ("Make Screenshot!")
{
#Override
public void actionPerformed (ActionEvent e)
{
Dimension size = frame.getSize ();
BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics ();
frame.paint (g);
g.dispose ();
try
{
ImageIO.write (img, "png", new File ("screenshot.png"));
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
});
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane ().setLayout (new BorderLayout ());
frame.getContentPane ().add (button, BorderLayout.CENTER);
frame.pack ();
frame.setVisible (true);
}
It does not render window title and border because this is handled by OS, not Swing.
You could try using something like Robot#createScreenCapture
If you don't want to capture the whole screen, you can use Component#getLocationOnScreen to find the position of the component on the screen instead...
public class CaptureScreen {
public static void main(String[] args) {
new CaptureScreen();
}
public CaptureScreen() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(new JLabel("Smile :D"), gbc);
JButton capture = new JButton("Click");
capture.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
Robot robot = new Robot();
Rectangle bounds = frame.getBounds();
bounds.x -= 1;
bounds.y -= 1;
bounds.width += 2;
bounds.height += 2;
BufferedImage snapShot = robot.createScreenCapture(bounds);
ImageIO.write(snapShot, "png", new File("Snapshot.png"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
frame.add(capture, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Example using Component#getLocationOnScreen
public class CaptureScreen {
public static void main(String[] args) {
new CaptureScreen();
}
public CaptureScreen() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(new JLabel("Smile :D"), gbc);
JButton capture = new JButton("Click");
capture.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
Robot robot = new Robot();
Container panel = frame.getContentPane();
Point pos = panel.getLocationOnScreen();
Rectangle bounds = panel.getBounds();
bounds.x = pos.x;
bounds.y = pos.y;
bounds.x -= 1;
bounds.y -= 1;
bounds.width += 2;
bounds.height += 2;
BufferedImage snapShot = robot.createScreenCapture(bounds);
ImageIO.write(snapShot, "png", new File("Snapshot.png"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
frame.add(capture, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Another Example show Component#getLocationOnScreen
The main reason 3 of the image are the same, is because the example dumps the root pane, layerd pane and content pane...
public class CaptureScreen {
public static void main(String[] args) {
new CaptureScreen();
}
public void save(Component comp, File file) {
if (comp.isVisible()) {
try {
System.out.println(comp);
Robot robot = new Robot();
Rectangle bounds = new Rectangle(comp.getLocationOnScreen(), comp.getSize());
bounds.x -= 1;
bounds.y -= 1;
bounds.width += 2;
bounds.height += 2;
BufferedImage snapShot = robot.createScreenCapture(bounds);
ImageIO.write(snapShot, "png", file);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private int layer;
public void capture(Container container) {
layer = 1;
captureLayers(container);
}
public void captureLayers(Container container) {
save(container, new File("SnapShot-" + layer + "-0.png"));
int thisLayer = layer;
int count = 1;
for (Component comp : container.getComponents()) {
if (comp instanceof Container) {
layer++;
captureLayers((Container) comp);
} else {
save(comp, new File("SnapShot-" + thisLayer + "-" + count + ".png"));
count++;
}
}
}
public CaptureScreen() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(new JLabel("Smile :D"), gbc);
JButton capture = new JButton("Click");
capture.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
capture(frame);
}
});
frame.add(capture, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Related
Is there any way to create a feature which allows a user to toggle screen magnification if they are visually impaired.
I'm asking in context of a program like eclipse, where a user who is visually impaired can toggle on and off a feature which magnifies the text, icons and navigation bar.
I use this short code for a general magnifier when cropping images.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
class ZoomOnMouse {
Robot robot;
int zoomFactor = 2;
PointerInfo pi;
JPanel gui;
JLabel output;
Timer t;
public ZoomOnMouse() throws AWTException {
robot = new Robot();
gui = new JPanel(new BorderLayout(2, 2));
output = new JLabel("Point at something to see it zoomed!");
gui.add(output, BorderLayout.PAGE_END);
final int size = 256;
final BufferedImage bi = new BufferedImage(
size, size, BufferedImage.TYPE_INT_RGB);
final JLabel zoomLabel = new JLabel(new ImageIcon(bi));
gui.add(zoomLabel, BorderLayout.CENTER);
MouseListener factorListener = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (zoomFactor == 2) {
zoomFactor = 4;
} else if (zoomFactor == 4) {
zoomFactor = 8;
} else if (zoomFactor == 8) {
zoomFactor = 2;
}
showInfo();
}
};
zoomLabel.addMouseListener(factorListener);
ActionListener zoomListener = (ActionEvent e) -> {
pi = MouseInfo.getPointerInfo();
Point p = pi.getLocation();
Rectangle r = new Rectangle(
p.x - (size / (2 * zoomFactor)),
p.y - (size / (2 * zoomFactor)),
(size / zoomFactor),
(size / zoomFactor));
BufferedImage temp = robot.createScreenCapture(r);
Graphics g = bi.getGraphics();
g.drawImage(temp, 0, 0, size, size, null);
g.setColor(new Color(255,0,0,128));
int x = (size/2)-1;
int y = (size/2)-1;
g.drawLine(0,y,size,y);
g.drawLine(x,0,x,size);
g.dispose();
zoomLabel.repaint();
showInfo();
};
t = new Timer(40, zoomListener);
t.start();
}
public void stop() {
t.stop();
}
public Component getGui() {
return gui;
}
public void showInfo() {
pi = MouseInfo.getPointerInfo();
output.setText("Zoom: " + zoomFactor + " Point: " + pi.getLocation());
}
public static void main(String[] args) {
Runnable r = () -> {
try {
final ZoomOnMouse zm = new ZoomOnMouse();
final JFrame f = new JFrame("Mouse Zoom");
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.add(zm.getGui());
f.setResizable(false);
f.pack();
f.setLocationByPlatform(true);
f.setAlwaysOnTop(true);
f.setVisible(true);
WindowListener closeListener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
zm.stop();
f.dispose();
}
};
f.addWindowListener(closeListener);
} catch (AWTException e) {
e.printStackTrace();
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
I am running the following code and i am getting a cannot find symbol error at resultPane.setResult(0); am i putting the new handlerclass in wrong spot? ive tried putting
it in different spots but nothing
public class MovingLabel {
public static void main(String[] args) {
new MovingLabel();
}
public MovingLabel() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
ResultPane resultPane = new ResultPane();
JFrame frame = new JFrame("Testing");
frame.setGlassPane(resultPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new NewPane(resultPane));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setBounds(500,300,200,200);
}
});
}
public class ResultPane extends JPanel {
private JLabel result;
private Timer timer;
private int xDelta = (Math.random() > 0.5) ? 1 : -1;
private int yDelta = (Math.random() > 0.5) ? 1 : -1;
public ResultPane() {
setOpaque(false);
setLayout(null);
result = new JLabel();
Font font = result.getFont();
font = font.deriveFont(Font.BOLD, 26f);
result.setFont(font);
add(result);
HandlerClass handler = new HandlerClass();
result.addMouseListener(handler);
result.addMouseMotionListener(handler);
timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Point point = result.getLocation();
point.x += xDelta;
point.y += yDelta;
if (point.x < 0) {
point.x = 0;
xDelta *= -1;
} else if (point.x + result.getWidth() > getWidth()) {
point.x = getWidth() - result.getWidth();
xDelta *= -1;
}
if (point.y < 0) {
point.y = 0;
yDelta *= -1;
} else if (point.y + result.getHeight() > getHeight()) {
point.y = getHeight() - result.getHeight();
yDelta *= -1;
}
result.setLocation(point);
repaint();
}
});
timer.start();
}
public void setResult(Number number) {
result.setText(NumberFormat.getNumberInstance().format(number));
result.setSize(result.getPreferredSize());
setVisible(true);
}
}
public class NewPane extends JPanel {
private final ResultPane resultPane;
public NewPane(ResultPane resultPane) {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
this.resultPane = resultPane;
JPanel buttons = new JPanel();
buttons.add(new JButton(new LabelAction()));
add(buttons, gbc);
}
public class LabelAction extends AbstractAction {
LabelAction() {
putValue(NAME, "Label");
}
#Override
public void actionPerformed(ActionEvent e) {
resultPane.setResult(123);
}
}
}
private class HandlerClass implements MouseListener, MouseMotionListener {
public void mouseClicked(MouseEvent event) {
resultPane.setResult(0);
}
public void mouseReleased(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mouseEntered(MouseEvent event) {
}
public void mouseMoved(MouseEvent event) {
}
public void mouseDragged(MouseEvent event){
}
}
}
resultPane is only defined in the scope of run(). If you want HandlerClass to have access to it you need to give it a definition.
Make resultPane instance variable. You can't access local variable outside the method.
class MovingLabel {
private ResultPane resultPane; // Declare it as instance variable
public MovingLabel() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
...
resultPane = new ResultPane(); // Initialize the instance variable
...
}
}
}
It's a nice program.
Personally, I put every class in a new file. For me it easier to understand scope. The problem is indeed that the reference in HandlerClass is outside of it's declaration in the other classes.
I'm trying to create a hold button on Java for my bandit machine, when pressed it will hold that image and the other 2 images will keep spinning. Anyone know the code to allow that to happen?
if (e.getSource()== btnaddcash){
txtbalance.setForeground(Color.red);
cash = cash + 100;
txtbalance.setText(cash + "");
if (e.getSource() == btnpic1){
The basic concept is, you want to spin an image (or take some action) while the button is "armed".
A way by which you can achieve this is to add a ChangeListener to the button and monitor the ButtonModel#isArmed state.
public class ChangeButton {
public static void main(String[] args) {
new ChangeButton();
}
public ChangeButton() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new SlotPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class SlotPaneextends JPanel {
private SpinPane spinPane;
private JButton button;
public SlotPane() {
spinPane = new SpinPane();
button = new JButton("Press");
// I've attached directly to the model, I don't
// think this is required, simply attaching a change
// listener to the button achieve the same result.
button.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
spinPane.setSpinning(button.getModel().isArmed());
}
});
setLayout(new BorderLayout());
add(spinPane);
add(button, BorderLayout.SOUTH);
}
}
public class SpinPane extends JPanel {
private BufferedImage mole;
private Timer timer;
private float angel = 0;
public SpinPane() {
try {
mole = ImageIO.read(new File("mole.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
timer = new Timer(15, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
angel += 15;
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
}
#Override
public Dimension getPreferredSize() {
return mole == null ? super.getPreferredSize() : new Dimension(mole.getWidth(), mole.getHeight());
}
public void setSpinning(boolean spinning) {
if (spinning) {
if (!timer.isRunning()) {
timer.restart();
}
} else {
timer.stop();
}
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (mole != null) {
int x = (getWidth() - mole.getWidth()) / 2;
int y = (getHeight() - mole.getHeight()) / 2;
Graphics2D g2d = (Graphics2D) g.create();
g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angel), getWidth() / 2, getHeight() / 2));
g2d.drawImage(mole, x, y, this);
g2d.dispose();
}
}
}
}
I have a program, with JFrame and JInternalFrames inside. So, when I try to set background with this code:
BufferedImage myImage;
myImage = ImageIO.read(new File("C:/5/JavaLibrary2/background.jpg"));
ImagePanel Image = new ImagePanel(myImage);
frame.setContentPane(Image);
My JInternalFrames just gone. So, see a short video with debug
frame.setContentPane(Image); just delete my JInternal windows.
I have no issue.
I've used both a JLabel and custom painting routines.
I've created and setup the internal frames BEFORE adding them to the desktop,
I've added the internal frame to the desktop and THEN changed their content panes as well as throwing the update to the end of the EDT to ensure that the main frame is visible.
The problem must be in some part of your code you're not showing us.
public class TestInternalFrame {
public static void main(String[] args) {
new TestInternalFrame();
}
public TestInternalFrame() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JDesktopPane desktop = new JDesktopPane();
final JInternalFrame frame1 = new JInternalFrame("Image on Label");
// frame1.setContentPane(new LabelImagePane());
// frame1.pack();
// frame1.setLocation(0, 0);
frame1.setVisible(true);
desktop.add(frame1);
final JInternalFrame frame2 = new JInternalFrame("Painted Image");
// frame2.setContentPane(new ImagePane());
// frame2.pack();
// frame2.setLocation(frame1.getWidth(), 0);
frame2.setVisible(true);
desktop.add(frame2);
JFrame frame = new JFrame("I Haz Images");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(desktop);
frame.setSize(800, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame1.setContentPane(new LabelImagePane());
frame1.pack();
frame1.setLocation(0, 0);
frame2.setContentPane(new ImagePane());
frame2.pack();
frame2.setLocation(frame1.getWidth(), 0);
}
});
}
});
}
public class LabelImagePane extends JPanel {
public LabelImagePane() {
setLayout(new BorderLayout());
JLabel label = new JLabel();
add(label);
try {
label.setIcon(new ImageIcon(ImageIO.read(new File("..."))));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ImagePane extends JPanel {
private BufferedImage image;
public ImagePane() {
try {
image = ImageIO.read(new File("..."));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int x = (getWidth() - image.getWidth()) / 2;
int y = (getHeight() - image.getHeight()) / 2;
g.drawImage(image, x, y, this);
}
}
}
}
thank you so much but I need Listener methods and solved it now.. But now I cant see the buttons until I hover on them! I think its just a small mistake but I couldnt figure it out!! Now my code is like below...
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class PaintMain extends JFrame
{
JPanel colorPanel = new JPanel();
JPanel drawPanel = new JPanel();
JPanel selectPanel = new JPanel();
JButton[][] randomColors = new JButton[5][5];
Color selectedColor = Color.BLACK;
Random colorGenerator = new Random();
int curx = drawPanel.getX();
int cury = drawPanel.getY();
public PaintMain()
{
setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
colorPanel.setLayout(new GridLayout(5,5));
drawPanel.setLayout(new BorderLayout());
drawPanel.setBackground(Color.WHITE);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
randomColors[i][j]=new JButton();
randomColors[i][j].setBackground(getRandomColor());
randomColors[i][j].addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if( e.getSource() instanceof JButton)
{
selectedColor=((JButton)e.getSource()).getBackground();
System.out.println(selectedColor);
}
}
});
colorPanel.add(randomColors[i][j]);
}
}
this.addMouseMotionListener(new MouseLsnr());
add(colorPanel, BorderLayout.WEST);
add(drawPanel, BorderLayout.CENTER);
setVisible(true);
pack();
}
public Color getRandomColor()
{
return new Color(colorGenerator.nextInt(256), colorGenerator.nextInt(256), colorGenerator.nextInt(256));
}
public static void main(String[] args)
{
new PaintMain();
}
public void paint(Graphics g)
{
//super.paint(g);
g.setColor(selectedColor);
g.drawRect(curx, cury, 2, 1);
}
class MouseLsnr implements MouseMotionListener
{
public void mouseDragged(MouseEvent arg0) {
System.out.println(arg0.getX()+":"+arg0.getY());
curx=arg0.getX();
cury=arg0.getY();
repaint();
}
public void mouseMoved(MouseEvent arg0)
{
}
}
}
You'll want to take a closer look at Custom Painting
The you might want to take a read through How to Write a Mouse Listener
public class RandomColorPane {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new RandomColorPane();
}
public RandomColorPane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
JPanel colorPanel = new JPanel();
JPanel drawPanel = new DrawPane();
JPanel selectPanel = new JPanel();
JPanel[][] randomColors = new JPanel[5][5];
Color selectedColor = Color.BLACK;
Random colorGenerator = new Random();
int curx = drawPanel.getX();
int cury = drawPanel.getY();
public MainPane() {
setLayout(new BorderLayout());
colorPanel.setLayout(new GridLayout(5, 5));
drawPanel.setLayout(new BorderLayout());
drawPanel.setBackground(Color.WHITE);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
randomColors[i][j] = new JPanel();
randomColors[i][j].setPreferredSize(new Dimension(25, 25));
randomColors[i][j].setBackground(getRandomColor());
// randomColors[i][j].addActionListener(new ActionListener() {
// #Override
// public void actionPerformed(ActionEvent e) {
// if (e.getSource() instanceof JButton) {
// selectedColor = ((JButton) e.getSource()).getBackground();
// drawPanel.setForeground(selectedColor);
// drawPanel.repaint();
// }
// }
//
// });
randomColors[i][j].addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
drawPanel.setForeground(((JPanel)e.getSource()).getBackground());
drawPanel.repaint();
}
});
colorPanel.add(randomColors[i][j]);
}
}
add(colorPanel, BorderLayout.WEST);
add(drawPanel, BorderLayout.CENTER);
}
public Color getRandomColor() {
return new Color(colorGenerator.nextInt(256), colorGenerator.nextInt(256), colorGenerator.nextInt(256));
}
}
public class DrawPane extends JPanel {
#Override
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = (getWidth() - 10) / 2;
int y = (getHeight() - 10) / 2;
g.setColor(getForeground());
g.fillRect(x, y, 20, 20);
}
}
}