当前位置: 技术问答>java相关
关于JFrame中的setSize方法的疑问
来源: 互联网 发布时间:2017-04-23
本文导语: 这是我的测试代码 import javax.swing.*; import java.awt.*; import java.awt.event.*; class test { public static void main(String[] args) { TestFrame frame = new TestFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); } } class Te...
这是我的测试代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class test
{
public static void main(String[] args)
{
TestFrame frame = new TestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class TestFrame extends JFrame
{
public TestFrame()
{
setSize(200, 300);
TestPanel panel = new TestPanel();
this.getContentPane().add(panel);
}
}
class TestPanel extends JPanel
{
public TestPanel()
{
JLabel label = new JLabel("Hello!");
add(label);
this.addMouseListener(new MouseAction());
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
removeAll();
g2.drawString(x + " " + y, 20, 20);
}
private class MouseAction implements MouseListener
{
public void mouseClicked(MouseEvent event)
{
x = event.getX();
y = event.getY();
repaint();
}
public void mouseReleased(MouseEvent event){}
public void mousePressed(MouseEvent event){}
public void mouseEntered(MouseEvent event){}
public void mouseExited(MouseEvent event){}
}
private double x;
private double y;
}
setSize(200, 300) 我用鼠标事件测试右下方的坐标,显示并不是(200, 300)
难道setSize()的参数不是以象素为单位的??
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class test
{
public static void main(String[] args)
{
TestFrame frame = new TestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class TestFrame extends JFrame
{
public TestFrame()
{
setSize(200, 300);
TestPanel panel = new TestPanel();
this.getContentPane().add(panel);
}
}
class TestPanel extends JPanel
{
public TestPanel()
{
JLabel label = new JLabel("Hello!");
add(label);
this.addMouseListener(new MouseAction());
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2 = (Graphics2D)g;
removeAll();
g2.drawString(x + " " + y, 20, 20);
}
private class MouseAction implements MouseListener
{
public void mouseClicked(MouseEvent event)
{
x = event.getX();
y = event.getY();
repaint();
}
public void mouseReleased(MouseEvent event){}
public void mousePressed(MouseEvent event){}
public void mouseEntered(MouseEvent event){}
public void mouseExited(MouseEvent event){}
}
private double x;
private double y;
}
setSize(200, 300) 我用鼠标事件测试右下方的坐标,显示并不是(200, 300)
难道setSize()的参数不是以象素为单位的??
|
对的,setSize设置的width和height把标题栏和边框都算进去了,而鼠标位置坐标是除掉标题栏和边框的,因此有这种结果
您可能感兴趣的文章:
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。