I have JPanel called panelCrtanje.
I need to change cBox state if it is pressed.
final PadDraw drawPad = new PadDraw();
panelCrtanje.setLayout(new BorderLayout());
panelCrtanje.add(drawPad, BorderLayout.CENTER);
It works before I add drawPad to panelCrtanje using this:
private void panelCrtanjeMousePressed(java.awt.event.MouseEvent evt) {
slikaC.setSelected(true);
}
PadDraw looks like this
public PadDraw(){
setDoubleBuffered(false);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
oldX = e.getX();
oldY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter()){
public void mouseDragged(MouseEvent e){
currentX = e.getX();
currentY = e.getY();
if(graphics2D != null) {
graphics2D.setStroke(new BasicStroke(18F,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
graphics2D.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
}
});
}
You need to use MouseEvent properly. To use it the class needs to implement MouseListener. Then you need to create a listener for the mouse event like so:
panelCrtanje.addMouseListener();
Then use these methods that are required in MouseListener and MotionMouseListener
#Override
public void mouseClicked(java.awt.event.MouseEvent e) {
// TODO In HERE do what you want to do
}
#Override
public void mousePressed(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(java.awt.event.MouseEvent e) {
// TODO Auto-generated method stub
When the mouse is clicked: mouseClicked
When the mouse is held down but not moved: mousePressed
When the mouse is released: mouseReleased
When the mouse enters the window: mouseEntered
When the mouse leaves the window: mouseExited
That is how you can use the mouseListener to do different things.
you should register a MouseListener on panelCartanje, I have used an anonymous inner class to do this.
panelCrtanje.addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent e) {
/// cBox state change goes here . . .
}
});
This was the solution
MouseAdapter adap = new MouseAdapter(){
public void mousePressed(MouseEvent e) {
slikaC.setSelected(true);
}
};
Related
I am currently creating a solitaire game where a card will pop up on the bottom left corner of the middle JPanel if it was drawn by the user. Once shown in the bottom left corner, it should be able to be dragged freely. However, the image itself is not updating while it is being dragged. Additionally, the terminal outputs that I am dragging the card of several coordinates but the image itself never seems to move. The stack of cards above it is using the same move listener class and works perfectly as it can be dragged freely. Could someone help me in finding out what the problem is? Thank you!
This is the code for my move listener class:
public class MoveListener extends javax.swing.JFrame implements MouseListener, MouseMotionListener{
ImageIcon image = new ImageIcon("back of playing card.png");
int WIDTH = image.getIconWidth();
int HEIGHT = image.getIconHeight();
Point imgCorner;
Point startPt;
Component label;
MoveListener(JLayeredPane pane) {
imgCorner = new Point(0, 0);
this.label = pane;
}
MoveListener(JLabel label) {
imgCorner = new Point(0,0);
this.label = label;
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
Component pressedComponent = e.getComponent().getComponentAt(e.getPoint());
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
startPt = SwingUtilities.convertPoint(label, e.getPoint(), label.getParent());
System.out.println("Starting point: " + startPt);
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
startPt = null;
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
Component enteredComponent = e.getComponent().getComponentAt(e.getPoint());
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
Point currPt = SwingUtilities.convertPoint(label, e.getPoint(), label.getParent());
System.out.println("You are currently dragging over the point: " + currPt);
if(label.getParent().getBounds().contains(currPt)) {
Point newPt = label.getLocation();
newPt.translate((currPt.x - startPt.x), (currPt.y - startPt.y));
newPt.x = Math.max(newPt.x, 0);
newPt.y = Math.max(newPt.y, 0);
newPt.x = Math.min(newPt.x, label.getParent().getWidth() - label.getWidth());
newPt.y = Math.min(newPt.y, label.getParent().getHeight() - label.getHeight());
label.setLocation(newPt);
startPt = currPt;
}
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
I have been trying to accomplish how to move the jframe when I drag it using the mouse. But I couldn't find a solution to it.
I have tried to implement listeners on the Jframe but it doesn't work the way I have intended it to.
JFrame jframe = new JFrame();
jframe.setSize(500,500);
jframe.setLocation(400, 100);
jframe.setVisible(true);
jframe.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
You could use MouseMotionListener. Get the position of the mouse when you move the mouse using mouseMoved event method and use it with the drag event to position the frame accordingly. :
jframe.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
xDrag = e.getX();
yDrag = e.getY();
JFrame sFrame = (JFrame) e.getSource();
sFrame.setLocation(sFrame.getLocation().x+xDrag-xPress,
sFrame.getLocation().y+yDrag-yPress);
}
#Override
public void mouseMoved(MouseEvent e) {
xPress = e.getX();
yPress = e.getY();
}
});
Declare the variables xDrag, yDrag, xPress, yPress in your class. I hope this helps.
I am trying to create some kind of Paint program. I created a BufferedImage and an Graphics2D but i cant draw on it. All what I can see is the BufferedImage itself without any changes.
public class paintapp implements ActionListener, MouseListener, MouseMotionListener
{
public static final int WIDTHBUFF=300;
public static final int HEIGHTBUFF=300;
BufferedImage buffimage=new BufferedImage(WIDTHBUFF,HEIGHTBUFF,BufferedImage.TYPE_INT_BGR);
JLabel imagelabel=new JLabel(new ImageIcon(buffimage));
int s=3;
Color curr_color=Color.BLACK;
int x,y;
public static final int WIDTH=700;
public static final int HEIGHT=700;
public paintapp()
{
Graphics2D g2d=buffimage.createGraphics();
g2d.setBackground(Color.WHITE);
g2d.fillRect(0, 0, WIDTHBUFF,HEIGHTBUFF);
JFrame frame=new JFrame("Painter");
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setVisible(true);
Panel buttonpanel=new Panel();
Panel colors=new Panel();
Panel draw=new Panel();
draw.add(imagelabel);
frame.add(draw);
frame.pack();
}
public static void main(String[]args)
{
paintapp paint1=new paintapp();
}
#Override
public void mouseDragged(MouseEvent e) {
Graphics2D g2=buffimage.createGraphics();
g2.setColor(curr_color);
g2.setStroke(new BasicStroke(s));
g2.drawLine(x, y, e.getX(), e.getY());
x=e.getX();
y=e.getY();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
x=e.getX();
y=e.getY();
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
I see you are poking through and you got things in jumbled up order. If you read the guides you will see how things go.
The first main thing is to add a MouseMotionListener to the drawing thing - be that JLabel JPanel whatever.
The second thing is that once you go outside of the constructor the JFrame is lost (unless you do some fancy things) and cant be accessed to be refreshed, so the system decides when to refresh and you will see - after you add the mouse listener - that your drawing will appear once you hide and show again the drawing window.
So you need to have JFrame as global - why dont you have you class extend JFrame and so no need to have some extra JFrame.
I am creating a costume component in Model UIDelegate using DrawPad example. However, for some reason I get the error UIDefaults.getUI() failed: no ComponentUI class. I am not even sure if I am implementing Model UIDelegate properly. But why am I getting that error?
Main
public class Main {
static JFrame frame;
static JButton clearButton;
static DrawPad drawPad;
public static void main(String[] args) {
UIManager.put("DrawPadUI", "BasicDrawPadUI");
frame = new JFrame();
drawPad = new DrawPad();
clearButton = new JButton("Clear");
frame.add(drawPad, BorderLayout.CENTER);
clearButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Graphics g = frame.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, frame.getWidth(), frame.getHeight());
}
});
frame.add(clearButton, BorderLayout.SOUTH);
frame.setSize(280, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
BasicDrawPadUI
public class BasicDrawPadUI extends ComponentUI implements MouseListener, MouseMotionListener {
Image image;
Graphics2D graphics2D;
int currentX, currentY, oldX, oldY;
JFrame frame;
JButton clearButton;
public static ComponentUI createUI(JComponent c) {
return new BasicDrawPadUI();
}
public void paintComponent(Graphics g, JComponent c) {
if (image == null) {
image = c.createImage(c.getWidth(), c.getHeight());
graphics2D = (Graphics2D) image.getGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
clear(c);
}
g.drawImage(image, 0, 0, null);
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
currentX = e.getX();
currentY = e.getY();
if (graphics2D != null)
graphics2D.drawLine(oldX, oldY, currentX, currentY);
//repaint();
oldX = currentX;
oldY = currentY;
}
public void clear(JComponent c) {
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, c.getWidth(), c.getHeight());
graphics2D.setPaint(Color.black);
c.repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
oldX = e.getX();
oldY = e.getY();
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
DrawPad
class DrawPad extends JComponent {
private final static String ID = "DrawPadUI";
public DrawPad() {
updateUI();
}
public void updateUI() {
setUI(UIManager.getUI(this));
}
#Override
public String getUIClassID() {
return ID;
}
}
Change UIManager.put("DrawPadUI", "BasicDrawPadUI"); to UIManager.put("DrawPadUI", "drawpad.BasicDrawPadUI");
You need to specify the full qualified class name of the UI class, including the package name
I'll need to have a look to be sure, but when it calls createUI, you could grab a reference to the component
Override the installUI method from ComponentUI and when it's called, maintain a reference to the component that is passed to you.
private DrawPad drawPad;
//...
#Override
public void installUI(JComponent c) {
drawPad = (DrawPad) c;
// Install required listeners and other functionality
}
Equally, in uninstallUI, you should dereference any strong references you have and uninstall your listeners
#Override
public void uninstallUI(JComponent c) {
// Uninstall any listeners
drawPad = null;
}
Have a look at custom java Swing component Model, UIDelegate, component format for a complete implementation.
Also, you should NEVER maintain a reference to a Graphics2D context that you did not create yourself
I have no Idea why my JFrame keeps freezeing after I type Letters into the JTextField "Username" and "Password" :/ Could anyone look thru my code and tell my why and fix it please ?
public class Main
{
public static void main(String [ ] args)
{
LoginWindow loginframe = new LoginWindow();
loginframe.setVisible(true);
loginframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginframe.initialize();
while(true)
{
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
loginframe.Repaint();
}
}
}
FrameClass:
public class LoginWindow extends JFrame implements MouseListener, KeyListener, MouseMotionListener{
public LoginWindow(){
setSize(806, 629);
setResizable(false);
setLayout(new BorderLayout());
background = new JLabel(ResourceLoader.Iconload("/main_01.jpg"));
background.setBounds(0, 0, 800, 600);
add(background);
background.setLayout(null);
Username = new JTextField("", 20);
Username.setForeground(Color.WHITE);
Username.setBounds(312, 433, 170, 40);
Username.setFont(new Font("Impact", Font.BOLD, 25));
Username.setBackground(Color.BLACK);
Username.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.BLACK));
background.add(Username);
Password = new JPasswordField("", 20);
Password.setForeground(Color.WHITE);
Password.setBounds(312, 489, 170, 40);
Password.setBackground(Color.BLACK);
Password.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.BLACK));
Password.setFont(new Font("Serif", Font.BOLD, 25));
background.add(Password);
}
public void initialize()
{
makestrat();
addKeyListener(this);
requestFocus();
addMouseListener(this);
addMouseMotionListener(this);
}
public void makestrat()
{
createBufferStrategy(2);
strat = getBufferStrategy();
}
public void Repaint()
{
//System.out.println(mouseX + " " + mouseY);
Graphics g = strat.getDrawGraphics();
paintComponents(g);
Draw(g);
g.dispose();
strat.show();
}
public void Update()
{
}
public void Draw(Graphics g)
{
if(((mouseX >= 499) && (mouseX <= 669)) && ((mouseY >= 433)&&( mouseY <= 530))){
g.drawImage(ResourceLoader.ImageLoad("/login_02.jpg"), 502, 459, null);
}else{
g.drawImage(ResourceLoader.ImageLoad("/login_01.jpg"), 502, 459, null);
}
}
private class thehandler implements ActionListener{
#Override
public void actionPerformed(ActionEvent event) {
}
}
public void mouseMoved(MouseEvent event)
{
mouseY = event.getY()-26;
mouseX = event.getX()-3;
}
#Override
public void mouseClicked(MouseEvent e) {
PointerInfo a = MouseInfo.getPointerInfo();
Point point = new Point(a.getLocation());
SwingUtilities.convertPointFromScreen(point, e.getComponent());
double mouseX = (int) point.getX();
double mouseY = (int) point.getY();
System.out.println("(ContainerPos) Mouse clicked! X: " + mouseX + " Y: " + mouseY);
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
You don't need the while loop with the Thread.sleeap(). It's screwing with your program.
What you're trying to achieve here, a call to repaint continuously, can easily be accomplished with a javax.swing.Timer
Don't explicitly call paintComponent. An actual call to the real repaint() method will do that for you. No need to create an imitation Repaint()
Use a JPanel for painting instead of trying to paint on a JFrame
I would initialize, then set visible
Your code doesn't even compilable, so I can try and make fixes for you.
Use Java naming convention: methods and variable start with lower case letters.
Here's an example of a simple Login Window, using a modal JDialog
Learn how to use Layout Managers instead of relying on setBounds()
Point 2. Your main should look like this
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
LoginWindow loginframe = new LoginWindow();
loginframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginframe.initialize();
loginframe.setVisible(true);
}
});
}
And in your constructor, have a javax.swing.Timer instead of your while loop
private Timer timer = null;
private DrawPanel drawPanel = new DrawPanel(); // see below for DrawPanel
public LoginWindow() {
// add drawPanel somewhere
...
timer = new Timer (50, new ActionListener(){
public void actionPerformed(ActionEvent e) {
drawPanel.repaint();
}
});
timer.start();
}
Point 4. Have an inner JPanel class that you do all your painting in, and add that component to the frame. You'll need to override the paintComponent method.
private DrawPanel extends JPanel {
#Override
protected void paintComponent(Graophics g) {
super.paintComponent(g);
Draw(g);
}
}
The obvious thing is that you shouldn't use Swing (or AWT really) off of the AWT Event Dispatch Thread (EDT). Fix with java.awt.EventQueue.invokeLater and java.swing.Timer (not java.util!). Diagnose with jstack(and jps) or the relevant key sequence in the terminal window (um, ctrl-break in Windows, ctrl-3 in Linux).