Hovering button causes window to close - java

I'm developing a program that's meant to open a mode-less window whenever I hover some specific component. I'm not going into details that are not necessary but basically I have a mouse listener that opens a JFrame and shows a picture. The problem is, I also want to have a button that's meant to change the picture, but whenever I hover the button, the window closes and I have no idea why.
Here's the code:
Listener call:
public class ImageAction extends FocusOwnerAction{
/**
* The user interface controller
*/
protected UIController uiController;
public ImageAction(UIController uiController) {
this.uiController = uiController;
}
public void actionPerformed(ActionEvent event) {
MouseHoverController mouse = new MouseHoverController(focusOwner, this.focusOwner.getSpreadsheet());
mouse.addMouseHoverEvent();
}
...
public class MouseHoverController {
private final JTable table;
private final Spreadsheet spread;
public MouseHoverController(JTable table, Spreadsheet spread) {
this.table = table;
this.spread = spread;
}
public void addMouseHoverEvent() {
MouseHoverEvent mouseEvent = new MouseHoverEvent(spread);
table.addMouseMotionListener((MouseMotionListener) mouseEvent);
}
}
...
public class MouseHoverEvent extends MouseMotionAdapter {
private Spreadsheet spreadsheet;
public MouseHoverEvent(Spreadsheet spreadsheet) {
this.spreadsheet = spreadsheet;
}
#Override
public void mouseMoved(MouseEvent e) {
final JTable aTable = (JTable) e.getSource();
int itsRow = aTable.rowAtPoint(e.getPoint());
int itsColumn = aTable.columnAtPoint(e.getPoint());
Cell c = this.spreadsheet.getCell(itsColumn, itsRow);
ImageCell choosedCell = (ImageCell) c.getExtension(ImageExtension.NAME);
if (choosedCell.hasImages()) {
aTable.removeMouseMotionListener(this);
final JFrame frame = new JFrame();
frame.setLayout(new GridLayout(2,1));
ImageIcon img = new ImageIcon("path.png");
Image im = img.getImage();
Image newimg = im.getScaledInstance(400, 500, java.awt.Image.SCALE_SMOOTH);
ImageIcon imgResizable = new ImageIcon(newimg);
JLabel image = new JLabel(imgResizable);
JPanel picPanel = new JPanel();
picPanel.add(image);
frame.add(picPanel);
JButton b1 = new JButton("Next");
frame.add(b1);
frame.setSize(400, 500);
// here's the part where I center the jframe on screen
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.addMouseListener(new MouseListener() {
public void mouseExited(MouseEvent e) {
frame.dispose();
MouseHoverEvent mouseEvent = new MouseHoverEvent(spreadsheet);
aTable.addMouseMotionListener((MouseMotionListener) mouseEvent);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
});
}
}
}

Related

How to change the background color of a Jbutton on click

I'm trying to change the color of a JButton when you click on it, but a blue color appears instead of the one I wrote about.
Goal: The goal is that when you click on the button the color change
I did several searches, but each time a blue font appeared.
I tried overide paintComponent, several alternatives such as this.getModel, but nothing works.
My button class:
package com.tralamy.lancherX.display;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TButton extends JButton {
private Color hoverColor = Display.LIGHT_GRAY;
private Color pressColor = Display.LIGHT_DARK;
private Color firstColor;
private Color basic;
private MouseAdapter hoverAdapter = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
basic = firstColor;
TButton.this.setBackground(hoverColor);
}
#Override
public void mouseExited(MouseEvent e) {
TButton.this.setBackground(basic);
}
};
private MouseAdapter pressAdapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
TButton.this.setBackground(pressColor);
super.mousePressed(e);
}
#Override
public void mouseReleased(MouseEvent e) {
TButton.this.setBackground(basic);
super.mouseReleased(e);
}
};
public TButton (String text){
super(text);
init();
}
public TButton (Icon icon){
super(icon);
init();
}
public TButton (){
super();
init();
}
private void init()
{
firstColor = this.getBackground();
setBorder(null);
setBorderPainted(false);
setContentAreaFilled(false);
setOpaque(false);
setFocusPainted(false);
setPressedIcon(new ImageIcon());
}
#Override
public void setBackground(Color bg) {
super.setBackground(bg);
firstColor = bg;
}
public void setHover()
{
this.addMouseListener(hoverAdapter);
}
public void removeHover()
{
this.removeMouseListener(hoverAdapter);
}
public void setPress()
{
this.addMouseListener(pressAdapter);
}
public void removePress()
{
this.removeMouseListener(pressAdapter);
}
public void setHoverColor(Color color)
{
hoverColor = color;
}
public Color getHoverColor()
{
return hoverColor;
}
public Color getPressColor() {
return pressColor;
}
public void setPressColor(Color pressColor) {
this.pressColor = pressColor;
}
}
Main menu panel:
private JPanel menuPanel() {
mp = new JPanel();
setPercentWidth(mp, 25);
mp.setBackground(LIGHT_GRAY);
mp.setLayout(new BorderLayout());
JPanel userSection = new JPanel();
userSection.setLayout(new GridBagLayout());
setPercentHeight(userSection, 5);
userSection.setPreferredSize(new Dimension(userSection.getWidth(), 0));
userSection.setBackground(LIGHT_DARK);
userIconButton.setHorizontalAlignment(SwingConstants.CENTER);
userName.setHorizontalAlignment(SwingConstants.CENTER);
userIconButton.setBorder(new EmptyBorder(0,0,0,10));
userSection.add(userIconButton);
userSection.add(userName);
menuButtons.add(new TButton("Library"));
menuButtons.add(new TButton("Store"));
menuButtons.add(new TButton("Friends"));
menuButtons.add(new TButton("News"));
JPanel menuSection = new JPanel();
menuSection.setLayout(new BoxLayout(menuSection, BoxLayout.Y_AXIS));
menuSection.setOpaque(false);
for (TButton button : menuButtons) {
button.setAlignmentX(TButton.CENTER_ALIGNMENT);
button.setFont(App.setSemiBoldNunito(48));
button.setForeground(SUPER_SUPER_LIGHT_GRAY);
button.setBackground(SUPER_LIGHT_GRAY);
button.setBorder(null);
button.setBorderPainted(true);
button.setContentAreaFilled(true);
button.setOpaque(true);
button.setHoverColor(DARK_GRAY);
button.setHover();
button.setPressColor(LIGHT_DARK);
button.setPress();
TButton marginLabel = new TButton();
marginLabel.setSize(MAIN_MENU_MARGIN, MAIN_MENU_MARGIN);
marginLabel.setMaximumSize(new Dimension(MAIN_MENU_MARGIN, MAIN_MENU_MARGIN));
marginLabel.setMinimumSize(new Dimension(MAIN_MENU_MARGIN, MAIN_MENU_MARGIN));
setPercentWidth(button, 20);
menuSection.add(marginLabel);
menuSection.add(button);
}
mp.add(menuSection);
mp.add(userSection, BorderLayout.SOUTH);
return mp;
}
And then some image:
My bug
And thank you in advance
If you want to change the background of the button with a persistent color when the user clicks on the button, then you can use setContentAreaFilled(false) on it. Then it is required to reset the opaque property to true because according to the docs of setContentAreaFilled: "This function may cause the component's opaque property to change.", for example:
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MainPersist {
private static void createAndShowGUI() {
final JButton button = new JButton("Click to change color");
button.addActionListener(e -> {
button.setContentAreaFilled(false);
button.setOpaque(true); //Reset the opacity.
button.setBackground(Color.CYAN.darker()); //Set your desired color as the background.
});
final JFrame frame = new JFrame("Button bg on click");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(MainPersist::createAndShowGUI);
}
}
Otherwise, if you want the button to only change its color when clicked and then return back to normal when released, then take a look at this question which is about exactly that. It has no accepted answers yet (it is very recent as of the time this answer itself is posted), but there is at least one/my answer (which suggests to modify the ButtonUI of the button) and there should be more answers coming I guess.

How do I get the MouseListener on a JTable working

I'm trying to get a JTable working with a MouseListener.
The code right now is a sample program for a JTable with Icons.
What I want is, that if you double click on a row, a dialog should open with informations from the whole row or just the index-number from the row.
But my problem is that the command: table.addMouseListener(this); is not working, maybe is it because of the constructor?
I tried to use a new object inside the main method and create then the MousListener.
public class TableIcon extends JPanel
{
public TableIcon()
{
Icon aboutIcon = new ImageIcon("Mypath");
Icon addIcon = new ImageIcon("Mypath");
Icon copyIcon = new ImageIcon("Mypath");
String[] columnNames = {"Picture", "Description"};
Object[][] data =
{
{aboutIcon, "Pic1"},
{addIcon, "Pic2"},
{copyIcon, "Pic3"},
};
DefaultTableModel model = new DefaultTableModel(data,columnNames)
{
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
public boolean isCellEditable(int row, int column)
{
return false;
}
};
JTable table = new JTable( model );
table.setPreferredScrollableViewportSize
(table.getPreferredSize());
// ################ MyError #########
table.addMouseListener(this); // Error
// ##################################
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
}
private static void createAndShowGUI()
{
TableIcon test = new TableIcon();
JFrame frame = new JFrame("Table Icon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(test);
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
public void mouseClicked(MouseEvent e)
{
System.out.println("clicked");
}
}
In this code I expect a print with"clicked" but all I get is this error
My Error
TableIcon cannot be cast to java.awt.event.MouseListener
Try using Adapter class:
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
//Code for handling the double click event
}
}
});
You refer to this which is class TableIcon and it does not implement interface MouseListener, but method addMouseListener() expects it.
public void addMouseListener(MouseListener l)
If you want to go with approach of TableIcon class acting as event handler as well, then add implementation for the MouseListener interface.
public class TableIcon extends JPanel implements MouseListener {
...
public void mouseClicked(MouseEvent e) {
// code for handling of the click event
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}

Why Won't the Java Component JPanel won't disapear?

I was trying to set up something with the JMenu where you can switch between "pages" (JPanels) but I ran into an issue where one would not disappear after trying a few methods online. What is the error I am making?
code:
public class Window {
public static boolean NewTerrainCamPos = false;
public static String textVal;
public static String textVal2;
public static String resiveTex;
public static String resiveTex2;
public static final int Width = 1000;
public static final int Height = 720;
public static final int FPS_CAP = 120;
private static long lastFrameTime;
private static float delta;
public void createDisplay(){
ContextAttribs attribs = new ContextAttribs(3,2).withForwardCompatible(true).withProfileCore(true);
try {
Canvas openglSurface = new Canvas();
JFrame frame = new JFrame();
JPanel game = new JPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
//..............Menu Bar...............
JMenuBar menuBar = new JMenuBar();
JMenu terrain = new JMenu("Terrain");
JMenu Home = new JMenu("Home");
menuBar.add(Home);
menuBar.add(terrain);
JMenuItem newTerrain = new JMenuItem("add Terrain");
JMenuItem editTerrain = new JMenuItem("Edit Terrain");
JMenuItem editTexture = new JMenuItem("Edit Texture");
terrain.add(newTerrain);
terrain.add(editTerrain);
terrain.add(editTexture);
frame.setJMenuBar(menuBar);
//......................................................
newTerrain.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewTerrainCamPos = true;
JFrame frame2 = new JFrame();
frame2.setVisible(true);
frame2.setSize(300, 300);
//...............................
GridLayout experimentLayout = new GridLayout(3,2);
frame2.setLayout(experimentLayout);
//.....................................
JLabel xCord = new JLabel("XCoords: ");
JLabel zCord = new JLabel("ZCoords: ");
JTextField text = new JTextField();
JTextField text2 = new JTextField();
resiveTex2 = text2.getText();
text.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
resiveTex = text.getText();
}
#Override
public void removeUpdate(DocumentEvent de) {
resiveTex = text.getText();
}
#Override
public void changedUpdate(DocumentEvent de) {
//plain text components don't fire these events
}
});
text2.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent de) {
resiveTex2 = text2.getText();
}
#Override
public void removeUpdate(DocumentEvent de) {
resiveTex2 = text2.getText();
}
#Override
public void changedUpdate(DocumentEvent de) {
//plain text components don't fire these events
}
});
JButton createTerrain = new JButton("CreateTerrain");
createTerrain.addActionListener(new ActionListener(){
TIDF terrainFileID;
public void actionPerformed(ActionEvent a){
NewTerrainCamPos = false;
textVal = text.getText();
textVal2 = text2.getText();
TIDF load = new TIDF();
load.terrainIDFile();
}
});
frame2.add(xCord);
frame2.add(text);
frame2.add(zCord);
frame2.add(text2);
frame2.add(createTerrain);
}
});
editTerrain.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JFrame frame3 = new JFrame();
frame3.setVisible(true);
frame3.setSize(300, 300);
//......................................
GridLayout experimentLayout = new GridLayout(3,2);
frame3.setLayout(experimentLayout);
//......................................
JButton select = new JButton("Select");
String terrainLocList[] =
{
"Item 1",
"Item 2",
"Item 3",
"Item 4"
};
JList list = new JList(terrainLocList);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setVisibleRowCount(-1);
frame3.add(list);
frame3.add(select);
}
});
editTexture.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
frame.remove(MainPage());
frame.add(TextureEditor());
frame.revalidate();
}
});
//.........................................
frame.add(MainPage());
frame.add(game);
frame.setSize(1200, 1200);
frame.setVisible(true);
game.add(openglSurface);
game.setBounds(0, 266, 1000, 720);
openglSurface.setSize(1000, 720);
Display.setParent(openglSurface);
Display.setDisplayMode(new DisplayMode(Width, Height));
Display.create(new PixelFormat(), attribs);
frame.setTitle("Game editor 0.3");
} catch (LWJGLException e) {
e.printStackTrace();
}
GL11.glViewport(0, 0, Width, Height);
lastFrameTime = getCurrentTime();
}
public Component MainPage(){
JPanel Main = new JPanel();
Main.setBounds(400, 0, 500, 200);
Label Welcome = new Label("Welcome to: Game Editor Version 0.3");
Welcome.setFont(new Font("Monotype Corsiva",10,22));
Main.add(Welcome);
return Main;
}
public Component TextureEditor(){
JPanel TextureLayoutLook = new JPanel();
TextureLayoutLook.setBounds(60, 0, 200, 200);
Label editorVersion = new Label("Terrain Texture Editor: 0.1");
TextureLayoutLook.add(editorVersion);
return TextureLayoutLook;
}
public static boolean Returnboolean(){
return NewTerrainCamPos;
}
public static String getTex1() {
return textVal;
}
public static String getTex2(){
return textVal2;
}
public static String getTexupdate(){
return resiveTex;
}
public static String getTexupdate2(){
return resiveTex2;
}
public static void updateDisplay(){
Display.sync(FPS_CAP);
Display.update();
long currentFrameTime = getCurrentTime();
delta = (currentFrameTime - lastFrameTime)/1000f;
lastFrameTime = currentFrameTime;
}
public static float getFrameTimeSeconds(){
return delta;
}
public static void closeDisplay(){
Display.destroy();
}
private static long getCurrentTime(){
return Sys.getTime()*1000/Sys.getTimerResolution();
}
}
frame.add(MainPage());
This line builds a brand new "main page" JPanel, and adds it the the JFrame.
frame.remove(MainPage());
This line of code creates a brand new "main page" JPanel, which has never been added to the JFrame, and attempts to remove it.
This new panel can't be removed, because it was never added. You need to retain a reference to the original panel, and remove that.
JPanel main_page = MainPage();
frame.add(main_page);
//...
frame.remove(main_page);
Note: This main_page could be re-added at a future time without needing to recreate it. Just call frame.add(main_page); again. But really, you want to use the card layout manager.

