Make an JLabel move with Key Bidings - java

I have a short script made in swing, people keep telling me that I need to use Key bindings to get the Jlabel to move but I can't figure out how to do it. anyone have any idea on how to implement Key bindings in a way it works that does not use a Key Listener or that will be a problem if I add a button?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.Font;
public class Screen extends JFrame {
private JPanel contentPane;
int x,y;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Screen frame = new Screen();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Screen() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new CardLayout(0, 0));
JPanel panel = new JPanel();
contentPane.add(panel, "p1");
panel.setLayout(null);
JButton btnPlay = new JButton("Play");
btnPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CardLayout c =(CardLayout)(contentPane.getLayout());
c.show(contentPane, "p2");
}
});
btnPlay.setBounds(185, 164, 53, 23);
panel.add(btnPlay);
JLabel lblGame = new JLabel("Game");
lblGame.setHorizontalAlignment(SwingConstants.CENTER);
lblGame.setBounds(189, 28, 46, 14);
panel.add(lblGame);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, "p2");
panel_1.setLayout(null);
JLabel player = new JLabel("P");
player.setHorizontalAlignment(SwingConstants.CENTER);
player.setFont(new Font("Tahoma", Font.BOLD, 27));
player.setForeground(Color.BLACK);
player.setBackground(Color.BLACK);
player.setBounds(x, y, 51, 40);
panel_1.add(player);
}
}

As with most things, start having a look at the tutorials, How to Use Key Bindings, as pretty much any answer is simply going to be based on these
You could do something as simple as this...
import com.sun.glass.events.KeyEvent;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
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();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface Movable {
public void changeLocation(int xDelta, int yDelta);
}
public class TestPane extends JPanel implements Movable {
private JLabel player;
public TestPane() {
setLayout(null);
player = new JLabel("X");
player.setSize(player.getPreferredSize());
add(player);
setupKeyBindings();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void setupKeyBindings() {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "up");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0), "down");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "left");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "right");
int xDelta = player.getWidth();
int yDelta = player.getHeight();
am.put("up", new MoveAction(this, 0, -yDelta));
am.put("down", new MoveAction(this, 0, yDelta));
am.put("left", new MoveAction(this, -xDelta, 0));
am.put("right", new MoveAction(this, xDelta, 0));
}
#Override
public void changeLocation(int xDelta, int yDelta) {
int xPos = player.getX() + xDelta;
int yPos = player.getY() + yDelta;
if (xPos + player.getWidth() > getWidth()) {
xPos = getWidth() - player.getWidth();
} else if (xPos < 0) {
xPos = 0;
}
if (yPos + player.getHeight() > getHeight()) {
yPos = getHeight() - player.getHeight();
} else if (xPos < 0) {
yPos = 0;
}
player.setLocation(xPos, yPos);
}
}
public class MoveAction extends AbstractAction{
private Movable movable;
private int xDelta;
private int yDelta;
public MoveAction(Movable movable, int xDelta, int yDelta) {
this.movable = movable;
this.xDelta = xDelta;
this.yDelta = yDelta;
}
#Override
public void actionPerformed(ActionEvent e) {
movable.changeLocation(xDelta, yDelta);
}
}
}
Disclaimer...
As I have, repeatedly, told either you or your fellow class mates, you shouldn't be using components this way. Instead, you should be following a custom painting route, which will provide you with greater flexibility and far less issues in the long run.
import com.sun.glass.events.KeyEvent;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
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();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface Movable {
public void changeLocation(int xDelta, int yDelta);
}
public class TestPane extends JPanel implements Movable {
private Rectangle player;
public TestPane() {
String text = "X";
FontMetrics fm = getFontMetrics(getFont());
int width = fm.stringWidth(text);
int height = fm.getHeight();
player = new Rectangle(0, 0, width, height);
setupKeyBindings();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void setupKeyBindings() {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "up");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0), "down");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "left");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "right");
int xDelta = player.width;
int yDelta = player.height;
am.put("up", new MoveAction(this, 0, -yDelta));
am.put("down", new MoveAction(this, 0, yDelta));
am.put("left", new MoveAction(this, -xDelta, 0));
am.put("right", new MoveAction(this, xDelta, 0));
}
#Override
public void changeLocation(int xDelta, int yDelta) {
int xPos = player.x + xDelta;
int yPos = player.y + yDelta;
if (xPos + player.width > getWidth()) {
xPos = getWidth() - player.width;
} else if (xPos < 0) {
xPos = 0;
}
if (yPos + player.height > getHeight()) {
yPos = getHeight() - player.height;
} else if (xPos < 0) {
yPos = 0;
}
player.setLocation(xPos, yPos);
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.draw(player);
FontMetrics fm = g2d.getFontMetrics();
g2d.drawString("X", player.x, player.y + fm.getAscent());
g2d.dispose();
}
}
public class MoveAction extends AbstractAction {
private Movable movable;
private int xDelta;
private int yDelta;
public MoveAction(Movable movable, int xDelta, int yDelta) {
this.movable = movable;
this.xDelta = xDelta;
this.yDelta = yDelta;
}
#Override
public void actionPerformed(ActionEvent e) {
movable.changeLocation(xDelta, yDelta);
}
}
}
You should also be making appropriate use layout managers. These will safe you a lot of hair and time.
See Laying Out Components Within a Container for more details

Related

Get current size of JPanel,JFrame

I have this code. I need to make this square flexible when I resize JFrame. The size of square should change in percentage. this.getWidth(),this.getHeight() returns (0,0);
super.getWidth(), super.getHeight() returns (0,0);
getWidth(), getHeight() returns (0,0);
No examples found by me. I have nothing more to add. Thank you very much!
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ComponentEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Parker {
public static void main(String[] args) {
new Parker();
}
public Parker() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ControlPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ControlPane extends JPanel {
private JSlider slider;
private DrawPane myPanel;
public ControlPane() {
setLayout(new BorderLayout());
myPanel = new DrawPane();
myPanel.setBackground(Color.WHITE);
Dimension dim = myPanel.getSize();
slider = new JSlider(SwingConstants.HORIZONTAL,0,100,20);
slider.setMajorTickSpacing(20);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setValue(0);
slider.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Slider"),
BorderFactory.createEmptyBorder(15,10,15,10)
)
);
slider.addChangeListener(
new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
myPanel.setScale(slider.getValue());
}
}
);
add(slider,BorderLayout.SOUTH);
add(myPanel,BorderLayout.CENTER);
}
}
public class DrawPane extends JPanel {
double scale = 1;
double angle = 0;
//here i tried different methods to find current size of frame, you can
//set some int values like 10 or 100 to watch that everything works
//properly
int rectWidth = ;
int rectHeight = ;
public void componentResized(ComponentEvent e) {
Dimension newSize = e.getComponent().getBounds().getSize();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int originX = getWidth() / 2;
int originY = getHeight() / 2;
int xOffset = -(rectWidth / 2);
int yOffset = -(rectHeight / 2);
g.setColor(Color.BLACK);
Graphics2D g2d = (Graphics2D) g.create();
g2d.translate(originX, originY);
g2d.scale(scale, scale);
g2d.fill(new Rectangle2D.Double(xOffset, yOffset, rectWidth, rectHeight));
g2d.dispose();
g.setColor(Color.RED);
g.drawRect(originX + xOffset, originY + yOffset, rectWidth, rectWidth);
}
public void setScale(int scale) {
this.scale = (scale / 100d);
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 200);
}
}
}
you should register a ComponentListener to your ControlPanel which is the main content pane of your JFrame for listening resize event's (also listens for initial resizing) and make the rectangle resize,
try this:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.Rectangle2D;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Parker {
public static void main(String[] args) {
new Parker();
}
public Parker() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ControlPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ControlPane extends JPanel {
private JSlider slider;
private DrawPane myPanel;
public ControlPane() {
setLayout(new BorderLayout());
myPanel = new DrawPane();
myPanel.setBackground(Color.WHITE);
Dimension dim = myPanel.getSize();
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
Dimension dim = e.getComponent().getSize();
myPanel.resizeRectangle(dim.width / 2, dim.height / 2);
}
});
slider = new JSlider(SwingConstants.HORIZONTAL, 0, 100, 20);
slider.setMajorTickSpacing(20);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setValue(0);
slider.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Slider"),
BorderFactory.createEmptyBorder(15, 10, 15, 10)));
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
myPanel.setScale(slider.getValue());
}
});
add(slider, BorderLayout.SOUTH);
add(myPanel, BorderLayout.CENTER);
}
}
public class DrawPane extends JPanel {
double scale = 1;
double angle = 0;
int rectWidth = 50;
int rectHeight = 50;
public void componentResized(ComponentEvent e) {
Dimension newSize = e.getComponent().getBounds().getSize();
}
public void resizeRectangle(int width, int height) {
rectWidth = width;
rectHeight = height;
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int originX = getWidth() / 2;
int originY = getHeight() / 2;
int xOffset = -(rectWidth / 2);
int yOffset = -(rectHeight / 2);
g.setColor(Color.BLACK);
Graphics2D g2d = (Graphics2D) g.create();
g2d.translate(originX, originY);
g2d.scale(scale, scale);
g2d.fill(new Rectangle2D.Double(xOffset, yOffset, rectWidth, rectHeight));
g2d.dispose();
g.setColor(Color.RED);
g.drawRect(originX + xOffset, originY + yOffset, rectWidth, rectWidth);
}
public void setScale(int scale) {
this.scale = (scale / 100d);
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 200);
}
}
}

