The Java development environment uses OpenJDK 11.0.4 installed on Ubuntu 18.04.
In Previous article, the application window was displayed. This time we will create a display area inside the window. In the previous code, the goal was to display the application window using Jframe for the time being, so I wrote all the code in the main method, but considering the ease of writing and reading in the future, I decided to use the MyFrame method. Created and instantiated in the main method.
MyFrame.java
import javax.swing.JFrame;
public class MyFrame extends JFrame{
public static void main(String[] args) {
MyFrame frame = new MyFrame("Java Swing test");
frame.setVisible(true);
}
MyFrame(String title){
setTitle(title);
setSize(500, 600); //Window size(width,height)
setLocationRelativeTo(null); //Display window in the center of the screen
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // x(X)Quit the application with the button.
}
}
JavaSwing has a layered structure in which the base JFrame and panels and buttons are placed on it. Since JFrame only displays a window, let's create a panel that displays the numbers required for the calculator app.
MyFrame.java
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
import java.awt.FlowLayout;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Container;
public class MyFrame extends JFrame{
public static void main(String[] args) {
MyFrame frame = new MyFrame("Java Swing test");
frame.setVisible(true);
}
MyFrame(String title){
setTitle(title);
setSize(500, 600); //Window size(width,height)
setLocationRelativeTo(null); //Display window in the center of the screen
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // x(X)Quit the application with the button.
setLayout(new FlowLayout());
JPanel panelDisplay = new JPanel(); //Panel instantiation
panelDisplay.setPreferredSize(new Dimension(500, 60)); //Panel size
panelDisplay.setBackground(new Color(51, 51, 51)); //Color code#333333
BevelBorder border = new BevelBorder(BevelBorder.RAISED);
panelDisplay.setBorder(border);
Container contentPane = getContentPane();
contentPane.add(panelDisplay);
}
}
The execution result is as shown in the figure below. This time, the panel size was set to 500 x 60 and the color was set to # 333333. After this, there are also arrangements such as buttons, so there may be changes in size etc.