Java drawing application - java

I need to develop an application which has 3 buttons for drawing a line,a rectangle and a circle. The application should behave like this: user clicks on a button to draw a wanted shape, mouse cursor changes to a dot, user moves the mouse down to some container, draws two dots by clicking the mouse twice at desired locations and then the wanted shape is drawn using those two dots. From the information I have already gathered, I know I should use a MouseClickListener for drawing the dots and then call a shape class with parameters passed from the dot class to draw the shape. What I need to know is what container to use for the shapes, where to put the MouseClickListener in order to allow drawing only in that container and how to restrict the user from drawing any more points until a button is pressed again.
So far this is my code:
`public class MyPanel {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyPanel window = new MyPanel();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyPanel() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 500, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setBounds(10, 25, 474, 336);
frame.getContentPane().add(panel);
JButton btnLine = new JButton("Line");
btnLine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
drawPoint draw = new drawPoint();
}
});
btnLine.setBounds(10, 0, 110, 23);
frame.getContentPane().add(btnLine);
JButton btnRectangle = new JButton("Rectangle");
btnRectangle.setBounds(196, 0, 110, 23);
frame.getContentPane().add(btnRectangle);
JButton btnCircle = new JButton("Circle");
btnCircle.setBounds(374, 0, 110, 23);
frame.getContentPane().add(btnCircle);
}
}
public class drawPoint implements MouseListener {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
getCoordinates
drawAPoint
drawLine(coordinates)
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}

What I need to know is what container to use for the shapes
Typically, components with custom draw are done by subclassing JPanel and overriding the paintComponent method. Less customary, and arguably more clean from an OO perspective, one may subclass JComponent. But you will find far fewer example code on the web via this route.
where to put the MouseClickListener
On the JPanel subclass would probably work.
in order to allow drawing only in that container
You can't really prevent a user from clicking in the JPanel and dragging outside it. But, you can try to detect this condition, and make sure the code ignores this kind of input.
and how to restrict the user from drawing any more points until a button is pressed again.
Use variables. E.g., a boolean variable ready which is true initially, gets set to false when drawing starts and is reset to true only by a button press. And have your drawing points handler check the ready value and only initiate drawing if it is true. You may need other variables to keep track of how many additional clicks are allowed as part of the current drawing operation.

Related

Java: Adding events to dynamically created components

I'm building a UI in Java. I want to create new components, like a JLabel, using a button. So every time I click a button it creates a new JLabel and places them in a specific JPanel.
Then, I want to be able to do some things with the labels based on how the user clicks on them.
With a left mouse press I want them to be able to drag the labels around the screen.
With a right mouse click I want to be open a new window where certain data can be entered, tied to the label (which might involve dynamically creating variables).
I've been toying around with some code I've Googled around for. I can get a button to create new labels in a panel, but when I try to get them to drag, I can only get one label at a time to appear, and after a second button press, moving the label isn't smooth, it jumps around.
I haven't even tried to implement any of the right mouse click things yet. If anyone can point me in the right direction, I'd appreciate it.
public class Testing {
JFrame frame;
//Launch the application.
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Testing window = new Testing();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Create the application.
public Testing() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JPanel area;
JButton btnCreate;
JLabel dragLabel;
frame = new JFrame();
frame.setBounds(100, 100, 511, 542);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setVisible(true);
area = new JPanel();
area.setBounds(10, 11, 477, 404);
frame.getContentPane().add(area);
area.setLayout(new BorderLayout());
btnCreate = new JButton("Create Label");
dragLabel = new JLabel("Drag Me");
btnCreate.setBounds(10, 425, 477, 67);
frame.getContentPane().add(btnCreate);
btnCreate.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
area.add(dragLabel);
area.revalidate();
DragListener drag = new DragListener();
dragLabel.addMouseListener(drag);
dragLabel.addMouseMotionListener(drag);
}
});
}
}
class DragListener extends MouseInputAdapter
{
Point location;
MouseEvent pressed;
public void mousePressed(MouseEvent me) {
pressed = me;
}
public void mouseDragged(MouseEvent me)
{
if(SwingUtilities.isLeftMouseButton(me)){
Component component = me.getComponent();
location = component.getLocation(location);
int x = location.x - pressed.getX() + me.getX();
int y = location.y - pressed.getY() + me.getY();
component.setLocation(x, y);
}
}
}
EDIT - I'm fairly certain the primary issue is in how the JLabel itself is being added to the panel. Every time the button is being pushed it's adding the same label over again, and this is gumming up the works.
Unfortunately, I'm not sure how to deal with that. I've done a bit more digging, and since dynamic variables aren't possible, I'm going to have to use an array or a map or some sort. With that, it appears I can declare arrays of components. Would something like that be necessary for my purposes?
Really odd stuff in your code. I don't want to go everything, and I'm not an expert by any stretch of the imagination, but I tried to remove redundant or contradictory stuff. I suspect a part of what you did was just copy pasting bits without really fitting them into the code.
Anyway, you needed to create the label inside the listener, so that it creates a new one everytime you click. Otherwise you only ever create one label and just reuse the same everytime.
I implemented a dialog on right click to enter the label name, don't know what you wanted to do but at least it detects right clicks.
Also in general it's easier to use layout managers instead of hardcoding everything. Here you had a borderlayout but were ignoring it.
class Main {
//Launch the application.
public static void main(String[] args) {
DrageableLabel window = new DrageableLabel();
}
}
public class DrageableLabel {
public DrageableLabel() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JFrame frame = new JFrame();
Container area = frame.getContentPane();
area.setLayout(new BorderLayout());
JButton btnCreate = new JButton("Create Label");
btnCreate.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isRightMouseButton(e)) {
/*
This is where you create your new window
for now I've added a dialog that takes a string parameter and creates a label with that string
I moved the method code to create a new drageable label outside the actionlistener to make it less confusing and reuseable
Either build w-e you want directly in here
or call a method that does it (which I prefer)
*/
String string = JOptionPane.showInputDialog(frame, "Enter your message", "Messages", JOptionPane.CANCEL_OPTION);
addDrageableLabel(string, area);
} else if (SwingUtilities.isLeftMouseButton(e)) {
addDrageableLabel("Drag me", area);
}
}
});
area.add(btnCreate, BorderLayout.SOUTH);
frame.setBounds(100, 100, 511, 542);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
// This is the method that creates and adds a drageable label
public void addDrageableLabel(String labelName, Container container) {
JLabel dragLabel = new JLabel(labelName);
container.add(dragLabel, BorderLayout.CENTER);
container.validate();
DragListener drag = new DragListener();
dragLabel.addMouseListener(drag);
dragLabel.addMouseMotionListener(drag);
}
}
class DragListener extends MouseInputAdapter {
Point location;
MouseEvent pressed;
#Override
public void mousePressed(MouseEvent me) {
pressed = me;
}
#Override
public void mouseDragged(MouseEvent me) {
Component component = me.getComponent();
location = component.getLocation(location);
int x = location.x - pressed.getX() + me.getX();
int y = location.y - pressed.getY() + me.getY();
component.setLocation(x, y);
}
}

repaint() not working when called from mouse listener method

I am making a Solitaire program as a side project and I am having problems with the paint window I have made.
In the program, I am having a line start at one point that ends at the position of my mouse click. When I click on the window, it successfully reads my clicks and changes the xcor and ycor variables to my mouse click position, but fails to repaint a line using the new coordinates.
public class Game_Play extends JFrame {
public int xcor = 0;
public int ycor = 0;
public void setup() { //sets up JFrame
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(0, 0);
frame.setTitle("Circles");
frame.add(new MouseHandler());
frame.addMouseListener(new MouseHandler());
frame.addMouseMotionListener(new MouseHandler());
frame.setVisible(true);
}
//listener and painting subclass
class MouseHandler extends JPanel implements MouseListener, MouseMotionListener {
//when mouse pressed, the Xcor and Ycor
//will be changed to the current mouse
//x and y cords, then it will call
//repaint() to repaint the line using the
//new Xcor and Ycor locations
public void mousePressed(MouseEvent me) {
System.out.println("mouse pressed");
xcor = me.getX();
ycor = me.getY();
//prints out new cords
System.out.println(xcor + " xcor");
System.out.println(ycor + " ycor");
repaint();
}
public void mouseReleased(MouseEvent me) { //tests to make sure listener is working
System.out.println("mouse released");
}
public void mouseClicked(MouseEvent me) {}
public void mouseEntered(MouseEvent me) {}
public void mouseMoved(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
public void mouseDragged(MouseEvent me) {}
//paints the line with the Xcor and Ycor values
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("repaint check"); //test to see if repaint has been called
g.drawLine(100, 100, xcor, ycor);
}
}
}
Note: repaint() is being called from the MouseListener method mousePressed, I also have tried calling it from different MouseListener and MouseMotionListener methods to no avail.
Note: The paintComponent method notifies me if it has been called successfully, and when I click, the paintComponent method does not execute.
Note: I did notice that if I click on the screen to set the new cords then hit the maximize button on the window, it will successfully call the repaint method with a redrawn line using the new cords.
Note: the setup() method is being called from another class in another file, the code is as follows:
public static void main(String[] args) throws IOException {
deck_Create();
deck_Shuffle();
game_setup();
BufferedImage_array_Setup();
//being called here
Game_Play a = new Game_Play();
a.setup();
//
}
Last Note: I have searched high and low for the fix to this problem, only coming up with similar problems that didn't help me. Any Feedback given is greatly appreciated.
If there are any questions, let me know and I will address them for you in a few.
Thanks!
Some comment on your code:
public void setup() {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(0, 0);
frame.setTitle("Circles");
frame.add(new MouseHandler());// your panel
frame.addMouseListener(new MouseHandler()); // your listener, also a panel, but not the one you added to your frame
frame.addMouseMotionListener(new MouseHandler()); // yet another listener, also not the panel you added to your frame
frame.setVisible(true);
}
You probably meant to write:
public void setup() {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(0, 0);
frame.setTitle("Circles");
JPanel p = new MouseHandler();
frame.add(p);
frame.addMouseListener(p);
frame.addMouseMotionListener(p);
frame.setVisible(true);
}
Note that having your UI components implement listener interfaces is not a good idea. What if you want to have two mouse listeners for different components in the panel? You can't have both listeners on the panel.
A better way is to have the listener interfaces implemented by anonymous classes, following the seperation of concerns guideline.
Another thing is to add the listeners to the components that should handle them. You should be registering these listeners on the panel, not the frame containing the panel.
And finally, you should be setting the panel as the content pane using setContentPane. Usually it's best to have the panel dictate what its size should be by overriding setPreferredSize. In that case you don't need to set the size of the containing frame, rather you call pack to size the frame to the preferred size of its subcomponents.

Drawing a graphical object

I'd like to draw something in JFrame, so i decided to use below code but although it works truly but i don't want to have any ActionListener.
public class Draw
{
public static void main(String[] args)
{
final JPanel jPanel = new JPanel();
JFrame jFrame = new JFrame("Drawing Window");
JButton jButton = new JButton("draw");
jPanel.add(jButton);
jFrame.add(jPanel);
jFrame.setBounds(0, 0, 500, 500);
// first place
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// second place
jButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Graphics graphics = jPanel.getGraphics();
graphics.drawLine(0,0,100,100);
graphics.drawOval(0,0,100,100);
}
});
}
}
as you can see i added the below code inside of ActionPerfomed method:
Graphics graphics = jPanel.getGraphics();
graphics.drawLine(0,0,100,100);
graphics.drawOval(0,0,100,100);
now i want to put it in the first place ( the comment place in the code ) but i will get an error, and if i put it in the second place, i will get no error but it does not draw any things.
It seems that it is necessary to put the drawing methods inside actionPerformed, my question is why? and is there any other way?
graphics.drawLine(0,0,100,100);
graphics.drawOval(0,0,100,100);
These statements need to be moved to an overridden paintComponent(Graphics) method of the jPanel.
The getPreferredSize() method of the panel should also be overridden to return a dimension of 500x500, then, instead of:
jFrame.setBounds(0, 0, 500, 500);
Simply call:
jFrame.pack();
One other option for you is to make the method(paintComponent or paint):
public void paintComponent(Graphics graphics){
graphics.drawLine(0,0,100,100);
graphics.drawOval(0,0,100,100);
}
and call the repaint from actionListener as shown..
public void actionPerformed(ActionEvent action){
repaint();
}
If it is usefull for you you can transform it as you want....

Click button and get draw rectangle

I am new to Java....I studied that we can add two things on frame... I added button and in response by clicking on button I want rectangle as output....but i don't understand that..Why i am not getting output.....
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class customizedgui5 implements ActionListener {
JButton button;
JFrame frame;
public static void main(String[] args) {
customizedgui5 hi = new customizedgui5();
hi.go();
}
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("click me");
button.addActionListener(this);
myclass a = new myclass();
frame.getContentPane().add(button, BorderLayout.CENTER);
frame.getContentPane().add(a, BorderLayout.SOUTH);
frame.setSize(100, 100);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
frame.repaint();
frame.revalidate();
}
}
class myclass extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.orange);
g.fillRect(20, 50, 100, 100);
}
}
I would start by taking a look at Performing Custom Painting.
The main problem in your code is you are getting NullPointerException when you click the button because the reference of frame is null.
It is null because you've shadowed it in the constructor (basically, declared another variable of the same name within the constructor)...
// I'm null..
JFrame frame;
public void go() {
// Not the same as frame above...
JFrame frame = new JFrame();
You are also going to not see any changes because of a number of reasons...
The myclass panel has no size. With BorderLayout, this won't be "too" much of a problem, but...
You've drawing outside of the visible range of the panel. The rectangle you are painting won't appear because it is being painted outside of the width and height of the panel.
The rectangle will appear before you press the button as paintComponent will be called to update the state of the panel once it's made visible on the screen...
The first thing you need to is provide some kind of size hints to the BorderLayout. Try adding...
#Override
public Dimension getPreferredSize() {
return new Dimension(120, 150);
}
To myclass.
You also don't need to repaint the frame, what you really want to repaint is the instance of myclass. Try updating customizedgui5 so that a becomes a instance variable (like frame...
//...
myclass a;
//...
public void go() {
//...
a = new myclass();
//...
}
public void actionPerformed(ActionEvent event) {
a.repaint();
}
Now, the rectangle will still be shown the moment that the panel is made visible on the screen. Sure you could try setting it invisible, but this will affect the layout of the frame, hiding your component to start with, so, instead, we need some kind of flag we can trip so we know when to paint the rectangle. This is easily achieved by using a simple boolean variable, for example...
class myclass extends JPanel {
private boolean paintRect;
public void setPaintRect(boolean paint) {
paintRect = paint;
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(120, 150);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (paintRect) {
g.setColor(Color.orange);
g.fillRect(20, 50, 100, 100);
}
}
}
Then in you actionPerformed method, you just need to set the flag...
public void actionPerformed(ActionEvent event) {
a.setPaintRect(true);
}
You may also want to take a read through Code Conventions for the Java Programming Language. It will make it easier for people to read your code...
When you click on your button, you're calling the method actionPerformed(ActionEvent event)
Take a look at what you did there. Currently, you repaint and re-validate the frame. If you want to add a rectangle to your frame, you need to do so by adding a new component to the frame that will draw the rectangle.
You could add another instance of your myclass JPanel which paints a rectangle like so:
public void actionPerformed(ActionEvent event) {
frame.getContentPane().add(new myclass(), BorderLayout.NORTH);
frame.repaint();
}
This would add your custom rectangle-drawing panel to the North section of your BorderLayout. If you want to add the rectangle "on top of" your button, you should embed your button within a JPanel, then add the rectangle-drawing panel to that instead of your main JFrame

Thread sleep inside of actionPerformed method

First of all I want to say I'm aware this aproach is wrong so I'm asking this question because of pure curiousity. Lets say I have a swing application like this:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ThreadSleeping {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Load");
JLabel label = new JLabel();
public ThreadSleeping() {
panel.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
label.setIcon(new ImageIcon(
"C:/Users/Public/Pictures/Sample Pictures/Tulips.jpg"));
System.out.println("Tulips painted");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
label.setIcon(new ImageIcon(
"C:/Users/Public/Pictures/Sample Pictures/Koala.jpg"));
System.out.println("Koala painted");
}
});
frame.add(panel, BorderLayout.NORTH);
frame.add(label, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(1024, 768);
// frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ThreadSleeping();
}
});
}
}
Basically when I click a Load button I expect that Tulips.jpg image displays then GUI freezes for a 2 seconds and after that I expect that Koala.jpg image displays. But what happens is that: I click on button, GUI freezes for a 2 seconds and Koala.jpg displays. No Tulips.jpg before that. But thing that confuses me is when I put those System.out.println("Tulips painted"); and System.out.println("Koala painted");. So when I click on button it prints "Tulips painted" and after 2 seconds "Koala painted". Can someone tell me whats going on here? Regards.
works in this case, because you programatically freeze ouf Swing GUI, but there is/aren't another update(s), ot another JComponent(s)
doens't works in the case that there are a few another updated to the Swing GUI, Thread.sleep(int) freeze Event Dispatch Thread,
by default all updates to the JComponents XxxModels never will be visible on the JComponents view
example until sleep ended you'll lost all updated to the GUI
The point I intended to make in my comment:
if you sleep the edt, the resulting mis-behaviour is basically unpredictable.
Unpredictable in the sense that you can't know what will happen or not. All we can do, is guess ...
The technical reason is that most ui updates don't happen immediately but are scheduled: we can't really know what's waiting in the line behind us. Remember: it's only one lane, and when in the actionPerformed, it's we that are sitting in it.
For educational reasons, the code below is the original code with a couple of lines to un/comment to demonstrate different scenarios.
[0] resetting the icon before/after sleeping: as you already noticed, the first doesn't show even though the property is taken. Technical reason: visual update happens via label.repaint() which is scheduled on the EDT for latter processing (as its api doc states)
[1] skimming the api doc, we notice another method: paintImmediately(...) which is documented to do exactly what it's name says and allowed - as we are on the EDT - is allowed to be called. Looks like success, the yellow icon shows up.
[2] but wait: being in the center of a Borderline, the label fills that area anyway, independent of whether or not it has an icon. Let's try to put it into a region that requires a re-layout, as f.i. into the south. Back to square [0], yellow icon not showing.
[3] looking into the source of setIcon(..) reveals that layout is ... scheduled again. We learned in square [1] that we can force thingies to happen immediately, in case of layout that would be the pair invalidate() / validate(). Bingo, yellow icon even when in south.
[4] nasty subclass which schedules the icon property setting (note: while contrived here there is nothing in its contract that hinders subclasses to do it!). As the property isn't even set, yellow isn't showing, back to square [0]
At the end of the day (but before going to sleep the EDT :-), there is simply no way to reliably predict the visual outcome during the sleep. And visuals are only the tip of the ice...
/**
* Unpredictable behaviour when sleeping the EDT.
* http://stackoverflow.com/q/15600203/203657
*
* [0] run as-is: property set but yellow not showing
* [1] uncomment paintImmediately: yellow showing in center
* [2] add label to south: yellow not showing
* [3] force immediate in-/validation: yellow showing in south
* [4] subclass label with invoked property setting:
* property not set, yellow not showing
*
*/
public class ThreadSleeping {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Load");
JLabel label = new JLabel() {
// [4] subclass implemented to schedule the property setting
// #Override
// public void setIcon(final Icon icon) {
// SwingUtilities.invokeLater(new Runnable() {
// public void run() {
// superSetIcon(icon);
//
// }
// });
// }
//
// protected void superSetIcon(Icon icon) {
// super.setIcon(icon);
// }
//
};
public ThreadSleeping() {
panel.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Icon firstIcon = new FixedIcon(Color.YELLOW, 100, 100);
Icon secondIcon = new FixedIcon(Color.RED, 500, 500);
label.setIcon(firstIcon);
// check if the property is already set
System.out.println(label.getIcon());
// following lines try to force the output before going to sleep
// [3] paintImmediately + force immediate re-layout
// label.invalidate();
// label.getParent().validate();
// {1] paintImmediately (fine for center, no effect for south)
// ((JComponent) label.getParent()).paintImmediately(0, 0, 5000, 5000);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
label.setIcon(secondIcon);
}
});
frame.add(panel, BorderLayout.NORTH);
// un/comment one of the following, placing the
// label either in CENTER (= sized to fill)
frame.add(label, BorderLayout.CENTER);
// [2] or in SOUTH (= sized to pref)
// frame.add(label, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(1024, 768);
frame.setVisible(true);
}
/**
* Simple fixed size Icon filling its area.
*/
public static class FixedIcon implements Icon {
private Color background;
private int width;
private int height;
public FixedIcon(Color background, int width, int height) {
this.background = background;
this.width = width;
this.height = height;
}
#Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(background);
g.fillRect(0, 0, width, height);
}
#Override
public int getIconWidth() {
return width;
}
#Override
public int getIconHeight() {
return height;
}
#Override
public String toString() {
return "[" + background + " w/h " + width + "/" + height + "]";
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ThreadSleeping();
}
});
}
}

Categories