How can you generate a JFrame in a Random Location? - java

As in wen you run any output in a frame, every time you run the program it pops on a different position on the screen?

You can use the setLocation(int, int) of JFrame to locate a JFrame in a new location.
So, put this in the frame's constructor and use Random to generate a random location, and your frame will pop up in a random location every time.
Another option would be to override the setVisible(boolean) method of the JFrame.
public void setVisible(boolean visible){
super.setVisible(visible);
if (visible) {
Random r = new Random();
// Find the screen size
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
// randomize new location taking into account
// the screen size, and current size of the window
int x = r.nextInt(d.x - getWidth());
int y = r.nextInt(d.y - getHeight());
setLocation(x, y);
}
}
The code located inside the if (visible) block could be moved inside the constructor. The getWidth() and getHieght() methods may not return the correct values that you expect though.

Use java.util.Random's nextInt(int) along with JFrame.setLocation(int, int).
For example,
frame.setLocation(random.nextInt(500), random.nextInt(500));

If you receive an error such as Cannot make a static reference to the non-static method nextInt(int) from the type Random
you can use the alternative code, frame.setLocation((int)Math.random(), (int)Math.random());
Hope this helps!

Related

JAVA, display phrase in increasing font sizes in a frame

I am having an issue getting this code to run properly. It compiles and initially the frame displays properly. The problem is that when I manually re-size the frame by either maximizing or by dragging the side of the frame over, the text disappears. I am using jGRASP, not sure if that is the issue or not. The code seems to make sense to me, and like I said, it compiles(I know that does not necessarily make it right). I'm still a newbie at this so if anyone can point me in the right direction I would be very appreciative.
import javax.swing.*;
import java.awt.*;
public class JFontSizes extends JFrame {
int x = 5;
int y = 50;
String homework = "This is the first homework assignment";
public JFontSizes() {
super("Increasing Font Sizes");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics brush) {
super.paint(brush);
// This works sometimes. I am not sure if it is a jGRASP issue or something else.
// If I resize the frame, the text disappears, and I cannot get the text to start at the top of the frame
for(int n = 6; n<= 20; ++n) {
brush.setFont(new Font("Serif", Font.PLAIN, n));
brush.drawString(homework, x, y);
y += 15;
}
}
public static void main(String[] args) {
JFontSizes frame = new JFontSizes();
frame.setSize(400, 500);
frame.setVisible(true);
}
}
When first time paint() is called the value of y was 5. And it is incremented in a loop. So that before leaving paint() its value will be 275.
But when you resize your frame paint() is called again and this time the value of y is 275 and when brush.drawString(homework, x, y); is called the homework is printed at 275px bottom from top left corner.
So what you need to do is re-initialize y every time :
public void paint(Graphics brush) {
y = 50;
....
Edit :
As commented by camickr you should override paintComponent(...) instead of paint(...) until you have some specific reason to override paint().
And you mean you are not able to print text at top (even in beginning) then it is because you had initialized y with 50. Which means the text will be drawn at 50px from top.

Java - Get Window Position Without Border

I'm trying to take a window screenshot to use that as background in the application.
This is my code:
try {
Robot robot = new Robot();
Rectangle captureSize = new Rectangle(new MainWindow().getX(), new MainWindow().getY(), MainWindow.getWIDTH(), MainWindow.getHEIGHT());
RenderManager.backgroundGUIs = robot.createScreenCapture(captureSize);
GUIManager.ThisGui = new GUI("inventory", null, false);
} catch(AWTException e) {
System.err.println("Error taking screenshot!");
}
And these are the MainWindow().getY() and MainWindow().getX() methods:
public int getX() {
return (int) frame.getLocationOnScreen().getX();
}
public int getY() {
return frame.getY();
}
Now... it works fine, but there is a problem. frame.getLocationOnScreen().getX() and frame.getX() return the location with the window border, that hasn't to be in the screensot. Ok, i can manually calculate border size to subtract it, but from Windows 7 to Windows 8, from Windows 8 to Mac, etc. window border changes.
So... is there a method to get frame position or window border size to calculate what i need?
Thank you for your time and your answer!
As simple as this:
x = frame.getRootPane().getX();
As well, you can make all other calculations according to the root pane, just dropping the frame's.
As expected, the root pane is the top-level container inside any Frame/Window/Dialog etc. It includes the menubar too.
Use this
frame.getContentPane().getSize();
Check out the Screen Image class. You can create an image of any component displayed on the frame.
So you could use frame.getRootPane() as the component you want the image of.
Or frame.getContentPane() if you don't want the menu bar. I think this method returns a Container object so you will need to cast is to a JComponent.
int mouseX = MouseInfo.getPointerInfo().getLocation().getX() - frame.getX() - frame.getRootPane().getX();
int mouseY = MouseInfo.getPointerInfo().getLocation().getY() - frame.getY() - frame.getRootPane().getY();
This gives the top right point within the border / tab of a frame

Creating a GUI via Netbeans

I have created a GUI via Netbeans Java but whenever I maximize the GUI window the text boxes become misaligned. I used the Netbeans drag and drop function to create the GUI. I was wondering why the text boxes become misaligned whenever I maximize the GUI
It's an issue with the layout.
Read up on using layouts: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
If you are going to use Netbean's GUI builder, run through a tutorial. It'll help you better understand how the builder is to be used. https://netbeans.org/kb/docs/java/quickstart-gui.html
I Understood your problem because I already had the same problem, My advice to you is that you can use the drag and drop of netbeans but before using it first make a panel and in that panel drop all your stuff then using the JFrame Component re sized function just put the panel wherever you want to put it for e.g if you want to center align it.
//if your class is extending JFrame
public static int getWIDTH(){
return WIDTH;
}
public static int getHEIGHT() {
return HEIGHT;
}
private void formComponentResized(java.awt.event.ComponentEvent evt) {
// this is for setting panel in the middle of the JFrame horizontally
int a = getWIDTH();
int b = Panel.getWidth();
a = a/2;
b = b/2;
int centerForX = b - a;
// This is for setting the panel in the middle vertically
int x = getHEIGHT();
int y = Panel.getHeight();
x = x/2;
y = y/2;
int centerForY = x - y;
// Making a 'Point' object and then setting location of the Panel.
Point p = new Point(centerForX , centerForY);
Panel.setLocation(p);
}
Some Keypoints:
1) getWIDTH and getHEIGHT methods will be generated by netbeans write outside all methods but in the class the getwidth and getheight and press ctrl + space and press enter and the getWIDTH and getHEIGHT methods will be generated respectively.
2) the formComponentResized method will be generated by netbeans, just go to design tab and then in the Navigator which is mostly in the bottom left right click on JFrame and then goto events then components and then componentResized.
3) If you have any question don't hesitate to ask, as I have detailed knowledge of this topic.

