简体   繁体   English

在Java中将Dimension转换为int?

[英]Convert Dimension to int in Java?

absolute java noob here. 绝对Java Noob在这里。 I was messing with some code and wondering if there is a way to convert a Dimension value to an integer or string. 我搞砸了一些代码,想知道是否有一种方法可以将Dimension值转换为整数或字符串。

I was using this line 我在用这条线

int i = (int) frame.getSize();

to get the size of a window but it cannot convert a dimension to int. 获取窗口的大小,但无法将尺寸转换为int。 Any help? 有什么帮助吗?

You cannot "convert" a Dimension to int , because it is something different. 您无法将Dimension “转换”为int ,因为它有所不同。 It is meant to store information about a rectangle. 它旨在存储有关矩形的信息。

You can calculate the area of the rectangle: 您可以计算矩形的面积:

double size = frame.getSize().getHeight() * frame.getSize().getWidth();

Of cause you can also store the information as a string: 当然,您也可以将信息存储为字符串:

String sizeStr = frame.getSize().getHeight() +" X " + frame.getSize().getWidth();

Now you could store the Dimension (but you would need to split the string again, to get the value. 现在您可以存储Dimension(但是您需要再次分割字符串以获取值)。

frame.getSize(); frame.getSize();

This is returning an Dimension object. 这将返回Dimension对象。 You cannot convert and object to primitive type. 您不能转换并反对为原始类型。

The Dimension have two attribute, height and width. 维度具有两个属性,高度和宽度。 You can use getter methods to access them. 您可以使用getter方法来访问它们。

double getHeight() : Returns the height of this Dimension in double precision. double getHeight():以double精度返回此Dimension的高度。

double getWidth() : Returns the width of this Dimension in double precision. double getWidth():以double精度返回此Dimension的宽度。

The size of the Window can be calculated using Height and Width . 可以使用HeightWidth计算窗口的大小。 As both are of double type, you need to store the size in double type. 由于两者均为double型,因此您需要将尺寸存储为double型。

Dimension dim = frame.getSize();
double size = dim.getHeight() * dim.getWidth();

You cannot cast an Dimension to a primitive. 您不能将Dimension转换为基本体。 What you could do, however, is use the access methods, such as getHeight() and getWidth() to calculate it: 但是,您可以做的是使用访问方法,例如getHeight()getWidth()来计算它:

// No need to explicitly cast, Java will do that automatically
// (although it will issue a warning on lost precision)
int size = frame.getHeight() * frame.getWidth();

The dimension object instantiated as follows; 尺寸对象的实例如下:

Dimension dim = new Dimension(100, 50);

That means, there are two factors, which you should think of, these are height and weight. 这意味着,您应该考虑两个因素,即身高和体重。

If you simply say, 如果你简单地说,

int i = (int) frame.getSize(); 

it is like; 它像是;

int i = (int) height, weight. 

Briefly, you cannot assign two values to one variable. 简要地说,您不能将两个值分配给一个变量。 You should make some calculation(s) to have one value from these two values. 您应该进行一些计算以从这两个值中得出一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM