- Create a new java
project in Intellij. File → New → Project. You should see the following
dialog. Click next.
- Select
Create project from template and click next.
- In the Project name field, type
SwingIntro and click finish.
- Extend
the Main class with JFrame class. Ensure that you import javax.swing.*;
public class Main
extends JFrame
{
- Modify
the main method as shown below:
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable()
{
@Override
public void run() {
new Main();
}
});
}
- In
the Main class constructor add the following coding
setVisible(true);
- Run
the program. You should be able to see the following window.
- We
have not added any component yet, but you can maximise, minimise. resize
and close the window.
- Close
the window. Notice that even after closing the window, the application is
still running. Let’s fix this by adding the following coding in the Main
class constructor and run the application again.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- Let’s
add a title to our frame and set the width and height of the frame using
the following code to the Main class constructor and run the program.
setTitle("My first swing app");
setSize(500,300);
- We
have a frame, now let's add a canvas. We will use a Panel object as canvas
and set the background color as blue. Then add the panel to frame. You
will have to create an attribute called panel of type JPanel. Run the
program.
panel = new JPanel();
panel.setBackground(Color.BLUE);
add(panel);
- Now
that we have a panel, let’s add some component to the panel. Let's start
by creating a button and adding it to the panel. Add the following code
and run the program.
btn1 = new JButton();
btn1.setText("Click Me");
panel.add(btn1);
- Notice
that nothing happens when you click on the button. We need a listener to
listen and respond to the events related to the button. To add a mouse
listener add the following code to the constructor.
btn1.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent
ae){
btn1MouseClicked(ae);
}
});
- Above
codes adds a new instance of MouseAdapter as the listener. mouseClicked
method is overridden to call the method that would run when the mouse is
clicked.
- Add
a method called btn1MouseClicked to Main class. This method will print
“Hello World!” to console. Run the application. The application should now
print “Hello World!” to the console, every time you click “click me”
button.
- Now
let’s add more components the panel. Add a JLabel to the panel. Set the
text of the label to “test”. Run the program.
- Modify
the btn1.MouseClicked() to set the text of the label to “Hello World!”
whenever the button is clicked.
- Code
a java swing project to create a simplified calculator the can be used for
addition. The calculator will have a label, textfield and a button as
shown below:
|
Comments
Post a Comment