JMenuBar repaints my JPanel

I am programming a small paint application, the problem is, when I clic on my Menu and then move the mouse out and clic on the panel to continiue painting, the panel erases everything I painted and changes the background too ... here's my code :
Frame's Code :
public class Ardoise extends JFrame {
private JMenuBar menu = new JMenuBar();
private JToolBar toolbar = new JToolBar();
private JMenu file = new JMenu("Fichier");
private JMenu edit = new JMenu("Edition");
private JMenu about = new JMenu("About");
private JMenu shape = new JMenu("Forme du curseur");
private JMenu color = new JMenu("Couleur du curseur");
private JMenuItem clear = new JMenuItem("Effacer");
private JMenuItem quit = new JMenuItem("Quitter");
private JMenuItem rond = new JMenuItem("Rond");
private JMenuItem carre = new JMenuItem("Carre");
private JMenuItem rouge = new JMenuItem("Rouge");
private JMenuItem bleu = new JMenuItem("Bleu");
private JMenuItem noir = new JMenuItem("Noir");
private JButton rougeButton = new JButton(new ImageIcon("rouge.jpg"));
private JButton bleuButton = new JButton(new ImageIcon("bleu.jpg"));
private JButton noirButton = new JButton(new ImageIcon("noir.jpg"));
private JButton formecarreeButton = new JButton(new ImageIcon("formecarree.png"));
private JButton formerondeButton = new JButton(new ImageIcon("formeronde.png"));
private JPanel container = new JPanel();
private Panneau pan = new Panneau();
private ColorListener cListener = new ColorListener();
public Ardoise(){
this.setTitle("Paint");
this.setSize(700,500);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
initComposants();
this.setVisible(true);
}
private void initComposants(){
file.add(clear);
file.addSeparator();
file.add(quit);
file.setMnemonic('F');
clear.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,KeyEvent.CTRL_DOWN_MASK));
quit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,KeyEvent.CTRL_DOWN_MASK));
shape.add(rond);
shape.add(carre);
color.add(rouge);
color.add(bleu);
color.add(noir);
edit.add(shape);
edit.add(color);
edit.setMnemonic('E');
menu.add(file);
menu.add(edit);
toolbar.add(formecarreeButton);
toolbar.add(formerondeButton);
toolbar.addSeparator();
toolbar.add(noirButton);
toolbar.add(rougeButton);
toolbar.add(bleuButton);
pan.addMouseMotionListener(new PaintListener1());
pan.addMouseListener(new PaintListener2());
clear.addActionListener(new ClearListener());
rougeButton.addActionListener(cListener);
bleuButton.addActionListener(cListener);
noirButton.addActionListener(cListener);
container.setLayout(new BorderLayout());
container.add(toolbar,BorderLayout.NORTH);
container.add(pan,BorderLayout.CENTER);
this.setContentPane(container);
this.setJMenuBar(menu);
}
class PaintListener1 implements MouseMotionListener{
public void mouseDragged(MouseEvent e) {
pan.setx(e.getX());
pan.sety(e.getY());
pan.repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
class PaintListener2 implements MouseListener{
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
pan.setx(e.getX());
pan.sety(e.getY());
pan.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
class ClearListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
pan.setClean(true);
pan.repaint();
}
}
class ColorListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getSource() == rougeButton)
pan.setColor(Color.red);
if(e.getSource() == bleuButton)
pan.setColor(Color.blue);
if(e.getSource() == noirButton)
pan.setColor(Color.black);
}
}
}
Panel's Code :
public class Panneau extends JPanel{
private int mousex=0,mousey=0;
private boolean clean=true;;
private Color color= Color.black;
public void paintComponent(Graphics g){
g.setColor(color);
draw(g);
if(clean){
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
clean=false;
}
}
private void draw(Graphics g){
g.fillOval(mousex, mousey, 10, 10);
}
public void setx(int x){
this.mousex=x;
}
public void sety(int y){
this.mousey=y;
}
public void setClean(boolean c){
this.clean = c;
}
public void setColor(Color c){
this.color=c;
}
}
the panel erases everything I painted and changes the background too ... here's my code :
You need to keep track of everything that has been painted and then repaint everything again.
See Custom Painting Approaches for the two common ways to do this:
Use a ArrayList to keep track of objects painted
Use a BufferedImage