Dragging-and-dropping to move a JTextArea around on JPanel

I want to be able to click on a JTextArea and drag it around my JPanel. I'm not sure the method on doing so. What I'm trying to do is change the x,y coordinates of the JTextArea as it is dragged, I'm not dragging a JTextArea above or below another. Just around on the screen, similar to moving Text Boxes in a program like Microsoft PowerPoint
The only method I can think of is using a MouseListener but I'm wondering if there is an easier way to implement it other than detecting a hover/press/drag on the JTextArea. Any ideas on how I can start?
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class UMLEditor {
public static void main(String[] args) {
JFrame frame = new UMLWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(30, 30, 1000, 700);
frame.getContentPane().setBackground(Color.white);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class UMLWindow extends JFrame {
Canvas canvas = new Canvas();
private static final long serialVersionUID = 1L;
public UMLWindow() {
addMenus();
}
public void addMenus() {
getContentPane().add(canvas);
JMenuBar menubar = new JMenuBar();
JMenuItem newTextBox = new JMenuItem("New Text Box");
newTextBox.setMnemonic(KeyEvent.VK_E);
newTextBox.setToolTipText("Exit application");
newTextBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
canvas.addTextBox();
}
});
menubar.add(newTextBox);
setJMenuBar(menubar);
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class Canvas extends JPanel {
JTextArea commentTextArea = new JTextArea(10, 10);
public Canvas() {
this.setOpaque(true);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
public void addTextBox() {
commentTextArea.setLineWrap(true);
commentTextArea.setWrapStyleWord(true);
commentTextArea.setVisible(true);
commentTextArea.setLocation(0, 0);
this.add(commentTextArea);
commentTextArea.setBounds(0, 0, 100, 100);
revalidate();
repaint();
}
class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
}
}
}
You don't really want to try and "drag" on JTextComponents, they already have functionality enabled which allows the user to click and drag to highlight text, you really don't want to be competing within this.
Instead, you want to define a "hot zone" area around the component which would allow you "highlight" the component in some and allow the user to drag the component via it.
For example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class DragMe {
public static void main(String[] args) {
new DragMe();
}
public DragMe() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JTextArea ta = new JTextArea(10, 20);
ta.setText("Bananas in pajamas");
JScrollPane sp = new JScrollPane(ta);
DragProxyPane proxy = new DragProxyPane(sp);
proxy.setSize(proxy.getPreferredSize());
proxy.setLocation(100 - proxy.getWidth() / 2, 100 - proxy.getHeight()/ 2);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
});
frame.add(proxy);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class DragProxyPane extends JPanel {
public static final int BUFFER_ZONE = 10;
private boolean mouseInHouse;
private JComponent component;
private List<HotZone> hotZones;
public DragProxyPane(JComponent comp) {
MouseAdapter ma = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
mouseInHouse = true;
repaint();
}
#Override
public void mouseExited(MouseEvent e) {
mouseInHouse = false;
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
Cursor cursor = Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR);
for (HotZone hz : hotZones) {
if (hz.getBounds(getSize()).contains(e.getPoint())) {
cursor = hz.getCursor();
break;
}
}
setCursor(cursor);
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
setOpaque(false);
setLayout(new BorderLayout());
add(comp);
setBorder(new EmptyBorder(BUFFER_ZONE, BUFFER_ZONE, BUFFER_ZONE, BUFFER_ZONE));
hotZones = new ArrayList<>(8);
// Top left, middle, right
hotZones.add(new HotZone(0f, 0f, Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR)));
hotZones.add(new HotZone(0.5f, 0f, Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR)));
hotZones.add(new HotZone(1f, 0f, Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR)));
// Left, right
hotZones.add(new HotZone(0f, 0.5f, Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)));
hotZones.add(new HotZone(1f, 0.5f, Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR)));
// Bottom left, middle, right
hotZones.add(new HotZone(0f, 1f, Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR)));
hotZones.add(new HotZone(0.5f, 1f, Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR)));
hotZones.add(new HotZone(1f, 1f, Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR)));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (mouseInHouse) {
g2d.setColor(Color.BLACK);
for (HotZone hotZone : hotZones) {
g2d.draw(hotZone.getBounds(getSize()));
}
}
g2d.dispose();
}
public class HotZone {
private float x, y;
private Cursor cursor;
public HotZone(float x, float y, Cursor cursor) {
this.x = x;
this.y = y;
this.cursor = cursor;
}
public Cursor getCursor() {
return cursor;
}
public Rectangle getBounds(Dimension size) {
return getBounds(size.width - 1, size.height - 1);
}
public Rectangle getBounds(int width, int height) {
int halfBuffer = BUFFER_ZONE / 2;
float xPos = (width * x) - halfBuffer;
float yPos = (height * y) - halfBuffer;
xPos = Math.min(Math.max(0, xPos), width - BUFFER_ZONE);
yPos = Math.min(Math.max(0, yPos), height - BUFFER_ZONE);
return new Rectangle(Math.round(xPos), Math.round(yPos), BUFFER_ZONE, BUFFER_ZONE);
}
}
}
}
This sets up a simple proxy component which acts as the hot zone manager, detecting the mouse coming into or out of it and updating the cursor based on its location within in it, but it does not disrupt the normal operations of the component.
Now, this example doesn't drag, sorry, you have plenty of other examples which should be able to get you over the line, but, you could simply add a MouseListener/MouseMoitionListener to the proxy to detect when the user drags, but you will need to add some more functionality to it to determine what that drag actually means (resize or move) ;)

