我正在使用IntelliJ IDEA的表单编辑器,并将JLabel绑定到我的mouse_input类。我的目标是在表单上获取鼠标的x和y坐标并将它们打印到标签上。一切进展顺利,我的代码总体上可以正常工作,我可以将JLabel文本设置为x和y的值,但是在加载表单时只能设置一次。我一辈子都无法弄清楚如何在表单加载后定期更新值。我是Java和IntelliJ的新手,所以我很可能会缺少一些简单的东西。这是我的代码。
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import static javax.swing.JFrame.*;
public class mouse_input {
private JPanel mouse_pad;
private JLabel label;
private static int x;
private static int y;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
displayJframe();
}
});
}
static void displayJframe(){
// Create blank content frame
JFrame frame = new JFrame("Mouse Input");
frame.setContentPane(new mouse_input().mouse_pad);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.validate();
// Add mouse motion listener
frame.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
// It doesn't like me deleting this
}
@Override
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
frame.revalidate();
}
});
// Set cursor type
frame.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
// Display frame
frame.setVisible(true);
}
private void createUIComponents() {
label = new JLabel();
label.setText("X" + x + "Y" + y);
}
}
现在,我已经进行了一些研究并进行了研究,发现我可以从头开始创建JLabel,但是我真的很想尝试看看是否可以单独使用IntelliJ的gui编辑器,但是我什么也没看到这种性质的周围。再说一次,我可能只是个白痴。我会很感激任何反馈。
从新的应用程序开始
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
// Add mouse motion listener
frame.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
// It doesn't like me deleting this
}
@Override
public void mouseMoved(MouseEvent e) {
int x = e.getX();
int y = e.getY();
label.setText("X" + x + "Y" + y);
frame.revalidate();
}
});
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
贷方https://examples.javacodegeeks.com/desktop-java/swing/java-swing-application-example/