JFrame.setVisible(false) and Robot.createScreenCapture timing

I'm trying to capture the screen without including my application's window. To do this I first call setVisible(false), then I call the createScreenCapture method, and finally I call setVisible(true). This isn't working however and I'm still getting my applications window in the screen capture. If I add a call to sleep this seems to resolve the issue, but I know this is bad practice. What is the right way to do this?
Code:
setVisible(false);
BufferedImage screen = robot.createScreenCapture(rectScreenSize);
setVisible(true);
Have you tried to use SwingUtilities.invokeLater() and run the capture inside of the runnable passed as an argument? My guess is that the repaint performed to remove your application is performed right after the end of the current event in the AWT-EventQueue and thus invoking the call immediately still captures your window. Invoking the createCapture in a delayed event through invokeLater should fix this.
you have to delay this action by implements Swing Timer, for example
import javax.imageio.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
public class CaptureScreen implements ActionListener {
private JFrame f = new JFrame("Screen Capture");
private JPanel pane = new JPanel();
private JButton capture = new JButton("Capture");
private JDialog d = new JDialog();
private JScrollPane scrollPane = new JScrollPane();
private JLabel l = new JLabel();
private Point location;
private Timer timer1;
public CaptureScreen() {
capture.setActionCommand("CaptureScreen");
capture.setFocusPainted(false);
capture.addActionListener(this);
capture.setPreferredSize(new Dimension(300, 50));
pane.add(capture);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(pane);
f.setLocation(100, 100);
f.pack();
f.setVisible(true);
createPicContainer();
startTimer();
}
private void createPicContainer() {
l.setPreferredSize(new Dimension(700, 500));
scrollPane = new JScrollPane(l,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBackground(Color.white);
scrollPane.getViewport().setBackground(Color.white);
d.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
d.add(scrollPane);
d.pack();
d.setVisible(false);
d.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
f.setVisible(true);
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
}
private void startTimer() {
timer1 = new Timer(1000, new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
capture.doClick();
f.setVisible(false);
}
});
}
});
timer1.setDelay(500);
timer1.setRepeats(false);
timer1.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("CaptureScreen")) {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // gets the screen size
Robot r;
BufferedImage bI;
try {
r = new Robot(); // creates robot not sure exactly how it works
Thread.sleep(1000); // waits 1 second before capture
bI = r.createScreenCapture(new Rectangle(dim)); // tells robot to capture the screen
showPic(bI);
saveImage(bI);
} catch (AWTException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}
}
private void saveImage(BufferedImage bI) {
try {
ImageIO.write(bI, "JPG", new File("screenShot.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
private void showPic(BufferedImage bI) {
ImageIcon pic = new ImageIcon(bI);
l.setIcon(pic);
l.revalidate();
l.repaint();
d.setVisible(false);
//location = f.getLocationOnScreen();
//int x = location.x;
//int y = location.y;
//d.setLocation(x, y + f.getHeight());
d.setLocation(150, 150);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
d.setVisible(true);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
CaptureScreen cs = new CaptureScreen();
}
});
}
}

Categories