How do I dynamically resize the JFrame to include JPanel with varying content size?

How do I make my JFrame match the size of the JPanel which holds the dynamically sized content?
I have created two simple class snippets if anyone could guide me through them.
Class1 : CanvasExample.java
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CanvasExample {
public static void main(String[] args) {
JPanelEx dataOut = new JPanelEx();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Title!");
f.setMinimumSize(new Dimension(200,100));
f.getContentPane().add(dataOut);
f.pack();
f.setVisible(true);
}
});
}
}
Class 2: JPanelEx.java
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JPanelEx extends JPanel {
public JPanelEx() {
super(new FlowLayout());
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Hello1", 10, 10);
g.drawString("Hello2", 10, 30);
g.drawString("Hello3", 10, 50);
g.drawString("Hello4", 10, 70);
g.drawString("Hello5", 10, 90);
g.drawString("Hello6", 10, 110);
g.drawString("Hello7", 10, 130);
g.drawString("Hello8", 10, 150);
g.drawString("Hello9", 10, 170);
g.drawString("Hello10", 10, 190);
g.dispose();
}
}
Current Output :
Expected Output :
I understand similar question might have been asked many times but I scanned through and couldn't get a clear solution. Any help is appreciated.
Your JPanelEx will need to provide size hints to allow the layout management system to determine how best the component should be laid out and the amount of space the content needs
Also, don't call dispose on Graphics contexts you didn't create!
As an example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
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();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JPanelEx());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class JPanelEx extends JPanel {
private int numElements = 10;
public JPanelEx() {
super(new FlowLayout());
}
#Override
public Dimension getPreferredSize() {
FontMetrics fm = getFontMetrics(getFont());
int width = 0;
int height = fm.getHeight() * numElements;
for (int index = 0; index < numElements; index++) {
width = Math.max(width, fm.stringWidth("Hello" + index));
}
return new Dimension(width, height);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0;
int y = 0;
FontMetrics fm = g.getFontMetrics();
for (int index = 0; index < numElements; index++) {
g.drawString("Hello" + index, x, y + fm.getAscent());
y += fm.getHeight();
}
}
}
}
Also see Laying Out Components Within a Container for more details about the layout manager API

java jframe transparent background on ubuntu

I have a problem with the code that I wrote when I run it on Ubuntu. I want to create a transparent JFrame and add an image as a border. When I run the program on Windows is working properly, but when I run it on ubuntu not only the JFrame but also the image is transparent.
I'd like the program to work in both os. I tried with this code setOpacity(0.0f); too. But the outcame is the same.
Help me please T_T
Sorry but I don't have enough reputation to post images so I put them as links...
This is what i see on Ubuntu: http://oi57.tinypic.com/wgymag.jpg
and this is on Windows:http://oi60.tinypic.com/5o5if4.jpg
and this is the link to the frameImage: oi58.tinypic.com/2j2xrwy.jpg
Here are the two classes that I used:
MainClass:
import com.sun.awt.AWTUtilities;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class Window extends JFrame {
private final int width, height;
private ContainerPanel container;
public Window() {
this.width = 1024;
this.height = 688;
this.setSize(width, height);
this.setMaximumSize(new Dimension(width, height));
this.setMinimumSize(new Dimension(width, height));
this.setResizable(false);
this.setUndecorated(true);
this.setBackground(new Color(0, 0, 0, 0));
container = new ContainerPanel(Window.this, 1024, 688);
this.setContentPane(container);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
try {
} catch (Exception e1) {
System.exit(0);
e1.printStackTrace();
}
}
});
this.setVisible(true);
this.pack();
}
public static void main(String[] args) {
System.out.println("TRANSLUCENT supported: " + AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.TRANSLUCENT));
System.out.println("PERPIXEL_TRANSPARENT supported: " + AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.PERPIXEL_TRANSPARENT));
System.out.println("PERPIXEL_TRANSLUCENT supported: " + AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.PERPIXEL_TRANSLUCENT));
new Window();
}
}
and this is the class with the background image:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ContainerPanel extends JPanel {
private final Window window;
private JLabel label;
private Point mouseDownCompCoords, currentLocationOnScreen;
private final int windowWidth, windowHeight;
private int closeButtonPosX, closeButtonPosY;
private BufferedImage frameImg;
public ContainerPanel(Window window, int windowWidth, int windowHeight) {
this.window = window;
this.windowWidth = windowWidth;
this.windowHeight = windowHeight;
this.closeButtonPosX = 900;
this.closeButtonPosY = 19;
this.setLayout(null);
this.setOpaque(false);
this.setSize(this.windowWidth, this.windowHeight);
this.setMaximumSize(new Dimension(this.windowWidth, this.windowHeight));
this.setMinimumSize(new Dimension(this.windowWidth, this.windowHeight));
crateLabel();
try {
createButton();
frameImg = ImageIO.read(new File("Images/Frame/frame.png"));
} catch (IOException ex) {
Logger.getLogger(ContainerPanel.class.getName()).log(Level.SEVERE, null, ex);
}
this.setVisible(true);
}
private void crateLabel() {
label = new JLabel();
final int labelHeight = 45;
label.setSize(windowWidth, labelHeight);
label.setMaximumSize(new Dimension(windowWidth, labelHeight));
label.setMinimumSize(new Dimension(windowWidth, labelHeight));
label.setLocation(0, 0);
label.setOpaque(false);
label.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseDownCompCoords = e.getPoint();
}
});
label.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
currentLocationOnScreen = e.getLocationOnScreen();
ContainerPanel.this.window.setLocation(currentLocationOnScreen.x - mouseDownCompCoords.x, currentLocationOnScreen.y - mouseDownCompCoords.y);
}
#Override
public void mouseMoved(MouseEvent e) {
//do nothing
}
});
label.setVisible(true);
this.add(label);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g2d);
g2d.drawImage(frameImg, 0, 0, windowWidth, windowHeight, null);
}
private void createButton() {
JButton close = new JButton("close");
close.setLocation(this.closeButtonPosX , this.closeButtonPosY);
close.setSize(100, 30);
close.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
System.exit(0);
}
});
label.add(close);
}
}
you can check this -> https://today.java.net/pub/a/today/2008/03/18/translucent-and-shaped-swing-windows.html by Kirill Grouchnikov.

How to Make a Splash Screen

