I'm making a screenshot program so when you press the screenshot button, a JMessageDial pops up and prompts you with your image, it the tells you to drag your mouse and make a box around the area that you want to take a screenshot of. I can't seem to find how to get the image inside the box when the user clicks okay.
So what I need help with is getting the image inside of the rectangle the user "draws" with his mouse, and store that in a variable.
Here is the specific code:
public void selectArea(final BufferedImage screen) throws Exception {
final BufferedImage screenCopy = new BufferedImage(screen.getWidth(), screen.getHeight(), screen.getType());
final JLabel screenLabel = new JLabel(new ImageIcon(screenCopy));
JScrollPane screenScroll = new JScrollPane(screenLabel);
screenScroll.setPreferredSize(new Dimension((int)(screen.getWidth()/2), (int)(screen.getHeight()/2)));
JPanel panel = new JPanel(new BorderLayout());
panel.add(screenScroll, BorderLayout.CENTER);
final JLabel selectionLabel = new JLabel("Draw a rectangle");
panel.add(selectionLabel, BorderLayout.SOUTH);
repaint(screen, screenCopy);
screenLabel.repaint();
screenLabel.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent me) {
start = me.getPoint();
repaint(screen, screenCopy);
selectionLabel.setText("Start Point: " + start);
screenLabel.repaint();
}
#Override
public void mouseDragged(MouseEvent me) {
end = me.getPoint();
captureRect = new Rectangle(start, new Dimension(end.x-start.x, end.y-start.y));
try {
paintFinalImage(new BufferedImage((int)screenCopy.getGraphics().getClipBounds(captureRect).getWidth()+1,
(int)screenCopy.getGraphics().getClipBounds(captureRect).getHeight()+1, screen.getType()));
} catch (Exception e) {
e.printStackTrace();
}
repaint(screen, screenCopy);
screenLabel.repaint();
selectionLabel.setText("Rectangle: " + captureRect);
}
});
JOptionPane.showMessageDialog(null, panel, "Select your image", JOptionPane.OK_OPTION, new ImageIcon(""));
uploadImage(screenShot);
System.out.println("Final rectangle: " + screenCopy.getGraphics().getClipBounds(captureRect));
}
And this is the full class if you need it:
package com.screencapture;
import java.awt.*;
public class Main implements ActionListener, ItemListener, KeyListener, NativeKeyListener {
private final Image icon = Toolkit.getDefaultToolkit().getImage("./data/icon.gif");
private final TrayIcon trayIcon = new TrayIcon(icon, "Screen Snapper");
private JFrame frame;
private Rectangle captureRect;
private JComboBox<String> imageType;
private boolean hideWhenMinimized = false;
private final String API_KEY = "b84e430b4a65d16a6955358141f21a61";
private static Robot robot;
private BufferedImage screenShot;
private Point end;
private Point start;
public static void main(String[] args) throws Exception {
robot = new Robot();
new Main().start();
}
public void start() throws Exception {
GlobalScreen.getInstance().registerNativeHook();
GlobalScreen.getInstance().addNativeKeyListener(this);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
frame = new JFrame("White power!");
frame.setPreferredSize(new Dimension(250, 250));
frame.getContentPane().setLayout(null);
frame.setIconImage(icon);
frame.addKeyListener(this);
frame.addWindowListener(new WindowListener() {
#Override
public void windowOpened(WindowEvent e) {}
#Override
public void windowClosing(WindowEvent e) {}
#Override
public void windowClosed(WindowEvent e) {}
#Override
public void windowIconified(WindowEvent e) {
if (hideWhenMinimized)
frame.setVisible(false);
}
#Override
public void windowDeiconified(WindowEvent e) {}
#Override
public void windowActivated(WindowEvent e) {}
#Override
public void windowDeactivated(WindowEvent e) {}
});
JLabel lblImageType = new JLabel("Image Format:");
lblImageType.setBounds(10, 11, 90, 14);
frame.getContentPane().add(lblImageType);
String[] imageTypes = {"PNG", "JPG"};
imageType = new JComboBox<String>(imageTypes);
imageType.setBounds(106, 8, 51, 20);
frame.getContentPane().add(imageType);
JButton btnTakeScreenShot = new JButton("ScreenShot");
btnTakeScreenShot.setBounds(24, 69, 115, 23);
frame.getContentPane().add(btnTakeScreenShot);
btnTakeScreenShot.addActionListener(this);
setTrayIcon();
frame.pack();
frame.setVisible(true);
}
public void setTrayIcon() throws AWTException {
CheckboxMenuItem startup = new CheckboxMenuItem("Run on start-up");
CheckboxMenuItem hide = new CheckboxMenuItem("Hide when minimized");
String[] popupMenuOptions = {"Open", "Exit"};
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
trayIcon.setImageAutoSize(true);
PopupMenu popupMenu = new PopupMenu();
for (String option : popupMenuOptions) {
if (option == "Exit") {
popupMenu.add(startup);
popupMenu.add(hide);
popupMenu.add(option);
} else {
popupMenu.add(option);
}
}
trayIcon.setPopupMenu(popupMenu);
popupMenu.addActionListener(this);
startup.addItemListener(this);
hide.addItemListener(this);
trayIcon.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(true);
}
});
tray.add(trayIcon);
}
}
public void selectArea(final BufferedImage screen) throws Exception {
final BufferedImage screenCopy = new BufferedImage(screen.getWidth(), screen.getHeight(), screen.getType());
final JLabel screenLabel = new JLabel(new ImageIcon(screenCopy));
JScrollPane screenScroll = new JScrollPane(screenLabel);
screenScroll.setPreferredSize(new Dimension((int)(screen.getWidth()/2), (int)(screen.getHeight()/2)));
JPanel panel = new JPanel(new BorderLayout());
panel.add(screenScroll, BorderLayout.CENTER);
final JLabel selectionLabel = new JLabel("Draw a rectangle");
panel.add(selectionLabel, BorderLayout.SOUTH);
repaint(screen, screenCopy);
screenLabel.repaint();
screenLabel.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent me) {
start = me.getPoint();
repaint(screen, screenCopy);
selectionLabel.setText("Start Point: " + start);
screenLabel.repaint();
}
#Override
public void mouseDragged(MouseEvent me) {
end = me.getPoint();
captureRect = new Rectangle(start, new Dimension(end.x-start.x, end.y-start.y));
try {
paintFinalImage(new BufferedImage((int)screenCopy.getGraphics().getClipBounds(captureRect).getWidth()+1,
(int)screenCopy.getGraphics().getClipBounds(captureRect).getHeight()+1, screen.getType()));
} catch (Exception e) {
e.printStackTrace();
}
repaint(screen, screenCopy);
screenLabel.repaint();
selectionLabel.setText("Rectangle: " + captureRect);
}
});
JOptionPane.showMessageDialog(null, panel, "Select your image", JOptionPane.OK_OPTION, new ImageIcon(""));
uploadImage(screenShot);
System.out.println("Final rectangle: " + screenCopy.getGraphics().getClipBounds(captureRect));
}
public void paintFinalImage(BufferedImage image) throws Exception {
screenShot = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
Graphics2D g = screenShot.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
}
public void repaint(BufferedImage orig, BufferedImage copy) {
Graphics2D g = copy.createGraphics();
g.drawImage(orig, 0, 0, null);
if (captureRect != null) {
g.setColor(Color.BLACK);
g.draw(captureRect);
}
g.dispose();
}
public void uploadImage(BufferedImage image) throws Exception {
String IMGUR_POST_URI = "http://api.imgur.com/2/upload.xml";
String IMGUR_API_KEY = API_KEY;
String readLine = null;
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, imageType.getSelectedItem().toString(), outputStream);
URL url = new URL(IMGUR_POST_URI);
String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(outputStream.toByteArray()).toString(), "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(IMGUR_API_KEY, "UTF-8");
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
InputStream inputStream;
if (((HttpURLConnection) urlConnection).getResponseCode() == 400) {
inputStream = ((HttpURLConnection) urlConnection).getErrorStream();
} else {
inputStream = urlConnection.getInputStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
readLine = line;
}
wr.close();
reader.close();
} catch(Exception e){
e.printStackTrace();
}
String URL = readLine.substring(readLine.indexOf("<original>") + 10, readLine.indexOf("</original>"));
System.out.println(URL);
Toolkit.getDefaultToolkit().beep();
StringSelection stringSelection = new StringSelection(URL);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
System.out.println(command);
if (command.equalsIgnoreCase("open")) {
frame.setVisible(true);
} else if (command.equalsIgnoreCase("exit")) {
System.exit(-1);
} else if (command.equalsIgnoreCase("screenshot")) {
try {
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final BufferedImage screen = robot.createScreenCapture(new Rectangle(screenSize));
selectArea(screen);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
#Override
public void itemStateChanged(ItemEvent e) {
System.out.println(e.getItem() + ", " +e.getStateChange());
String itemChanged = e.getItem().toString();
if (itemChanged.equalsIgnoreCase("run on start-up")) {
//TODO
} else if (itemChanged.equalsIgnoreCase("hide when minimized")) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
hideWhenMinimized = false;
} else if (e.getStateChange() == ItemEvent.SELECTED) {
hideWhenMinimized = true;
}
}
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("KeyTyped: "+e.getKeyCode());
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void nativeKeyPressed(NativeKeyEvent e) {
}
#Override
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("KeyReleased: "+e.getKeyCode());
System.out.println(KeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == 154) {
try {
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final BufferedImage screen = robot.createScreenCapture(new Rectangle(screenSize));
selectArea(screen);
frame.setVisible(true);
} catch(Exception e1) {
e1.printStackTrace();
}
}
}
#Override
public void nativeKeyTyped(NativeKeyEvent e) {
}
}
I recommend that you simplify your problem to solve it. Create a small compilable and runnable program that doesn't have all the baggage of your current code, but whose only goal is to display an image, and let the user select a sub-portion of that image. Then if your attempt fails, you can post your attempt here, and we can actually both run it, and understand it, and hopefully then be able to fix it.
For example, here's a small bit of compilable and runnable code that uses a MouseListener to select a small section of an image. Perhaps you can get some ideas from it:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class ImagePlay extends JPanel {
public static final String IMAGE_PATH = "http://upload.wikimedia.org/wikipedia/" +
"commons/thumb/3/39/European_Common_Frog_Rana_temporaria.jpg/" +
"800px-European_Common_Frog_Rana_temporaria.jpg";
private static final Color RECT_COLOR = new Color(180, 180, 255);
private BufferedImage img = null;
Point p1 = null;
Point p2 = null;
public ImagePlay() {
URL imgUrl;
try {
imgUrl = new URL(IMAGE_PATH);
img = ImageIO.read(imgUrl );
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel(icon) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
myLabelPaint(g);
}
};
setLayout(new BorderLayout());
add(new JScrollPane(label));
MouseAdapter mAdapter = new MyMouseAdapter();
label.addMouseListener(mAdapter);
label.addMouseMotionListener(mAdapter);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void myLabelPaint(Graphics g) {
if (p1 != null && p2 != null) {
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int width = Math.abs(p1.x - p2.x);
int height = Math.abs(p1.y - p2.y);
g.setXORMode(Color.DARK_GRAY);
g.setColor(RECT_COLOR);
g.drawRect(x, y, width, height);
}
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
p1 = e.getPoint();
p2 = null;
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
p2 = e.getPoint();
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
p2 = e.getPoint();
repaint();
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int width = Math.abs(p1.x - p2.x);
int height = Math.abs(p1.y - p2.y);
BufferedImage smlImg = img.getSubimage(x, y, width, height);
ImageIcon icon = new ImageIcon(smlImg);
JLabel label = new JLabel(icon);
JOptionPane.showMessageDialog(ImagePlay.this, label, "Selected Image",
JOptionPane.PLAIN_MESSAGE);
}
}
private static void createAndShowGui() {
ImagePlay mainPanel = new ImagePlay();
JFrame frame = new JFrame("ImagePlay");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
It uses a publicly available image obtained online, a MouseListener that's added to a JLabel, and the JLabel has its paintComponent(...) method overridden so as to show the guide lines from the MouseListener/Adapter. It creates the sub image via BufferedImage's getSubimage(...) method, and then it displays it in a JOptionPane, but it would be trivial to save the image if desired.
Related
I'm pretty new in Java, but I need to do something for school. I'm trying to do a Server-Client Puns game. I have Client and Server classes with chat and I have a class to drawing images on JPanel by mouse, but I have no idea how to share that picture with other Clients. Could you give me some ideas? Thanks!
Client code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.rmi.registry.*;
import java.util.*;
public class PunsClient extends JFrame {
//GUI
private JButton polacz, rozlacz;
private JPanel topPanel;
private JPanel centerPanel;
private Painter painter;
private JTextField host, wiadomosc;
private JTextArea komunikaty;
private JList<String> zalogowani;
private DefaultListModel<String> listaZalogowanych;
//Klient
private String nazwaSerwera = "localhost";
private Klient watekKlienta;
private PunsClient instancjaKlienta;
private Puns serwer;
private ClientImpl klient;
public PunsClient() {
super("Klient");
instancjaKlienta = this;
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
topPanel = new JPanel(new FlowLayout());
centerPanel = new JPanel(new FlowLayout());
painter = new Painter();
komunikaty = new JTextArea(20,12);
komunikaty.setLineWrap(true);
komunikaty.setEditable(false);
wiadomosc = new JTextField();
host = new JTextField(nazwaSerwera, 12);
polacz = new JButton("Połącz");
rozlacz = new JButton("Rozłącz");
rozlacz.setEnabled(false);
listaZalogowanych = new DefaultListModel<String>();
zalogowani = new JList<String>(listaZalogowanych);
zalogowani.setFixedCellWidth(120);
ObslugaZdarzen obsluga = new ObslugaZdarzen();
polacz.addActionListener(obsluga);
rozlacz.addActionListener(obsluga);
wiadomosc.addKeyListener(obsluga);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
rozlacz.doClick();
setVisible(false);
System.exit(0);
}
});
topPanel.add(new JLabel("Serwer RMI: "));
topPanel.add(host);
topPanel.add(polacz);
topPanel.add(rozlacz);
centerPanel.add(painter);
centerPanel.add(new JScrollPane(komunikaty), BorderLayout.EAST);
add(topPanel, BorderLayout.NORTH);
add(centerPanel, BorderLayout.CENTER);
//add(painter, BorderLayout.CENTER);
//add(new JScrollPane(komunikaty), BorderLayout.EAST);
//add(new JScrollPane(zalogowani), BorderLayout.EAST);
add(wiadomosc, BorderLayout.SOUTH);
setVisible(true);
}
private class ObslugaZdarzen extends KeyAdapter implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Połącz")) {
wyswietlKomunikat("Łączę z: " + nazwaSerwera + "...");
polacz.setEnabled(false);
rozlacz.setEnabled(true);
host.setEnabled(false);
watekKlienta = new Klient();
watekKlienta.start();
}
if (e.getActionCommand().equals("Rozłącz")) {
listaZalogowanych.clear();
try {
serwer.opusc(klient);
} catch (Exception ex) {
System.out.println("Błąd: " + ex);
}
rozlacz.setEnabled(false);
polacz.setEnabled(true);
host.setEnabled(true);
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == 10) {
try {
serwer.wiadomosc(klient, wiadomosc.getText());
wiadomosc.setText("");
} catch (Exception ex) {
System.out.println("Błąd: " + ex);
}
}
}
}
private class Klient extends Thread {
public void run() {
try {
Registry rejestr = LocateRegistry.getRegistry(host.getText());
serwer = (Puns) rejestr.lookup("RMICzat");
wyswietlKomunikat("Połączyłem się z serwerem.");
String nick = JOptionPane.showInputDialog(null, "Podaj nick: ");
klient = new ClientImpl(instancjaKlienta, nick);
serwer.dolacz(klient);
} catch (Exception e) {
System.out.println("Błąd połączenia: " + e);
}
}
}
public void wyswietlKomunikat(String tekst) {
komunikaty.append(tekst + "\n");
komunikaty.setCaretPosition(komunikaty.getDocument().getLength());
}
public void odswiezListe(Vector<Client> lista) {
listaZalogowanych.clear();
for (Client n : lista) {
try {
listaZalogowanych.addElement(n.pobierzNicka());
System.out.println(n.pobierzNicka());
} catch (Exception e) {
System.out.println("Błąd: " + e);
}
}
}
public static void main(String[] args) {
new PunsClient();
}
}
Painter code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Painter extends JPanel {
private static final long serialVersionUID = 1L;
int xvalue = -10, yvalue = -10;
public Painter() {
setPreferredSize(new Dimension(400, 400));
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged( MouseEvent event ) {
xvalue = event.getX();
yvalue = event.getY();
repaint();
}
});
}
public void paint ( Graphics g ) {
g.fillOval( xvalue, yvalue, 10, 10 );
}
}
My suggestion would be to use a BufferedImage from which you there is a method getGraphics() I believe. Use this method as your graphics for drawing and you can then send the BufferedImage across.
i have made an application that loads image from specific directory, loads all images in stack, when i am clicking on next button next image loads.
i have also added JSlider that change Brightness of Loaded Image but it doesn't work.
i don't know why but i am not getting exact problem.
my code :
public class PictureEditor extends JFrame
{
private static final long serialVersionUID = 6676383931562999417L;
String[] validpicturetypes = {"png", "jpg", "jpeg", "gif"};
Stack<File> pictures ;
JLabel label = new JLabel();
BufferedImage a = null;
float fval=1;
public PictureEditor()
{
JPanel panel = new JPanel();
JMenuBar menubar = new JMenuBar();
JMenu toolsmenu = new JMenu("Tools");
final JSlider slider1;
slider1 = new JSlider(JSlider.HORIZONTAL,0,4,1);
slider1.setToolTipText("Slide To Change Brightness");
slider1.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
slider1.setMajorTickSpacing(1);
slider1.setPaintLabels(true);
slider1.setPaintTicks(true);
slider1.setPaintTrack(true);
slider1.setAutoscrolls(true);
slider1.setBounds(50, 55, 200, 50);
slider1.addChangeListener(new ChangeListener()
{
#Override
public void stateChanged(ChangeEvent e)
{
System.out.println("Before");
fval=slider1.getValue();
chgBrt(fval);
repaint();
}
});
TitledBorder title;
title = BorderFactory.createTitledBorder("Operations");
title.setTitleJustification(TitledBorder.LEFT);
JButton RT90 = new JButton("");
JButton RT180 = new JButton("");
JButton RTM90 = new JButton("");
JButton RTM180 = new JButton("");
JButton NEXT = new JButton("");
Image img = null;
Image imgn = null;
try
{
img = ImageIO.read(getClass().getResource("/images/images_Horizontal.png"));
imgn = ImageIO.read(getClass().getResource("/images/next12.png"));
}
catch (IOException e)
{
e.printStackTrace();
}
RT90.setIcon(new ImageIcon(img));
RT180.setIcon(new ImageIcon(img));
RTM90.setIcon(new ImageIcon(img));
RTM180.setIcon(new ImageIcon(img));
NEXT.setIcon(new ImageIcon(imgn));
JPanel buttonPane = new JPanel();
buttonPane.add(slider1);
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
buttonPane.setBorder(title);
buttonPane.add(RT90);
buttonPane.add(RT180);
buttonPane.add(RTM90);
buttonPane.add(RTM180);
buttonPane.add(Box.createRigidArea(new Dimension(250,0)));
NEXT.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0)
{
nextImage();
}
});
buttonPane.add(NEXT);
getContentPane().add(buttonPane, BorderLayout.SOUTH);
final File dir = new File("");
final JFileChooser file;
file = new JFileChooser();
file.setCurrentDirectory(dir);
file.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
file.showOpenDialog(panel);
String path = file.getSelectedFile().getAbsolutePath();
System.out.println(path);
pictures= getFilesInFolder(path.toString());
Action nextpictureaction = new AbstractAction("Next Picture")
{
private static final long serialVersionUID = 2421742449531785343L;
#Override
public void actionPerformed(ActionEvent e)
{
nextImage();
}
};
setJMenuBar(menubar);
menubar.add(toolsmenu);
toolsmenu.add(nextpictureaction);
panel.add(label,BorderLayout.CENTER);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
setSize(1000, 700);
setTitle("PictureEditor");
setVisible(true);
}
public Stack<File> getFilesInFolder(String startPath)
{
File startFolder = new File(startPath);
Stack<File> picturestack = new Stack<File>();
String extension;
int dotindex;
// Go through the folder
for (File file : startFolder.listFiles())
{
extension = "";
dotindex = file.getName().lastIndexOf('.'); // Get the index of the dot in the filename
if (dotindex > 0)
{
extension = file.getName().substring(dotindex + 1);
// Iterate all valid file types and check it
for (String filetype : validpicturetypes)
{
if (extension.equals(filetype))
{
picturestack.add(file);
}
}
}
}
return picturestack;
}
public void nextImage()
{
try
{
a=ImageIO.read(pictures.pop().getAbsoluteFile());
}
catch (IOException e1)
{
e1.printStackTrace();
}
final ImageIcon image = new ImageIcon(a);
label.setIcon(image);
repaint();
}
#SuppressWarnings("null")
public void chgBrt(float f)
{
Graphics g = null;
Graphics2D g2d=(Graphics2D)g;
try
{
BufferedImage dest=changeBrightness(a,(float)fval);
System.out.println("Change Bright");
int w = a.getWidth();
int h = a.getHeight();
g2d.drawImage(dest,w,h,this);
ImageIO.write(dest,"jpeg",new File("/images/dest.jpg"));
System.out.println("Image Write");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public BufferedImage changeBrightness(BufferedImage src,float val)
{
RescaleOp brighterOp = new RescaleOp(val, 0, null);
return brighterOp.filter(src,null); //filtering
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PictureEditor();
}
});
}
}
anyone who can guide me and tell me where i am wrong ??
You may be able to adapt the approach shown in this RescaleTest, which varies the scaleFactor passed to RescaleOp to a value between zero and twice the slider's maximum.
my question is i want to add full background image if JDialog, this JDialog is created by JOptionPane. This image does not cover full Dialog.
If you have any solution please let me know.
public class BrowseFilePath {
public static final String DIALOG_NAME = "what-dialog";
public static final String PANE_NAME = "what-pane";
private static JDialog loginRegister;
private static String path;
private static JPanel Browse_panel = new JPanel(new BorderLayout());
private static JLabel pathLbl = new JLabel("Please Choose Folder / File");
private static JTextField regtxt_file = new JTextField(30);
private static JButton browse_btn = new JButton("Browse");
private static JButton ok_btn = new JButton("Ok");
private static JButton close_btn = new JButton("Cancel");
/*public static void main(String [] arg){
showFileDialog();
}*/
public static void showFileDialog() {
JOptionPane.setDefaultLocale(null);
JOptionPane pane = new JOptionPane(createRegInputComponent());
pane.setName(PANE_NAME);
loginRegister = pane.createDialog("ShareBLU");
/* try {
loginRegister.setContentPane(new JLabel(new ImageIcon(ImageIO.read(AlertWindow.getBgImgFilePath()))));
} catch (IOException e) {
e.printStackTrace();
}*/
loginRegister.setName(DIALOG_NAME);
loginRegister.setSize(380,150);
loginRegister.setVisible(true);
if(pane.getInputValue().equals("Ok")){
String getTxt = regtxt_file.getText();
BrowseFilePath.setPath(getTxt);
}
else if(pane.getInputValue().equals("Cancel")){
regtxt_file.setText("");
System.out.println("Pressed Cancel Button =======********=");
System.exit(0);
}
}
public static String getPath() {
return path;
}
public static void setPath(String path) {
BrowseFilePath.path = path;
}
private static JComponent createRegInputComponent() {
Browse_panel = new JBackgroundPanel();
Browse_panel.setLayout(new BorderLayout());
Box rows = Box.createVerticalBox();
Browse_panel.setBounds(0,0,380,150);
Browse_panel.add(pathLbl);
pathLbl.setForeground(Color.white);
pathLbl.setBounds(20, 20, 200, 20);
Browse_panel.add(regtxt_file);
regtxt_file.setToolTipText("Select File/Folder..");
regtxt_file.setBounds(20, 40, 220, 20);
Browse_panel.add(browse_btn);
browse_btn.setToolTipText("Browse");
browse_btn.setBounds(250, 40, 90, 20);
Browse_panel.add(ok_btn);
ok_btn.setToolTipText("Ok");
ok_btn.setBounds(40, 75, 80, 20);
Browse_panel.add(close_btn);
close_btn.setToolTipText("Cancel");
close_btn.setBounds(130, 75, 80, 20);
ActionListener chooseMe = createChoiceAction();
ok_btn.addActionListener(chooseMe);
close_btn.addActionListener(chooseMe);
browse_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int selection = JFileChooser.FILES_AND_DIRECTORIES;
fileChooser.setFileSelectionMode(selection);
fileChooser.setAcceptAllFileFilterUsed(false);
int rVal = fileChooser.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION) {
path = fileChooser.getSelectedFile().toString();
regtxt_file.setText(path);
}
}
});
rows.add(Box.createVerticalStrut(105));
Browse_panel.add(rows,BorderLayout.CENTER);
return Browse_panel;
}
public static ActionListener createChoiceAction() {
ActionListener chooseMe = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton choice = (JButton) e.getSource();
// find the pane so we can set the choice.
Container parent = choice.getParent();
while (!PANE_NAME.equals(parent.getName())) {
parent = parent.getParent();
}
JOptionPane pane = (JOptionPane) parent;
pane.setInputValue(choice.getText());
// find the dialog so we can close it.
while ((parent != null) && !DIALOG_NAME.equals(parent.getName()))
{
parent = parent.getParent();
//parent.setBounds(0, 0, 350, 150);
}
if (parent != null) {
parent.setVisible(false);
}
}
};
return chooseMe;
}
}
Don't use JOptionPane but use a full-blown JDialog. Set the content pane to a JComponent that overrides paintComponent() and returns an appropriate getPreferredSize().
Example code below:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestBackgroundImage {
private static final String BACKHGROUND_IMAGE_URL = "http://cache2.allpostersimages.com/p/LRG/27/2740/AEPND00Z/affiches/blue-fiber-optic-wires-against-black-background.jpg";
protected void initUI() throws MalformedURLException {
JDialog dialog = new JDialog((Frame) null, TestBackgroundImage.class.getSimpleName());
dialog.setModal(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JPanel mainPanel = new JPanel(new BorderLayout()) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = Math.max(backgroundImage.getIconWidth(), size.width);
size.height = Math.max(backgroundImage.getIconHeight(), size.height);
return size;
}
};
mainPanel.add(new JButton("A button"), BorderLayout.WEST);
dialog.add(mainPanel);
dialog.setSize(400, 300);
dialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestBackgroundImage().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Don't forget to provide an appropriate parent Frame
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();
}
});
}
}
I am making an application similar to a chat. For that purpose I have two JTextPanes, one where I'm writing and one that displays messages. This is the code that handles the transferring of text from input to display :
String input = textPane.getText();
if(!input.endsWith("\n")){
input+="\n";
}
StyledDocument doc = displayPane.getStyledDocument();
int offset = displayPane.getCaretPosition();
textPane.setText("");
try {
doc.insertString(offset, input, set);
} catch (BadLocationException ex) {
Logger.getLogger(ChatComponent.class.getName()).log(Level.SEVERE, null, ex);
}
The problem is that if i have colour on some words of the input text , the output is all coloured . So the colour is applied to all of the text when moved to display(while displayed correctly on input). Any suggestions on how i can move text properly?
Notice that same happens with other format as bold , italic etc
The text is already formatted on the input JTextPane . What i need to do
is transfer it as it is on a different JTextPane without having to check
the different style options
example
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class Fonts implements Runnable {
private String[] fnt;
private JFrame frm;
private JScrollPane jsp;
private JTextPane jta;
private int width = 450;
private int height = 300;
private GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
private StyledDocument doc;
private MutableAttributeSet mas;
private int cp = 0;
private Highlighter.HighlightPainter cyanPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.cyan);
private Highlighter.HighlightPainter redPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.red);
private Highlighter.HighlightPainter whitePainter = new DefaultHighlighter.DefaultHighlightPainter(Color.white);
private int _count = 0;
private int _lenght = 0;
public Fonts() {
jta = new JTextPane();
doc = jta.getStyledDocument();
jsp = new JScrollPane(jta);
jsp.setPreferredSize(new Dimension(height, width));
frm = new JFrame("awesome");
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLayout(new BorderLayout());
frm.add(jsp, BorderLayout.CENTER);
frm.setLocation(100, 100);
frm.pack();
frm.setVisible(true);
jta.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
fnt = ge.getAvailableFontFamilyNames();
mas = jta.getInputAttributes();
new Thread(this).start();
}
#Override
public void run() {
for (int i = 0; i < fnt.length; i++) {
StyleConstants.setBold(mas, false);
StyleConstants.setItalic(mas, false);
StyleConstants.setFontFamily(mas, fnt[i]);
StyleConstants.setFontSize(mas, 16);
dis(fnt[i]);
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setBold(mas, true);
dis(fnt[i] + " Bold");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setItalic(mas, true);
dis(fnt[i] + " Bold & Italic");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setBold(mas, false);
dis(fnt[i] + " Italic");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
}
jta.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
public void dis(String s) {
_count++;
_lenght = jta.getText().length();
try {
doc.insertString(cp, s, mas);
doc.insertString(cp, "\n", mas);
} catch (Exception bla_bla_bla_bla) {
bla_bla_bla_bla.printStackTrace();
}
if (_count % 2 == 0) {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, cyanPainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
} else if (_count % 3 == 0) {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, redPainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
} else {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, whitePainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Fonts fs = new Fonts();
}
});
}
}
In the absence of a good SSCCE, I really don't know how you adding colour to the text on your JTextPane, but hopefully this method might sort things out for you :
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
private void appendToTextPane(String name, Color c, String f)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, f);
int len = Client.nPane.getDocument().getLength();
textPane.setCaretPosition(len);
textPane.setCharacterAttributes(aset, true);
textPane.replaceSelection(name);
}
With this you can give a different Color and Font to each String literal that will be added to your JTextPane.
Hope this new Code might help you in some way :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class TextPaneTest extends JFrame
{
private JPanel topPanel;
private JPanel bottomPanel;
private JTextPane tPane1;
private JTextPane tPane2;
private JButton button;
public TextPaneTest()
{
topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1, 2));
bottomPanel = new JPanel();
bottomPanel.setBackground(Color.BLACK);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLUE);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
tPane1 = new JTextPane();
tPane1.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
tPane1.setCharacterAttributes(aset, false); // Add these settings to the other JTextPane also
tPane2 = new JTextPane();
tPane2.setCharacterAttributes(aset, false); // Mimic what the other JTextPane has
button = new JButton("ADD TO THE TOP JTEXTPANE");
button.setBackground(Color.DARK_GRAY);
button.setForeground(Color.WHITE);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
tPane1.setText(tPane2.getText());
}
});
add(topPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
topPanel.add(tPane1);
topPanel.add(tPane2);
bottomPanel.add(button);
pack();
tPane2.requestFocusInWindow();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextPaneTest();
}
});
}
}
Regards
This has been solved by merging the document models of the two panes. The solution is in this question: Keeping the format on text retrieval