Keeping the rectangle within JFrame

I know I am being an idiot and that's why I can't figure it out but I am trying to paint a bunch of rectangles with randoms size and position using paintComponent. I am trying to make sure that all of them are painted within the frame. I am able to do it with the following code (snippet) but I am wondering if there is a better way to do it than me hardcoding numbers into the program. Is there a method that I should take a look at that might be what I'm looking for?
Here's the inner class that overrides the paintComponent() method:
class DrawPanel extends JPanel {
public void paintComponent(Graphics g) {
int red = (int)(Math.random()*256);
int blue = (int)(Math.random()*256);
int green = (int)(Math.random()*256);
g.setColor(new Color(red, blue, green));
//The following 4 lines keep the rects within the frame
//The frame is 500,500
int ht = (int)(Math.random()*400);
int wd = (int)(Math.random()*400);
int x = (int)(Math.random()*100);
int y = (int)(Math.random()*100);
g.fillRect(x,y,ht,wd);
}
}
You should base your co-ordinates & sizes on the DrawPanel component size. Also using Random.nextInt instead of Math.random() will make it easier to keep within range based on the current size of the panel:
Random random = new Random();
int ht = random.nextInt(getHeight());
int wd = random.nextInt(getWidth());
int x = random.nextInt(getWidth() - wd);
int y = random.nextInt(getHeight() - ht);
I am wondering if there is a better way to do it than me hardcoding numbers into the program.
Yes there is
call getSize() on the enclosing JPanel, the DrawPanel, so you can see the actual boundaries of the component that is being drawn upon. (edit: or getWidth() and getHeight() as recommended by Lucas -- 1+ to his answer!).
Also, you will usually want to call the super's paintComponent(...) method within the child's override.
Also you will usually want to do your randomization elsewhere, such as in the DrawPanel's constructor so as not to change your rectangles each time you re-size the GUI.
There is a method to get the length and width of the panel you are working in.
getHeight();
getWidth();
These will return the current size of the JPanel you are working in, meaning if you resize the window it'll actually still draw them inside.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#getWidth()

JAVA: size of frame and centering graphical objects

Is there anything obvious wrong with this line of code? I want rectangle to stay centered regardless the size of the window. But this donĀ“t work for some reason, the rectangle stays the same place.
public void run() {
setSize(800, 800);
createEntireFigure();
}
private void createEntireFigure(){
int centerOfWindowWidth = getWidth() / 2;
int centerOfWindowHeight = getHeight() / 2;
GRectWithGLabel ("A String",centerOfWindowWidth, centerOfWindowHeight);
}
Your rectangle size code is only called on rectangle creation, and so it makes sense that the rectangle's position will not change if the GUI is re-sized. You need to somehow listen for size changes in your GUI and call code to re-position the rectangle then for this to work. What graphics library are you using?

Categories