Mouse Coordinates keep getting on top of one another -Java - java

I am trying to get the mouse coordinates display in the panel but each time I move the cursor the message and new coordinates are being displayed on the previous one.I am using MouseMotionListener with JPanel. I can't figure out the problem.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.MouseMotionListener;
public class Main extends JPanel implements MouseMotionListener {
public JLabel label;
public static void main(String[] args) {
new Main();
JFrame frame = new JFrame();
frame.setTitle("MouseCoordinates");
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new Main());
frame.setVisible(true);
}
public Main() {
setSize(400, 400);
label = new JLabel("No Mouse Event Captured", JLabel.CENTER);
add(label);
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent e) {
label.setText("Mouse Cursor Coordinates => X:" + e.getX() + " |Y:" + e.getY());
}
public void mouseDragged(MouseEvent e) {}
}

You're creating Main twice.
public class Main extends JPanel implements MouseMotionListener {
public JLabel label;
public static void main(String[] args) {
Main m = new Main();// create an object and reference it
JFrame frame = new JFrame();
frame.setTitle("MouseCoordinates");
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(m);
frame.setVisible(true);
}
//...
your problem was creating the Main object twice (which is a jpanel) and then the writing appeared twice. if you give the Main object a reference, then your problem should be fixed.

Related

Changing Jpanel location from Jframe to JDialog

Let's say that I have 1 frame, 1 JDialog and 1 panel. The panel is on the frame. What I want to do is if a button is clicked i wanna switch the location of the panel to JDialog. I need two windows so i use Jdialog for that. Maybe there is a better way of creating that window rather then using JDialog.
Part of my code:
public class Bestellterminal {
private static JPanel panel;
public static void addComponentsToPane(final Container pane) {}
public static void addComponentsToPane1(final Container pane) {}
public static void addComponentsToPane2(final Container pane) {
final JPanel kpanel1 = new JPanel();
kpanel1.setBounds(0 + insets.left, 0 + insets.top, size.width + 900,
size.height + 700);
kpanel1.setVisible(true);
final JDialog meinJDialog = new JDialog();
meinJDialog.setTitle("Küchenterminal");
meinJDialog.setSize(1200,900);
meinJDialog.setVisible(true);
meinJDialog.setLayout(null);
meinJDialog.add(kpanel1);
Classic.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (brclassic == 1) {
if (kunde == 1)
{Bestellpanel.add(buttonx);buttonx.setVisible(true);brclassic++;
kpanel1.add(Bestellpanel);
}
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
addComponentsToPane1(frame.getContentPane());
addComponentsToPane2(frame.getContentPane());
Insets insets = frame.getInsets();
frame.setSize(1200 + insets.left + insets.right,
900 + insets.top + insets.bottom);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I made a simple example using two JFrames, it could be done with any type of container/layout really.
package helloworld;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.BorderLayout;
/**
* Created on 4/30/17.
*/
public class SwapPanel {
public static void main(String[] args){
JPanel panel = new JPanel();
panel.add(new JLabel("mover"));
JFrame a = new JFrame("frame a");
JButton aButton = new JButton("swap");
JFrame b = new JFrame("frame b");
JButton bButton = new JButton("swap");
bButton.setEnabled(false);
a.getContentPane().add(aButton, BorderLayout.SOUTH);
a.getContentPane().add(panel, BorderLayout.CENTER);
b.getContentPane().add(bButton, BorderLayout.SOUTH);
aButton.addActionListener(evt->{
if(aButton.isEnabled()){
aButton.setEnabled(false);
a.getContentPane().remove(panel);
b.getContentPane().add(panel, BorderLayout.CENTER);
bButton.setEnabled(true);
a.pack();
b.pack();
a.repaint();
b.repaint();
}
});
bButton.addActionListener(evt->{
if(bButton.isEnabled()){
bButton.setEnabled(false);
b.getContentPane().remove(panel);
a.getContentPane().add(panel, BorderLayout.CENTER);
aButton.setEnabled(true);
a.pack();
b.pack();
a.repaint();
b.repaint();
}
});
a.pack();
a.setVisible(true);
b.pack();
b.setVisible(true);
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
The main thing that needs to be done, first remove the panel from one layout/container, then add the component panel to another container, and finally validate/repaint.

Components not added to JPanel object

This is a tutorial example and pnl.add(field); pnl.add(txtArea); not compiling. Why not?
import javax.swing.*;
import java.awt.event.*;
class KeyStrokes extends JFrame implements KeyListener {
JPanel pnl = new JPanel();
public static void main (String[] args) {
KeyStrokes gui = new KeyStrokes();
}
JTextField field = new JTextField(38);
JTextArea txtArea = new JTextArea(5, 38);
pnl.add(field);
pnl.add(txtArea);
public KeyStrokes() {
super("Swing Window");
setSize(500, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(pnl);
setVisible(true);
field.addKeyListener(this);
}
public void keyPressed (KeyEvent event){
txtArea.setText("Key Pressed");
}
public void keyTyped(KeyEvent event){
txtArea.append("\nCharacter :" + event.getKeyChar());
}
public void keyReleased (KeyEvent event){
int keyCode = event.getKeyCode();
txtArea.append("\nKey Code :" + event.getKeyText(keyCode));
}
}
That's because you can not make those statements outside of a method, note that you can declare variables in the global scope you are in. Move it to the KeyStrokes() method, just before the setVisible(true) statement. And then KeyStrokes() would be something like this:
public KeyStrokes() {
super("Swing Window");
setSize(500, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(pnl);
pnl.add(field);
pnl.add(txtArea);
setVisible(true);
field.addKeyListener(this);
}

Mouse event doesn't work in java for some reason

Mouse event appears not to work, and i can't find out, why.
I added a debug output at imgEdit.drawDot and there's no output at the console. I'm a newbie in java, so my code may seem to be very bad, as well as my english
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
/**
* Created by doctor on 12/29/15.
*/
public class MainUI {
Window mainWindow;
MainUI() {
mainWindow = new Window();
}
}
class Window extends JFrame {
Window() {
setBounds(0, 0, 600, 400);
setTitle("RebBrush");
Panel mainPanel = new Panel();
Container mainCont = getContentPane();
mainCont.setLayout(null);
mainCont.add(mainPanel);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
class Panel extends JPanel {
private ImageEdit imgEdit;
private JLabel imgLabel;
Panel() {
setLayout(null);
imgEdit = new ImageEdit(600, 400);
imgLabel = new JLabel(new ImageIcon(imgEdit.getImage()));
imgLabel.setBounds(0, 0, 600, 400);
add(imgLabel);
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
imgEdit.drawDot(e.getX(), e.getY());
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
}
}
Simply getting rid of the null layouts did the trick for me. I'm not sure what ImageEdit is (some other class you've defined?), but by running the following I see "Mouse Dragged" show up in the console, so the mouseDragged method is definitely being called. Just uncomment the imageEdit stuff to put it back in.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
/**
* Created by doctor on 12/29/15.
*/
public class MainUI {
Window mainWindow;
MainUI() {
mainWindow = new Window();
}
public static void main(String[] args) {
new MainUI();
}
}
class Window extends JFrame {
Window() {
setBounds(0, 0, 600, 400);
setTitle("RebBrush");
Panel mainPanel = new Panel();
Container mainCont = getContentPane();
mainCont.add(mainPanel);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
class Panel extends JPanel {
//private ImageEdit imgEdit;
private JLabel imgLabel;
Panel() {
//imgEdit = new ImageEdit(600, 400);
//imgLabel = new JLabel(new ImageIcon(imgEdit.getImage()));
//imgLabel.setBounds(0, 0, 600, 400);
//add(imgLabel);
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
System.out.println("Mouse Dragged");
//imgEdit.drawDot(e.getX(), e.getY());
}
#Override
public void mouseMoved(MouseEvent e) {
}
});
}
}

How to add components to the frame?

I am new to Swing programming. And I m trying to develop a desktop application.
First all I need to create a login window, which should not be draggable and its position must be in center of the screen.
So by learning , I have created a window by the following code:
import com.sun.awt.AWTUtilities;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Newframe {
private JLabel label;
JFrame frame;
JButton btn;
Newframe(){
prepareGUI();
}
public static void main(String arg[]) {
Newframe n=new Newframe();
}
public void prepareGUI(){
frame=new JFrame();
frame.setUndecorated(true);
frame.setSize(300, 300);
frame.setVisible(true);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
}
}
Now, I want to add components (e.g textfields, labels, buttons, etc...) to this created frame.
I m trying to add the components to the frame by initialize the components and add them to the frame ( by this frame.add(jbutton)) , but components are not going to add to the created frame...
Can any one help me for this?
frame.getContentPane().add(component)
Note this may vary depending on the layout you use.
Also, it'd be better to put the UI in the Event Dispatch Thread, with this:
public static void main(String arg[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Newframe n=new Newframe();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
You can use below code to add component to the frame and to center the frame you can use frame.setLocationRelativeTo(null);.
public class Newframe {
private JLabel label;
private JTextField txt;
JFrame frame;
JButton btn;
Newframe() {
prepareGUI();
}
public static void main(String arg[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
Newframe n = new Newframe();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void prepareGUI() {
frame = new JFrame();
frame.setLayout(null);
frame.setSize(300, 300);
frame.setUndecorated(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);
label = new JLabel("Name");
label.setBounds(10, 10, 100, 20);
frame.add(label);
txt = new JTextField();
txt.setBounds(50, 10, 100, 20);
frame.add(txt);
btn = new JButton("OK");
btn.setBounds(40, 40, 80, 20);
frame.add(btn);
}
}

Giving a JPanel priority focus

I have a JPanel that is using a KeyListener as the content pane as the window; however, there are buttons and text fields in a grid layout on top of the JPanel.
How do I prioritize the focus of the JPanel that it retains focus after editing text or clicking the buttons so I can read the key input?
You just need to add a FocusListener on the focusLost event and then request focus back again. Something like this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JPanelFocus {
public static void main(String... argv) throws Exception {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("FocusTest");
JButton b = new JButton("Button");
final JPanel p = new JPanel();
p.add(b);
// Here is the KeyListener installed on our JPanel
p.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent ev) {
System.out.println(ev.getKeyChar());
}
});
// This is the bit that does the magic - make sure
// that our JPanel is always focussed
p.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent ev) {
p.requestFocus();
}
});
f.getContentPane().add(p);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
// Make sure JPanel starts with the focus
p.requestFocus();
}
});
}
}
This won't work if you have fields that need to keep the focus though (you mentioned an editable text field). When should key events go to the text field and when should they go to the JPanel?
As an alternative, you could also just make the child components non-focusable.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyPanel extends JPanel implements KeyListener {
public MyPanel() {
this.setFocusable(true);
this.addKeyListener(this);
// for each component
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addItem("Item1");
this.add(comboBox);
// this is what keeps each child from intercepting KeyEvents
comboBox.setFocusable(false);
}
public void keyPressed(KeyEvent e) { ... }
public void keyTyped(KeyEvent e) { ... }
public void keyReleased(KeyEvent e) { ... }
public static void main(String[] args) {
// create a frame
JFrame frame = new JFrame();
frame.setSize(640, 480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add MyPanel to frame
MyPanel panel = new MyPanel();
frame.add(panel);
frame.setVisible(true);
}
}

Categories