I have a program which should has splash screen on JPanel, after button click should show another JPanel (object of the class) and draw shapes. I tried remove splash JPanel and after that add JPanel for drawing but it doeesn't work. How can I fix it? Two JLabel should be in the center of screen and it should be on 2 lines.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JComponent;
/**
*
* #author Taras
*/
public class MyComponent extends JComponent {
int i;
Color randColor;
public MyComponent()
{
this.i = i;
addMouseListener(new MouseHandler());
}
private ArrayList<Rectangle2D> arrOfRect=new ArrayList<>();
private ArrayList<Ellipse2D> arrOfEllipse=new ArrayList<>();
// private ArrayList<Color> randColor = new ArrayList<>();
Random rand = new Random();
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Rectangle2D r : arrOfRect) {
g.setColor(new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
g2.draw(r);
}
for (Ellipse2D e : arrOfEllipse) {
g.setColor(new Color(rand.nextFloat(), rand.nextFloat(), rand.nextFloat()));
g2.draw(e);
}
}
public void add(Point2D p)
{
double x=p.getX();
double y=p.getY();
if (Pole.i == 1){
Ellipse2D ellipse = new Ellipse2D.Double(x, y, 100,100);
//randColor = new Color(randRed(), randGreen(), randBlue());
arrOfEllipse.add(ellipse);
}
if (Pole.i == 2){
Rectangle2D rectangls=new Rectangle2D.Double(x, y, 100, 100);
arrOfRect.add(rectangls);
}
if (Pole.i == 3){
Rectangle2D rectangls=new Rectangle2D.Double(x, y, 150, 100);
arrOfRect.add(rectangls);
}
if (Pole.i == 4){
Ellipse2D ellipse = new Ellipse2D.Double(x, y, 100,50);
arrOfEllipse.add(ellipse);
}
}
private class MouseHandler extends MouseAdapter {
public void mousePressed(MouseEvent event)
{
add(event.getPoint());
//Color rColor = new Color(randRed(), randGreen(), randBlue());
//randColor.add(rColor);
repaint();
}
}
private int randRed() {
int red;
Random randomNumber = new Random();
red = randomNumber.nextInt(255);
return red;
}
private int randGreen() {
int green;
Random randomNumber = new Random();
green = randomNumber.nextInt(255);
return green;
}
private int randBlue() {
int blue;
Random randomNumber = new Random();
blue = randomNumber.nextInt(255);
return blue;
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import org.omg.CosNaming.NameComponent;
public class Pole extends JFrame {
public static int i;
public static JPanel nameContainer = new JPanel(new GridLayout(2, 1));
public static JFrame frame= new JFrame("Shape Stamper!");
public static void main(String[] args) {
JPanel container;
JButton circle = new JButton("Circle");
JButton square = new JButton("Square");
JButton rectangle = new JButton("Rectangle");
JButton oval = new JButton("Oval");
JLabel programName = new JLabel("Shape Stamper!");
JLabel programmerName = new JLabel("Progrramed by: ");
Font font = new Font("Serif", Font.BOLD, 32);
programName.setFont(font);
font = new Font("Serif", Font.ITALIC, 16);
programmerName.setFont(font);
programName.setHorizontalAlignment(JLabel.CENTER);
programmerName.setHorizontalAlignment(JLabel.CENTER);
//programmerName.setVerticalAlignment(JLabel.CENTER);
// nameContainer.setLayout(new BorderLayout());
nameContainer.add(programName);
nameContainer.add(programmerName);
//nameContainer.setLayout(new BoxLayout(nameContainer, BoxLayout.X_AXIS));
container = new JPanel(new GridLayout(1, 4));
container.add(circle);
container.add(square);
container.add(rectangle);
container.add(oval);
circle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 1;
frame.remove(nameContainer);
frame.repaint();
System.out.println(i);
}
});
square.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 2;
}
});
rectangle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 3;
}
});
oval.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
i = 4;
}
});
MyComponent shape = new MyComponent();
frame.setSize(500, 500);
frame.add(shape, BorderLayout.CENTER);
frame.add(container, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Here's an example of making a splash screen using an image.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
public class CircleSplashScreen {
public CircleSplashScreen() {
JFrame frame = new JFrame();
frame.getContentPane().add(new ImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setBackground(new Color(0, 0, 0, 0));
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CircleSplashScreen();
}
});
}
#SuppressWarnings("serial")
public class ImagePanel extends JPanel {
BufferedImage img;
public ImagePanel() {
setOpaque(false);
setLayout(new GridBagLayout());
try {
img = ImageIO.read(new URL("http://www.iconsdb.com/icons/preview/royal-blue/stackoverflow-4-xxl.png"));
} catch (IOException ex) {
Logger.getLogger(CircleSplashScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
}
}

Categories

Resources