Explanation of Swing Class Example in Java

  • 2021-08-28 20:10:57
  • OfStack

Explanation of Swing partial drawing method

Definition Framework


JFrame jFrame=new JFrame(" Title name ");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Sets the user to initiate on this form  "close"  The action to be performed by default when the. 
// There are two options, and the default is  HIDE_ON_CLOSE That is, click Close to hide the interface. 
jFrame.setBounds(0,0,1200,1200);
// Set the size of the frame 
jFrame.setVisible(true);
// Make the frame visible 

Load the background picture into the program


ImageIcon image=new ImageIcon(" File address ");
JLabel label=new JLabel(image);
label.setBounds(0,0,image.getIconWidth(),image.getIconHeight());
// Define the size of the label as the size of the picture 
jFrame.getLayeredPane().add(label);
// Add a label to the JFrame In the framework 

Add a button to the frame


 JButton button=new JButton("hello");
 button.setFont(new Font(" Song Style ",Font.PLAIN,70));
 // Set the font (type, format, size) 
 button.setForeground(Color.red);
 // Set the color of the font 
 button.setBackground(Color.GREEN);
 // Set the color of the button box 
 button.setBounds(400,0,400,400);
 // Set the size of the button 
 button.addActionListener(new ActionListener() {
 int n=1;
 @Override
 public void actionPerformed(ActionEvent e) {
  System.out.println("click"+n+" Times ");
  n++;
 }
 });
 // Add event listening for buttons 
jFrame.getLayeredPane().add(button);
// Add a button to a frame 

Class JPanel


JPanel panel = new JPanel();
panel.setLayout(null);
// Define Layout 
frame.add(panel);
// Add to the panel. 

Text box usage


// Text box 
JTextField userText = new JTextField( Required word limit );
userText.setBounds(100,20,165,25);
panel.add(userText);
// Password text box (which contains * ) 
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);

Related articles: