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.
Related
Im woking on some code to do some computations on different types of beer. I have a main class which uses a GUI and has a JTextArea to print output. Calling append within the main class works just fine, but as soon as I try to call append from an outside class to write to the text area..no cigar..i've worked at this for awhile and simply have no clue. Quite a bit of code, but I think the fix is simple
and I guess while im at it, does it make sense to extend NewFileOpener into LagerChooser? Or should it extend jpanel?
thanks for the help!!
public class NewFinalOpener extends JPanel implements ActionListener {
JFileChooser fc;
private CustomPanel customPanel;
public CustomTextArea customTextArea = new CustomTextArea();
private double versionID = 1.0;
private JButton openButton;
protected ArrayList<String> namesForGeneration;
private boolean namesRead = false;
void displayGUI() {
JFrame frame = new JFrame("Binary Brewing! " + "Version:" + versionID);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE, 5));
customPanel = new CustomPanel();
// customTextArea = new CustomTextArea();
customTextArea
.append(" Program progress and/or errors will display below:");
customTextArea
.append("\n"
+ "----------------------------------------------------------------------------------------------------");
customTextArea.append("\n" + "\n"
+ "To Enable Beer recipe Generation please read in Name file!" + "\n");
contentPane.add(customTextArea, BorderLayout.CENTER);
contentPane.add(customPanel, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new NewFinalOpener().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
class CustomPanel extends JPanel implements ActionListener {
private static final int GAP = 5;
JButton openButton, b2, b3, b4;
public CustomPanel() {
fc = new JFileChooser();
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(Color.GRAY, GAP));
openButton = new JButton("Choose names file");
openButton.setVerticalTextPosition(AbstractButton.CENTER);
openButton.setHorizontalTextPosition(AbstractButton.LEADING);
openButton.setMnemonic(KeyEvent.VK_D);
openButton.setActionCommand("open");
openButton.setEnabled(true);
openButton.addActionListener(this);
add(openButton);
b2 = new JButton("Ale");
b2.setVerticalTextPosition(AbstractButton.CENTER);
b2.setHorizontalTextPosition(AbstractButton.LEADING);
b2.setMnemonic(KeyEvent.VK_D);
b2.setActionCommand("ale");
if(namesRead == false){
b2.setEnabled(false);
}
b2.addActionListener(this);
add(b2);
b3 = new JButton("Lager");
b3.setVerticalTextPosition(AbstractButton.CENTER);
b3.setHorizontalTextPosition(AbstractButton.LEADING);
b3.setMnemonic(KeyEvent.VK_D);
b3.setActionCommand("lager");
if(namesRead == false){
b3.setEnabled(false);
}
b3.addActionListener(this);
add(b3);
b4 = new JButton("Random");
b4.setVerticalTextPosition(AbstractButton.BOTTOM);
b4.setHorizontalTextPosition(AbstractButton.LEADING);
b4.setMnemonic(KeyEvent.VK_D);
b4.setActionCommand("lager");
if(namesRead == false){
b4.setEnabled(false);
}
b4.addActionListener(this);
add(b4);
}
public Dimension getPreferredSize() {
return (new Dimension(200, 100));
}
#Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("open")) {
int returnVal = fc.showOpenDialog(NewFinalOpener.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
BufferedReader br = new BufferedReader(new FileReader(
fc.getSelectedFile()));
String line = " ";
namesForGeneration = new ArrayList<String>();
while (br.ready() == true) {
line = br.readLine();
namesForGeneration.add(line);
}
if (br.ready() == false) {
customTextArea.append("\n"
+ "Successfully read all names!" + " "
+ file + "\n");
customTextArea.append("\n" + "Beer Recipe Generator Enabled!" + "\n");
namesRead = true;
b2.setEnabled(true);
b3.setEnabled(true);
b4.setEnabled(true);
openButton.setEnabled(false);
customTextArea
.append("\n"
+ "---------------------------------------------------------");
br.close();
}
} catch (Exception f) {
JOptionPane.showMessageDialog(null, e);
}
} else {
customTextArea.append("Open command cancelled by user."
+ "\n");
}
}
if(action.equalsIgnoreCase("lager")){
customTextArea.append("\n" + "\n "+ "Ale recipe generation selected proceeding to sub categories...");
b2.setEnabled(false);
b3.setEnabled(false);
b4.setEnabled(false);
createLagerFrame();
}
}
protected void createLagerFrame(){
LagerChooser l1 = new LagerChooser();
}
}
class CustomTextArea extends JTextArea {
private static final int GAP = 5;
public CustomTextArea() {
setEditable(false);
setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
}
public Dimension getPreferredSize() {
return (new Dimension(800, 800));
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
public void setCustomText(String text){
customTextArea.append(text);
}
}
and the class that needs to append to the JTextarea
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class LagerChooser extends NewFinalOpener{
public LagerChooser() {
}
public void tellCustom(String line){
setCustomText(line);
}
}
You can use:
public static final PrintStream OUT = System.out;
public CustomPanel() throws Throwable
{
...
System.setOut(new PrintStream(new OutputStream(){
#Override
public void write(int oneByte) throws IOException {
if(oneByte<0||oneByte>255)
return;
write(new byte[]{(byte)oneByte}, 0, 1);
}
#Override
public void write(byte[] b, int offset, int length) throws IOException {
String str = new String(b, offset, length);
customTextArea.append(str);
}
}));
And write to System.out. it will print to console and to textarea.
PS. Why you create custom textarea class? You should use JTextArea:
customTextArea=new JTextArea();
customTextArea.setEditable(false);
customTextArea.setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
customTextArea.setPrefferedSize(...);
Your code uses lot of memory, size of exported JAR isn't small for "simple program".
Optimized code:
import java.io.*;
import java.util.*;
class NewFinalOpener extends JPanel implements ActionListener {
JFileChooser fc;
private CustomPanel customPanel;
public JTextArea customTextArea = new JTextArea();
private double versionID = 1.0;
private JButton openButton;
protected ArrayList < String > namesForGeneration;
private boolean namesRead = false;
private static final PrintStream SYSOUT = System.out;
public NewFinalOpener() {
JFrame frame = new JFrame("Binary Brewing! Version:" + versionID);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE, 5));
customPanel = new CustomPanel();
customTextArea.setEditable(false);
customTextArea.setBorder(BorderFactory.createLineBorder(Color.CYAN, GAP));
customTextArea.setPreferredSize(new Dimension(800, 800));
System.setOut(new PrintStream(new OutputStream(){
#Override
public void write(int oneByte) throws IOException {
if(oneByte<0||oneByte>255)
return;
write(new byte[]{(byte)oneByte}, 0, 1);
}
#Override
public void write(byte[] b, int offset, int length) throws IOException {
String str = new String(b, offset, length);
SYSOUT.write(b,offset,length);
customTextArea.append(str);
}
}));
System.setErr(System.out);
System.out.println(" Program progress and/or errors will display below:");
System.out.println("----------------------------------------------------------------------------------------------------\n");
System.out.println("To Enable Beer recipe Generation please read in Name file!");
contentPane.add(customTextArea, BorderLayout.CENTER);
contentPane.add(customPanel, BorderLayout.LINE_START);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new NewFinalOpener();
}
});
}
class CustomPanel extends JPanel implements ActionListener {
private static final int GAP = 5;
JButton openButton, b2, b3, b4;
public CustomPanel() {
setPreferredSize(new Dimension(200, 100));
fc = new JFileChooser();
setOpaque(true);
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(Color.GRAY, GAP));
openButton = new JButton("Choose names file");
openButton.setVerticalTextPosition(AbstractButton.CENTER);
openButton.setHorizontalTextPosition(AbstractButton.LEADING);
openButton.setMnemonic(KeyEvent.VK_D);
openButton.setActionCommand("open");
openButton.setEnabled(true);
openButton.addActionListener(this);
add(openButton);
b2 = new JButton("Ale");
b2.setVerticalTextPosition(AbstractButton.CENTER);
b2.setHorizontalTextPosition(AbstractButton.LEADING);
b2.setMnemonic(KeyEvent.VK_D);
b2.setActionCommand("ale");
if (namesRead == false) {
b2.setEnabled(false);
}
b2.addActionListener(this);
add(b2);
b3 = new JButton("Lager");
b3.setVerticalTextPosition(AbstractButton.CENTER);
b3.setHorizontalTextPosition(AbstractButton.LEADING);
b3.setMnemonic(KeyEvent.VK_D);
b3.setActionCommand("lager");
if (namesRead == false) {
b3.setEnabled(false);
}
b3.addActionListener(this);
add(b3);
b4 = new JButton("Random");
b4.setVerticalTextPosition(AbstractButton.BOTTOM);
b4.setHorizontalTextPosition(AbstractButton.LEADING);
b4.setMnemonic(KeyEvent.VK_D);
b4.setActionCommand("lager");
if (namesRead == false) {
b4.setEnabled(false);
}
b4.addActionListener(this);
add(b4);
}
#Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("open")) {
int returnVal = fc.showOpenDialog(NewFinalOpener.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
BufferedReader br = new BufferedReader(new FileReader(fc.getSelectedFile()));
String line = " ";
namesForGeneration = new ArrayList < String > ();
while (br.ready() == true) {
line = br.readLine();
namesForGeneration.add(line);
}
if (br.ready() == false) {
System.out.println("Successfully read all names!" + " " + file + "\n");
System.out.println("Beer Recipe Generator Enabled!" + "\n");
namesRead = true;
b2.setEnabled(true);
b3.setEnabled(true);
b4.setEnabled(true);
openButton.setEnabled(false);
System.out.println("\n---------------------------------------------------------");
br.close();
}
} catch (Throwable f) {
f.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
} else {
System.out.println("Open command cancelled by user.");
}
}
if (action.equalsIgnoreCase("lager")) {
System.out.println("Ale recipe generation selected proceeding to sub categories...");
b2.setEnabled(false);
b3.setEnabled(false);
b4.setEnabled(false);
createLagerFrame();
}
}
protected void createLagerFrame() {
LagerChooser l1 = new LagerChooser();
}
}
}
class LagerChooser extends NewFinalOpener {
public LagerChooser() {}
public void tellCustom(String line) {
setCustomText(line);
}
}
I am having two classes, a main class and class which extends JPanel and implements Runnable. I am trying to create two threads for the same instance of the JPanel class in an actionListener, but i just don't know where to create the JPanel1 object...
//Edit: Button1 is the start of the application .After that , button 2 will appear with a quick animation of labels and when clicked it(button2) will start the same animation too. How can i do whenever one of these buttons is clicked to launch the run method ?
public void run() {
if(isTom){
repaint();
revalidate();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
panel.removeAll();
panel.add(tomLabel1);
repaint();
revalidate();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
panel.add(tomLabel2);
repaint();
revalidate();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
panel.add(tomLabel3);
repaint();
revalidate();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
panel.add(tomLabel4);
repaint();
revalidate();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
panel.add(tomLabel5);
repaint();
revalidate();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
panel.removeAll();
repaint();
revalidate();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
public Game(){
JFrame frame = new JFrame();
Panel1 key = new Panel1();
key.addKeyListener(key);
frame.add(key);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setUndecorated(true);
frame.setVisible(true);
}
public static void main(String[] args) {
new Game();
}
public class Panel1 extends JPanel implements KeyListener,Runnable{
JButton button1 = new JButton("BUTTON1");
JButton button2 = new JButton("BUTTON2");
add(button1);add(button2);
Thread t = new Thread(this); // This works, but i need it inside the actionListener.
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("button1");
Thread x = new Thread(j);//'j' is an JPanel1 object. I need something like this i guess
x.setName("Thread x");});
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("button2");
Thread y = new Thread(j);
y.setName("Thread y");
});
public void run(){
System.out.println(Thread.currentThread().getName());
}
First, Swing is NOT thread safe! This means that you should NEVER create or modify the UI from outside of context of the Event Dispatching Thread!
Second, Swing is a single threaded environment, this means that you should never block or execute long running code from within the context of the Event Dispatching Thread, this will cause the UI to freeze until the block is removed.
Your concept is correct, you implementation is wrong, you should use a Swing Timer instead.
Instead of removing and adding labels, use a single label and change it's properties (text/icon, what ever)
See Concurrency in Swing and How to use Swing Timers for more details
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
try {
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException exp) {
exp.printStackTrace();
}
}
});
}
public class TestPane extends JPanel {
private JButton button1;
private JButton button2;
private SplashScreen splashScreen;
public TestPane() throws IOException {
button1 = new JButton("Button One");
button2 = new JButton("Button Two");
JPanel buttons = new JPanel();
buttons.add(button1);
buttons.add(button2);
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
splashScreen.run();
}
});
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
splashScreen.run();
}
});
splashScreen = new SplashScreen();
setLayout(new BorderLayout());
add(splashScreen);
add(buttons, BorderLayout.SOUTH);
}
}
public static class SplashScreen extends JPanel {
protected static final int IMAGE_COUNT = 4;
private JLabel label;
private Timer timer;
private int delta;
private int count;
private Icon[] icons;
private Dimension preferredSize;
public SplashScreen() throws IOException {
String path = "/images/splash";
String ext = ".png";
icons = new Icon[IMAGE_COUNT];
int maxWidth = 0;
int maxHeight = 0;
for (int index = 0; index < IMAGE_COUNT; index++) {
String name = path + (index + 1) + ext;
System.out.println(name);
icons[index] = new ImageIcon(ImageIO.read(getClass().getResource(name)));
maxWidth = Math.max(maxWidth, icons[index].getIconWidth());
maxHeight = Math.max(maxHeight, icons[index].getIconHeight());
}
preferredSize = new Dimension(maxWidth, maxHeight);
timer = new Timer(250, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (count >= IMAGE_COUNT) {
count = IMAGE_COUNT - 2;
delta = -1;
} else if (count < 0) {
((Timer)e.getSource()).stop();
} else {
label.setIcon(icons[count]);
count += delta;
}
}
});
setLayout(new BorderLayout());
label = new JLabel();
add(label);
}
#Override
public Dimension getPreferredSize() {
return preferredSize;
}
public void run() {
if (!timer.isRunning()) {
delta = 1;
count = 0;
timer.start();
}
}
}
}
Create a new instance of a Thread with your Panel1 class instance:
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("button1");
Thread x = new Thread(Panel1.this);
x.start();
x.setName("Thread x");});
Repeat for the other button with a new Thread object:
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("button2");
Thread y = new Thread(Panel1.this);
y.start();
y.setName("Thread y"); });
Panel1.this is referring to the instance of the Panel1 class that is currently running, making sure that your Threads are executing run() of that instance.
I am performing actions for 2 combo boxes which involves in changing the background color of JLabel. Here is my code,
public class JavaApplication8 {
private JFrame mainFrame;
private JLabel signal1;
private JLabel signal2;
private JPanel s1Panel;
private JPanel s2Panel;
public JavaApplication8()
{
try {
prepareGUI();
} catch (ClassNotFoundException ex) {
Logger.getLogger(JavaApplication8.class.getName())
.log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) throws
ClassNotFoundException
{
JavaApplication8 swingControl = new JavaApplication8();
swingControl.showCombobox1();
}
public void prepareGUI() throws ClassNotFoundException
{
mainFrame = new JFrame("Signal");
mainFrame.setSize(300,200);
mainFrame.setLayout(new GridLayout(3, 0));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
signal1 = new JLabel("Signal 1",JLabel.LEFT);
signal1.setSize(100,100);
signal1.setOpaque(true);
signal2 = new JLabel("Signal 2",JLabel.LEFT);
signal2.setSize(100,100);
signal2.setOpaque(true);
final DefaultComboBoxModel light = new DefaultComboBoxModel();
light.addElement("Red");
light.addElement("Green");
final JComboBox s1Combo = new JComboBox(light);
s1Combo.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae)
{
if(s1Combo.getSelectedIndex() == 0)
{
signal1.setBackground(Color.RED);
}
else
{
signal1.setBackground(Color.GREEN);
}
}
});
final JComboBox s2Combo1 = new JComboBox(light);
s2Combo1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae)
{
if(s2Combo1.getSelectedIndex() == 0)
{
signal2.setBackground(Color.RED);
}
else
{
signal2.setBackground(Color.GREEN);
}
}
});
s1Panel = new JPanel();
s1Panel.setLayout(new FlowLayout());
JScrollPane ListScrollPane = new JScrollPane(s1Combo);
s1Panel.add(signal1);
s1Panel.add(ListScrollPane);
s2Panel = new JPanel();
s2Panel.setLayout(new FlowLayout());
JScrollPane List1ScrollPane = new JScrollPane(s2Combo1);
s2Panel.add(signal2);
s2Panel.add(List1ScrollPane);
mainFrame.add(s1Panel);
mainFrame.add(s2Panel);
String[] columnNames = {"Signal 1","Signal 2"};
Object[][] data = {{"1","1"}};
final JTable table = new JTable(data,columnNames);
JScrollPane tablepane = new JScrollPane(table);
table.setFillsViewportHeight(true);
mainFrame.add(tablepane);
mainFrame.setVisible(true);
}
}
When Executed, If I change the item from combo box 1, the 2nd combo box also performs the change. Where did I go wrong?
Yours is a simple solution: don't have the JComboBoxes share the same model. If they share the same model, then changes to the selected item of one JComboBox causes a change in the shared model which changes the view of both JComboBoxes.
I wold use a method to create your combo-jlabel duo so as not to duplicate code. For instance:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class App8 extends JPanel {
private static final int COMBO_COUNT = 2;
private static final String SIGNAL = "Signal";
private List<JComboBox<ComboColor>> comboList = new ArrayList<>();
public App8() {
setLayout(new GridLayout(0, 1));
for (int i = 0; i < COMBO_COUNT; i++) {
DefaultComboBoxModel<ComboColor> cModel = new DefaultComboBoxModel<>(ComboColor.values());
JComboBox<ComboColor> combo = new JComboBox<>(cModel);
add(createComboLabelPanel((i + 1), combo));
comboList.add(combo);
}
}
private JPanel createComboLabelPanel(int index, final JComboBox<ComboColor> combo) {
JPanel panel = new JPanel();
final JLabel label = new JLabel(SIGNAL + " " + index);
label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
label.setOpaque(true);
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
ComboColor cColor = (ComboColor) combo.getSelectedItem();
label.setBackground(cColor.getColor());
}
});
panel.add(label);
panel.add(combo);
return panel;
}
private static void createAndShowGui() {
App8 mainPanel = new App8();
JFrame frame = new JFrame("App8");
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();
}
});
}
}
enum ComboColor {
RED("Red", Color.RED),
GREEN("Green", Color.GREEN);
private String text;
private Color color;
public String getText() {
return text;
}
public Color getColor() {
return color;
}
private ComboColor(String text, Color color) {
this.text = text;
this.color = color;
}
#Override
public String toString() {
return text;
}
}
I want to implement dragging and dropping of files from a directory such as someones hard drive but can't figure out how to do it. I've read the java api but it talks of color pickers and dragging and dropping between lists but how to drag files from a computers file system and drop into my application. I tried writing the transferhandler class and a mouse event for when the drag starts but nothing seems to work. Now I'm back to just having my JFileChooser set so drag has been enabled but how to drop?
Any info or point in the right direction greatly appreciated.
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
public class FileChooserDemo
extends JPanel
implements ActionListener
{
JLabel selectedFileLabel;
JList selectedFilesList;
JLabel returnCodeLabel;
public FileChooserDemo()
{
super();
createContent();
}
void initFrameContent()
{
JPanel closePanel = new JPanel();
add(closePanel, BorderLayout.SOUTH);
}
private void createContent()
{
setLayout(new BorderLayout());
JPanel NorthPanel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem quit = new JMenuItem("Quit");
menuBar.add(menu);
menu.add(quit);
NorthPanel.add(menu,BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(7,1 ));
JButton openButton = new JButton("Open...");
openButton.setActionCommand("OPEN");
openButton.addActionListener(this);
buttonPanel.add(openButton);
JButton saveButton = new JButton("Save...");
saveButton.setActionCommand("SAVE");
saveButton.addActionListener(this);
buttonPanel.add(saveButton);
JButton delete = new JButton("Delete");
delete.addActionListener(this);
delete.setActionCommand("DELETE");
buttonPanel.add(delete);
add(buttonPanel, BorderLayout.WEST);
// create a panel to display the selected file(s) and the return code
JPanel displayPanel = new JPanel(new BorderLayout());
selectedFileLabel = new JLabel("-");
selectedFileLabel.setBorder(BorderFactory.createTitledBorder
("Selected File/Directory "));
displayPanel.add(selectedFileLabel, BorderLayout.NORTH);
selectedFilesList = new JList();
JScrollPane sp = new JScrollPane(selectedFilesList);
sp.setBorder(BorderFactory.createTitledBorder("Selected Files "));
MouseListener listener = new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
JComponent comp = (JComponent) me.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, me, TransferHandler.MOVE);
}
};
selectedFilesList.addMouseListener(listener);
displayPanel.add(sp);
returnCodeLabel = new JLabel("");
returnCodeLabel.setBorder(BorderFactory.createTitledBorder("Return Code"));
displayPanel.add(returnCodeLabel, BorderLayout.SOUTH);
add(displayPanel);
}
public void actionPerformed(ActionEvent e)
{
int option = 0;
File selectedFile = null;
File[] selectedFiles = new File[0];
if (e.getActionCommand().equals("CLOSE"))
{
System.exit(0);
}
else if (e.getActionCommand().equals("OPEN"))
{
JFileChooser chooser = new JFileChooser();
chooser.setDragEnabled(true);
chooser.setMultiSelectionEnabled(true);
option = chooser.showOpenDialog(this);
selectedFiles = chooser.getSelectedFiles();
}
else if (e.getActionCommand().equals("SAVE"))
{
JFileChooser chooser = new JFileChooser();
option = chooser.showSaveDialog(this);
selectedFiles = chooser.getSelectedFiles();
}
// display the selection and return code
if (selectedFile != null)
selectedFileLabel.setText(selectedFile.toString());
else
selectedFileLabel.setText("null");
DefaultListModel listModel = new DefaultListModel();
for (int i =0; i < selectedFiles.length; i++)
listModel.addElement(selectedFiles[i]);
selectedFilesList.setModel(listModel);
returnCodeLabel.setText(Integer.toString(option));
}
public static void main(String[] args)
{
SwingUtilities.invokeLater
(new Runnable()
{
public void run()
{
FileChooserDemo app = new FileChooserDemo();
app.initFrameContent();
JFrame frame = new JFrame("LoquetUP");
frame.getContentPane().add(app);
frame.setDefaultCloseOperation(3);
frame.setSize(600,400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
//frame.pack();
frame.setVisible(true);
}
});
}
}
This is my take on the idea. I've used the "traditional" drag and drop API in this example. It has some extra "paint" tweaks just to show off what you might be able to do.
This example doesn't scan folders dropped onto it, so any folder will only register as a single file, but I'm sure you can work it out
public class TestDragNDropFiles {
public static void main(String[] args) {
new TestDragNDropFiles();
}
public TestDragNDropFiles() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DropPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DropPane extends JPanel {
private DropTarget dropTarget;
private DropTargetHandler dropTargetHandler;
private Point dragPoint;
private boolean dragOver = false;
private BufferedImage target;
private JLabel message;
public DropPane() {
try {
target = ImageIO.read(new File("target.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
setLayout(new GridBagLayout());
message = new JLabel();
message.setFont(message.getFont().deriveFont(Font.BOLD, 24));
add(message);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected DropTarget getMyDropTarget() {
if (dropTarget == null) {
dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, null);
}
return dropTarget;
}
protected DropTargetHandler getDropTargetHandler() {
if (dropTargetHandler == null) {
dropTargetHandler = new DropTargetHandler();
}
return dropTargetHandler;
}
#Override
public void addNotify() {
super.addNotify();
try {
getMyDropTarget().addDropTargetListener(getDropTargetHandler());
} catch (TooManyListenersException ex) {
ex.printStackTrace();
}
}
#Override
public void removeNotify() {
super.removeNotify();
getMyDropTarget().removeDropTargetListener(getDropTargetHandler());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (dragOver) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(0, 255, 0, 64));
g2d.fill(new Rectangle(getWidth(), getHeight()));
if (dragPoint != null && target != null) {
int x = dragPoint.x - 12;
int y = dragPoint.y - 12;
g2d.drawImage(target, x, y, this);
}
g2d.dispose();
}
}
protected void importFiles(final List files) {
Runnable run = new Runnable() {
#Override
public void run() {
message.setText("You dropped " + files.size() + " files");
}
};
SwingUtilities.invokeLater(run);
}
protected class DropTargetHandler implements DropTargetListener {
protected void processDrag(DropTargetDragEvent dtde) {
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrag(DnDConstants.ACTION_COPY);
} else {
dtde.rejectDrag();
}
}
#Override
public void dragEnter(DropTargetDragEvent dtde) {
processDrag(dtde);
SwingUtilities.invokeLater(new DragUpdate(true, dtde.getLocation()));
repaint();
}
#Override
public void dragOver(DropTargetDragEvent dtde) {
processDrag(dtde);
SwingUtilities.invokeLater(new DragUpdate(true, dtde.getLocation()));
repaint();
}
#Override
public void dropActionChanged(DropTargetDragEvent dtde) {
}
#Override
public void dragExit(DropTargetEvent dte) {
SwingUtilities.invokeLater(new DragUpdate(false, null));
repaint();
}
#Override
public void drop(DropTargetDropEvent dtde) {
SwingUtilities.invokeLater(new DragUpdate(false, null));
Transferable transferable = dtde.getTransferable();
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(dtde.getDropAction());
try {
List transferData = (List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
if (transferData != null && transferData.size() > 0) {
importFiles(transferData);
dtde.dropComplete(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
dtde.rejectDrop();
}
}
}
public class DragUpdate implements Runnable {
private boolean dragOver;
private Point dragPoint;
public DragUpdate(boolean dragOver, Point dragPoint) {
this.dragOver = dragOver;
this.dragPoint = dragPoint;
}
#Override
public void run() {
DropPane.this.dragOver = dragOver;
DropPane.this.dragPoint = dragPoint;
DropPane.this.repaint();
}
}
}
}
You need to experiment with Drag & Drop and see exactly what flavors are available when you try to drag files. If you do this in your custom TransferHandler you'll be pleasantly surprised one Flavor is the DataFlavor.javaFileListFlavor, which indicates that the item can be used simply as a List. Try it and you'll see that it works!
Note on review of your posted code, I don't see any code for your attempt at using a TransferHandler, so it is hard to say what you could be doing wrong here.
Edit 1
You seem to be trying to use a MouseListener for your drag and drop, and I'm not familiar with this usage. Can you show a reference to a tutorial that tells you to do this?
Edit 2
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class FileDragDemo extends JPanel {
private JList list = new JList();
public FileDragDemo() {
list.setDragEnabled(true);
list.setTransferHandler(new FileListTransferHandler(list));
add(new JScrollPane(list));
}
private static void createAndShowGui() {
FileDragDemo mainPanel = new FileDragDemo();
JFrame frame = new JFrame("FileDragDemo");
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();
}
});
}
}
#SuppressWarnings("serial")
class FileListTransferHandler extends TransferHandler {
private JList list;
public FileListTransferHandler(JList list) {
this.list = list;
}
public int getSourceActions(JComponent c) {
return COPY_OR_MOVE;
}
public boolean canImport(TransferSupport ts) {
return ts.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
public boolean importData(TransferSupport ts) {
try {
#SuppressWarnings("rawtypes")
List data = (List) ts.getTransferable().getTransferData(
DataFlavor.javaFileListFlavor);
if (data.size() < 1) {
return false;
}
DefaultListModel listModel = new DefaultListModel();
for (Object item : data) {
File file = (File) item;
listModel.addElement(file);
}
list.setModel(listModel);
return true;
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
}
}
}
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.