Useful Tips

Java GUI

Pin
Send
Share
Send
Send


At this point, the grid will not do anything special, but if you want to experiment a bit, you can add ActionListener listeners and a bit of logic to make a simple 2D game like tic-tac-toe or a more complex one like Sea Battle.

Please note: In this article, Eclipse is used for all examples, so there may be some differences depending on what you use>, but it is almost useless for such graphics> mainly due to the use of the drag-and-drop method (dragging and dropping objects) in this environment.

  1. 1 Create a Java project. It is pretty simple. Launch your development environment and create a new project. Call him what you wish. In our example, this will be a buttongrid.
    • The name does not matter, as it is simply the name of the file.

2 Create a Java class with the main method. Create a new class and name it as you wish. In our example, this will be a buttongrid. Eclipse users just click on the field labeled "public static void main (string [] args)", i.e. you won’t need to type it yourself.

    This name is more important. than the previous one, since it should consist of one word, otherwise it cannot be used.

  • 3 Import the libraries. This way you will have access to all the information you need to write your code. You need to import javax.swing.JFrame, javax.swing.JButton and java.awt.Gr> Create a constructor. The constructor creates an instance of the buttongr class> Create the main window (frame):
    1. The frame must have a name. So that it can be referenced outside the ButtonGr constructor>
    2. Inside the constructor, we need to make sure that all the buttons are placed on the grid. To do this, we need to set the placement in the frame by typing the following: frame.setLayout (new GridLayout (x, y)),

    Not absolutely necessary, but for the main window to close when you click on the "x" button in its upper right corner, we need to add the line: frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE),

    In order to set the frame to the correct size, and so that it contains everything we need, we need to execute the packing command: frame.pack (),

    The last thing to do with a frame is to make it visible: frame.setVisible (true),

    6 Create a grid with buttons:

      We need to create buttons that the user interacts with, but since we don’t know how many buttons we need, we just need to declare them first. Therefore, immediately after the frame creation line, declare the buttons: JButton [] [] grid. Two pairs of square brackets mean that the JButton instances on the grid will be contained in two-dimensional format. If there were one pair of brackets, then this would mean a simple line of JButton buttons, which also works. But it’s much easier to refer to the created button or to interact with the button if they are declared as a two-dimensional array.

    1. We announced the JButton buttons, but did not indicate how many of them. In the constructor, you need to add a line of code that sets this number: gr>
    2. Now it is determined that there will be a certain number of buttons, and each of them needs to be created. The easiest way to do this is to use a double loop, one along the x axis and the other along the y axis. Inside this double loop, we create a new button, and to simplify the subsequent link in our example, we will place text inside each button to know where each of the buttons of the two-dimensional array is located. To create a button inside the loop we need to write gr),

      Hacker # 183. Malware for Android

      AWT was Sun's first attempt at creating a graphical interface for Java. They went the easy way and simply made a layer in Java that calls methods from libraries written in C. Library methods create and use graphical components of the operating environment. On the one hand, this is good, since a Java program is similar to other programs within this OS. But on the other hand, there is no guarantee that differences in component sizes and fonts will not spoil the appearance of the program when running it on another platform. In addition, in order to provide multi-platform, it was necessary to unify the component call interfaces, due to which their functionality turned out to be a bit truncated. And the set of components turned out to be quite small. For example, AWT has no tables, and buttons do not support displaying icons.

      Used resources AWT tries to release automatically. This complicates the architecture a bit and affects performance. Mastering AWT is quite simple, but writing something complicated will be a little difficult. Now it is used except for applets.

      Advantages:

      • part of the JDK,
      • speed of work
      • graphic components are similar to standard ones.

      Disadvantages:

      • the use of native components imposes restrictions on the use of their properties. Some components may not work at all on non-native platforms,
      • some features, such as icons and tooltips, are not available in AWT at all,
      • there are very few standard AWT components, a programmer has to implement a lot of custom ones,
      • the program looks different on different platforms (may be crooked).

      conclusion:

      Currently, AWT is used extremely rarely - mainly in older projects and applets. Oracle has tidied up the training and encourages the move to Swing. It is understandable, direct access to the axis components can become a serious security hole.

      What does Swing look like?

      Following AWT, Sun developed a set of graphics components called Swing. Swing components are fully written in Java. 2D is used for rendering, which brought with it several advantages at once. The set of standard components far surpasses AWT in variety and functionality. It has become easy to create new components, inheriting from existing ones and drawing whatever your heart desires. Support for various styles and skins has become possible. However, the speed of the first versions of Swing left much to be desired. An incorrectly written program could completely hang Windows tightly.

      However, due to its ease of use, rich documentation, and the flexibility of its components, Swing has become perhaps the most popular graphics framework in Java. Many extensions have appeared on its basis, such as SwingX, JGoodies, which greatly simplify the creation of complex user interfaces. Almost all popular Java programming environments include graphic editors for Swing forms. Therefore, to understand and start using Swing is not difficult.

      Advantages:

      • part of the JDK, no need to install additional libraries,
      • Swing has a lot more books and answers on the forums. All problems, especially for beginners, are thoroughly known by Google,
      • built-in form editor in almost all development environments,
      • based on swing there are many extensions like SwingX,
      • support for various styles (Look and feel).

      Disadvantages:

      • a window with many components starts to slow down,
      • working with layout managers can be a real nightmare in complex interfaces.

      Conclusion:

      Swing lived, Swing alive, Swing will live. Although Oracle is trying to promote JavaFX, Swing is by far the most popular Java user interface framework.

      SWT: weather widget

      To demonstrate the capabilities of the most popular graphic libraries and the basic principles of working with them, we will make several small widgets displaying various information.

      And let's start, perhaps, with the most popular widget - displaying the current weather, for the implementation of which we choose SWT.

      Any SWT program starts with creating a Display object. It serves as a kind of application context, which contains the necessary methods for accessing system resources and provides an event loop. The next step is to create an equally important Shell object. Shell is a normal operating system window. Display is passed to the shell constructor to create a top-level window.

      Since we are creating a widget, we do not need to display the standard window border and control buttons; for this, we specified the NO_TRIM flag. For the background, we will use the picture - a rounded rectangle. In principle, a SWT window can take any form. To achieve this effect, we use the Region class. All that is needed is to add to this class all visible points from the background image, skipping transparent ones.

      In images of different formats, transparency is set differently, therefore, information about transparent areas is also not extracted the same way. Create a background area and add all the visible points there:

      Set the window shape:

      Now you need to create an event listener for the window. We will be interested in window drawing events, mouse events, and keystrokes so that the window can be moved around the screen.

      So, by pressing the Esc key, the window closes. When you click the left mouse button on the window area, remember the coordinates of the click. When the mouse moves with the left button pressed, we move the window on the screen according to the movement. At a redraw event, we draw a background image using the GC graphics context.

      Assign the listener to the corresponding window events:

      Set the window size to the image size:

      Open the window and start the event loop:

      Do not forget to free up used resources at the end:

      By launching the program at this stage, we get a rectangle that can be moved with the mouse and closed by Esc.

      It's time to add content. We will display the current weather in the form of a status icon (sunny, rain, snow ...), temperature readings and time of the last update.

      Layout managers are used to position graphic components in a window in the required form. The layout manager is engaged not only in the arrangement of components, but also in resizing them when resizing a window. For our widget we will use GridLayout. This manager arranges components in cells of an imaginary table. Create a GridBagLayout for two columns with different column widths (false flag in the constructor), set it as a window layout manager:

      For the status picture we use the Label component. We pass the window object as the parent. The second parameter you can set the style of the component. For each component, the set of possible style flags is different, you can see them in the documentation or directly in the component source.

      Flags in the GridData class mean that the label will be located at the top left, will be stretched horizontally and vertically (flags set to true) if there is free space and will occupy one row and one column of the layout table.

      There is no transparent background of components in SWT, and a white background will flaunt behind the status picture, which, of course, would not be desirable. Therefore, create a Color object with the background color of the window:

      At the end of the program, this object must also be cleared by calling the dispose method. Set the background color and the status picture, which can be downloaded from the file in the same way as we downloaded the background picture at the beginning:

      Now add a Label with the current temperature and place it in the upper right part of the window:

      Set some temperature:

      To record the temperature in Celsius, the unicode number of the corresponding symbol with the service characters u is used.

      The default font for text labels is too small. So create a new, bigger one:

      FontData [] fD = temperatureLabel.getFont (). GetFontData (), fD.setHeight (30), fD.setStyle (SWT.BOLD), Font newFont = new Font (display, fD), temperatureLabel.setFont (newFont), Font , like other resource objects, you need to free. To do this, use the label destruction event listener:

      Finally, add a label with a description of the weather conditions:

      The text can be quite long, so when creating a label, specify the WRAP flag so that the text automatically splits into several lines when there is not enough space. Center the component and let it fill the entire horizontal space. We also indicate that the component occupies two columns of the layout table. We launch and get a window from the Weather Widget picture.

      Weather widget

      Now you can fasten some weather service, create a timer for automatic updating - and the widget is ready.

      Swing, AWT & SWT

      Jan 29, 2012 9:44 p.m.

      There is a code snippet:

      help implement the cursor over the cell.
      example:

      Jan 29, 2012 21:54

      There is a code snippet:

      help implement the cursor over the cell.
      example:

      Inherit your class from the Component class and start reading about Mouse [Motion] Listener:

      Jan 29, 2012 10:44 p.m.

      Sorry, from English. not really with me.
      From what I understood, did so, for some reason it doesn’t work = (

      somewhere on the top edge of the window it works, it’s not clear.

      Jan 29, 2012 10:54 PM

      Sorry, from English. not really with me.
      From what I understood, did so, for some reason it doesn’t work = (

      somewhere on the top edge of the window it works, it’s not clear.

      Jan 29, 2012 23:32

      I apologize for importunity.

      Actually, what am I trying to achieve:
      1. Create a grid.
      2. When you click on one of the cells, change its color.

      Here is what I have:

      Could you point out the flaws?

      Until now, I wrote in "actionscript" for this a lot is not clear.
      Sorry again and thanks for the help.

      Jan 30, 2012 07:19

      Try JTable or GridLayout.
      It is also probably better to place one listener and handler in the parent component, which will receive the cell object by the coordinates of the click and change its color.

      Jan 30, 2012 08:19

      Thank you, I did so (by reviewing a bunch of videos from YouTube).
      Here is the result:

      But then a new problem was born = (

      If I create a JFrame with a size (for example) of 700x500px, it turns out that to the right of the created mesh there is an indent width of 200px i.e. free, unused area.
      The question is: - Why do mouse receivers continue to respond if the mouse cursor is outside the grid itself?
      I just want to understand how JPanel works and whether to use it at all.

      One more incomprehensible moment:
      There is a JFrame 500x500px. I add in it the 2nd "JPanel" - and.
      It is logical that one of them is under the other, but here's how to move and set the width for them.
      I can not find the answer, i.e. I saw examples, but everything around me is something wrong with my hands.

      Thanks again for helping.

      Jan 30, 2012 10:07 a.m.

      If I create a JFrame with a size (for example) of 700x500px, it turns out that to the right of the created mesh there is an indent width of 200px i.e. free, unused area.
      The question is: - Why do mouse receivers continue to respond if the mouse cursor is outside the grid itself?
      I just want to understand how JPanel works and whether to use it at all.

      One more incomprehensible moment:
      There is a JFrame 500x500px. I add in it the 2nd "JPanel" - and.
      It is logical that one of them is under the other, but here's how to move and set the width for them.
      I can not find the answer, i.e. I saw examples, but everything around me is something wrong with my hands.

      Pin
      Send
      Share
      Send
      Send