Multiple users working in the same JFrame - java

Trying to work on a networking project, where two or more users need to be able to paint in the same JFrame.
How would this be approached most realisticly, connecting the two PCs using their IPs, then create a real-time scenario for them to work in, OR, some kind of package system, where the users send what they've drawne recently, and then the other user can see what have just been send?
EDIT: Added my drawing class for context
public class CanvasFrame extends JPanel {
ArrayList<Point> location = new ArrayList<Point>();
JTextArea consoleOutput = new JTextArea(1,20);
public void addComponentToPane(Container pane) {
consoleOutput.setEditable(false);
}
public CanvasFrame() {
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
location.clear();
location.add(e.getPoint());
}
});
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
location.add(e.getPoint());
repaint();
}
});
setPreferredSize(new Dimension(800, 500));
setBackground(Color.WHITE);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(location.isEmpty()){
return;
}
Point p = location.get(0);
for (int i = 1; i < location.size(); i++) {
Point q = location.get(i);
g.drawLine(p.x, p.y, q.x, q.y);
p = q;
}
}
public static void main(String[] args) throws Exception {
InetAddress SERVERIP = InetAddress.getLocalHost();
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Drawing with friends");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CanvasFrame(), BorderLayout.CENTER);
JTextArea IPadress = new JTextArea(1,20);
IPadress.setEditable(false);
IPadress.append("DEVICE IP: " + SERVERIP.getHostAddress());
frame.add(IPadress, BorderLayout.SOUTH);
frame.setSize(new Dimension(800,600));
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}
}

Related

Hovering button causes window to close

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

Custom Repaint not working at all

I am trying to create an X/O game and in that i am not able to call drawString() when user clicks on the required position.
I am able to display grid and take mouse co-ordinated where user clicks but i am not able to repaint "X" and "O" on that.
Please help.Thanks
Here is code snippet:
public class Tic_Tac_Toe extends JPanel
{
int xpos,ypos;
ArrayList xlist = new ArrayList();
ArrayList ylist = new ArrayList();
Point cursorPosition;
public static void main(String[] args)
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
int x=0,y=0;
boolean win,mark;
Board b=new Board();
Tic_Tac_Toe t=new Tic_Tac_Toe();
t.dispFrame();
while(!b.isGridFull())
{
b.printboard();
System.out.println("Enter the desired character position:");
try
{
x=Integer.parseInt(br.readLine());
y=Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println("Exception is:");
}
mark=b.placeMark(x,y);
win=b.checkforwin();
if(b.flag==true)
{
System.out.println("Congratulations player with character "+b.CurrentPlayerMark+" has won");
break;
}
b.changePlayer();
}
if(b.flag==false)
System.out.println("The game has been drawn!!!");
}
public void dispFrame()
{
JFrame frame = new JFrame("My New Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 300));
frame.setResizable(false);
JPanel panel=new JPanel()
{
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(30,100,270,100);
g.drawLine(30,200,270,200);
g.drawLine(100,35,100,250);
g.drawLine(200,35,200,250);
for(int i = 0; i < xlist.size(); i ++)
{
Object a1=xlist.get(i);
Object b1=ylist.get(i);
int k=(Integer)a1;
int j=(Integer)b1;
g.drawString("X",k,j);
}
}
#Override
public void update(Graphics g)
{
paint(g);
if(Board.CurrentPlayerMark=='x')
g.drawString("X",xpos,ypos);
else if(Board.CurrentPlayerMark=='o')
g.drawString("O",xpos,ypos);
}
};
panel.addMouseListener(new MouseListener()
{
public char c;
#Override
public void mouseClicked(MouseEvent e)
{
c=Board.CurrentPlayerMark;
System.out.println(":MOUSE_CLICK_EVENT:");
cursorPosition = MouseInfo.getPointerInfo().getLocation();
xpos=cursorPosition.x;
ypos=cursorPosition.y;
xlist.add(xpos);
ylist.add(ypos);
Graphics g = getGraphics();
update(g);
repaint(); //Want to repaint here after user clicks on desired position in X/O grid
//Does update method is useful to call or not???
System.out.println("xlist: " + xlist +"ylist: " + ylist);
System.out.println("X: " + xpos + " Y: " + ypos);
System.out.println("CurrentPlayerMark is:"+c);
Board.changePlayer();
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}

swings trouble with splash screen

I am trying to implement splash screen followed my main activity. Code below is what I have manged to do so far. And I am not able to get my splash screen working. Please help.
On running the the file its showing SplashScreen.getSplashScreen() returned null.What to do ?
SplashDemo.java
public class SplashDemo extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame) {
final String[] comps = {"foo", "bar", "baz"};
g.setComposite(AlphaComposite.Clear);
g.fillRect(120,140,200,40);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString("Loading "+comps[(frame/5)%3]+"...", 120, 150);
}
public SplashDemo() {
super("SplashScreen demo");
setSize(300, 200);
setLayout(new BorderLayout());
Menu m1 = new Menu("File");
MenuItem mi1 = new MenuItem("Exit");
m1.add(mi1);
mi1.addActionListener(this);
this.addWindowListener(closeWindow);
MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(m1);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
Graphics2D g = splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
for(int i=0; i<100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(90);
}
catch(InterruptedException e) {
}
}
splash.close();
setVisible(true);
toFront();
}
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
private static WindowListener closeWindow = new WindowAdapter(){
public void windowClosing(WindowEvent e){
e.getWindow().dispose();
}
};
public static void main (String args[]) {
SplashDemo test = new SplashDemo();
}
}
Create your splash screen image, say MySplashyScreen.gif, and put it in a directory called images (or wherever you like).
Then on startup use this command line:
java -splash:images/MySplashyScreen.gif SplashDemo

how to drag and drop files from a directory in java

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;
}
}
}

JFrame (being fullscreened) background color not changing

im using
getContentPane().setBackground(Color.PINK);
to set the background of a JFrame to the color pink. this JFrame is being fullscreened using a GraphicsDevice. the color of the background is not changing. any help?
fullscreen code:
public static void main(String... args) {
DisplayMode dMode = new DisplayMode(800, 600, 16, DisplayMode.REFRESH_RATE_UNKNOWN);
GameMain game = new GameMain();
game.run(dMode);
}
public void run(DisplayMode dMode) {
getContentPane().setBackground(Color.PINK);
setForeground(Color.WHITE);
setFont(new Font("Arial", Font.PLAIN, 24));
Screen s = new Screen();
try {
s.setFullScreen(dMode, this);
try {
Thread.sleep(5000);
} catch(Exception e) { }
} finally {
s.restoreScreen();
}
}
public void setFullScreen(DisplayMode dMode, JFrame window) {
window.setUndecorated(true);
window.setResizable(false);
gDevice.setFullScreenWindow(window);
if(dMode != null && gDevice.isDisplayChangeSupported()) {
try {
gDevice.setDisplayMode(dMode);
} catch(Exception e) { }
}
}
This works fine for me...
public class TestFullScreen {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
FullFrame frame = new FullFrame();
frame.setUndecorated(true);
frame.getContentPane().setBackground(Color.PINK);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
gs[0].setFullScreenWindow(frame);
}
});
}
public static class FullFrame extends JFrame {
public FullFrame() {
super();
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
});
}
}
}
I even set moved the setBackground call after the setFullScreenWindow call.
Make sure you don't have anything on the content pane that might be taking up the full space and that the content pane hasn't been changed.

Categories