当前位置:网站首页>Summary of JFrame knowledge points 1
Summary of JFrame knowledge points 1
2022-07-01 11:46:00 【dengfengling999】
MyEclipse Key techniques in :
Class, right click to rename the selected change Refactor—>Rename or alt+shift+R
If you forget how to write words by dictation, you can press and hold Alt+/ Let him remind you
Comment code Ctrl+/ or Ctrl+shift+/
Ctrl+D Delete current row
Ctrl+i Alignment code
SetText(); Set realistic text
Right click Debug As Modulation , You need to set the breakpoint first and right-click the leftmost place where the code is added Toogle Breakpoint
- JPanel, Represents a container , Finished panel .
- JButton, Represents a button control
Set up a container first
JPanel root= new JPanel();
frame.setContentPane(root);;
Then add controls
JButton button new JButton(“ test ”);// Button
root.add(button);
- JLabel lable=new JLabel();// label
root.add(lable);
JLabel lable=new JLabel(" Hello ");
root.add(lable);
// Abbreviation
root.add(new JLabel(" How do you do "));
- Customize a window
Public class MyFrame extends JFrame{
}
- Event handling , Monitor , When the button is clicked , There are 3 Ways to create ( Inner class 、 Anonymous inner class 、Lambda expression )
The first inner class
1 Add a listener class , Realization ActionListener Interface
Class MyActionListener implements ActionListener{
}
2 Set listener
MyActionListener listener =new MyActionListener();
Button.addActionListener(listener);
The second anonymous inner class — simplify
button.addActionListener(new ActionListener() {
});
The third kind of Lambda expression --- More simplified
Button.addActionListener((e)->){
}
Parentheses (e) Is the parameter , Curly braces {} Is the method body .
- Text box control JTextField, Single line text box
JTextField textField=new JTextField(20);//20 Denotes initialization 20 The width of English characters
JTextField Of API:
Set text :
textField.setText(str);
Get text :
Str=textField.getText();
- Check box control JCheckBox
JCheckBox agreeField=new JCheckBox(“ Agree to the user agreement ”);
relevant API
setSelected(true/false);// Initialization setting selected
isSelected(); Is it checked?
addActionListener();// Check or cancel the acquisition event
- The drop-down list .JComboBox
(1) establish JComboBox
JComboBox<String> colorField=new JComboBox<>();
so ,JComboBox It's a generic , Parameter type T It represents the type of data item
(2) Data item API Method
-addItem(T) Add data items ,T The type of is specified at creation , Here is String type , That is, every item Item The data type of is String
-getItemcount() Number of data items
-getItemAt(index) Specify index data items
for example :
colorField.addItem(" red ");
colorField.addItem(" green ");
colorField.addItem(" blue ");
(3) Selected items Access by index
getSelectedIndex(); Get the index of the selected item
setSelectedIndex(); Set initialization selection
remove(index); Security index deleted
(4) Access by data item
getSelectedItem(); Gets the value of the selected item
setSelectedItem();
remove(item);
(5) Event handling
Use addActionListener() Realize the event processing selected by the user
- JLabel Label control
- typeface // style // Font size
Label.setFont(new Font(“ Microsoft Tahoma ”,Font.PLAIN,14));
- The font color Use RGB
Label.setForeground(new Color(255,255,255));
(4) Background color
Label.setOpaque(true);// The background is opaque
Label.setBackground(new Color(0,0,255));
The default background is transparent , So we need to setOpaque() Set to opaque
white :255,255,255 Red :255,0,0 black :0,0,0
green :0,255,0 Blue 0,0,255 yellow :255,255,0
(5) Control size
Label.setPreferredSize(new Dimension(60,30));
(6) text alignment
Label.setHorizontalAlignment(SwingConstants.CENTER);
- Layout device LayoutManager Be responsible for the layout of each sub control
default ,JPanel Bring one with you. FlowLayout Flow layout
LayoutManager layout=new FlowLayout();
Root.setLayout(layout);// setLayout() Set up a layout manager
among ,FlowLayout For child controls, from left to right , Arrange from top to bottom
11. Manual layout , That is, do not use the layout , When the window size changes , The position of child controls will not change adaptively
1 Do not use the layout
root.setLayout(null);
2 Add child control
root.add(a1);
3 Specify the location of the control
a1.setBounds(0,0,100,50); 0,0 Represents the upper left corner Height :100 Width :50
.setBounds(x,y,width,height);
among ,x,y Top left coordinates width,height Width , Height , Unit is pixel
GUI Coordinate system : The upper left corner is the origin ,X Shaft to the right ,Y Axis down
- Custom cloth layout
The layout should implement the following interfaces
LayoutManager,LayoutManager2 among LayoutManager2 Is the new version , Inherited from LayoutManager
- Add a class SimpleLayout, Realization LayoutManager2
Class SimpleLayout implements LayoutManager2{
When adding child controls to this container, call
-void addLayoutComponent(Component comp,Object constraints)
Call this method when the control is deleted
-void removelLayoutComponent(Component comp);
Call this method when the container needs layout
-void layoutContainer(Container parent);
}
- Use custom layout
root.setLayout(new SimpleLayout());
JPanel The upward trace belongs to Container, And all kinds of controls belong to Component
int width=parent.getWidth();// Gets the width of the container
int height=parent.getHeight();// Get the height of the container
Component[] children=parent.getComponents();// Take out all the child controls to get the control array
- Short for custom layout
To make the code simpler , add to LayoutAdapter( Adapter 、 adapter )
First step Declared as an abstract class abstract, There are 3 Two methods are not implemented
When customizing the layout , Direct inheritance layoutAdapter that will do , You can hide unused methods , Just focus on the methods we want to see
- Private layout
Private layout , Only responsible for the layout of the current window
demonstration : Add an inner class
Private class MyCustomLayout extends LayoutAdapter{
}
14. Custom control
Public class MyControl extends JPanel{
// Rewrite the method , Responsible for the drawing of controls
Protected void paintComponet(Graphics g){
Super.paintComponent(g);
…
}
}
among JPanel, It's a container , Is also a control .
… Write in
// Width of control 、 Height
int width=this.getWidth();
int height=this.getHeight();
// Set background color
g.setColor(new Color(225,0,0));
// Draw a rectangle
g.fillRect(0, 0, width, height);// In turn, the coordinates of the upper left corner , Width height
Add to the main form
MyControl c=new MyControl();
Root.add(c);
c.setPreferredSize(new Dimension(100,50))// Set size
15.
(1)RGB 0-255
FF FF FF or (255,255,255) white
00 00 00 or (0,0,0) black
FF 00 00 or (255,0,0) Red
FF FF 0 or (255,255,0) Yellow other colors can be found in Baidu
Color Class represents a color , for example :
new Color(255,0,0); or new Color(Color.RED);// Color.RED Is the red constant
perhaps new Color(0XFF0000); Hexadecimal
(2)RGBA, Colors with transparency indicate . among A representative Alpha transparency , be located 0-255, for example :
Translucent blue :
new Color(0,0,255,128); perhaps
new Color(0x800000FF,true)
(3) To add a second custom label, you need to add ( white ) Background color
Draw an ellipse Oval The peripheral rectangle is taken as the parameter
g.setColor(Color.RED);
g.fillOval(30,30,100,50);//30 30 Is the upper left coordinate ,100 Width 50 Height
Drawing fan
g.setColor(Color.RED);
g.fillArc(30,30,100,50,0,120); startAngle 0 Is the starting angle ,arcAngle 120 Is the arc angle
(4)g.fill Rect() With fil The beginning is the filling effect
g.fillRect(); Filled rectangle

With draw The beginning is stroke
g.drawRect();// Stroke rectangle

g.drawOval();// Stroke ellipse
g.drawArc();/ Stroke sector
(5) Other drawing methods
g.drawLine(); Draw line segments
g.drawImage(); Drawing pictures
g.drawPolygon(); Draw polygon
g.drawString(); Draw text
- The drawing of pictures
(1) Prepare a picture 1.jpg, Put it in data Under the table of contents
Loading pictures , obtain Image object
File file=new File(“data/1.jpg”);
BufferedImage image=ImageIO.read(file);
c.setImage(image);
among ,Image Abstract class ,BufferImage Depending on the specific implementation class
(2)g.drawImage(image,x,y,width,height,observer);
among -image Picture object to draw
-x,y,width,height The position of the drawing observer Set to null
When the window changes every time, it will call paintComponent(Graphics g) Method , The same image will be constantly loaded inside
In order to avoid repeated loading of pictures, it is necessary to put the above loaded picture content in the construction method , Just load it once .
- encapsulation :
Three criteria for good code : Can be read 、 reusable 、 Scalable .
- The frame of the picture
g.drawRect(0,0,width-1,height-1)
Rectangle relevant API
Rectangle rect=new Rectangle(0,0,width,height);
Rect.grow(h,v) To expand outward h v Pixel . When h,v Less than 0 when , To contract
- Icon :
Icon Icon, Usually smaller square pictures 、PNG Format , You can set it yourself , Or get it from the website, for example : Website www.iconfont.cn
Use PictureView Show icons , Just like adding picture display
Image icon=ImageIO.read();
c.setImage(icon);
18. Resource file Resource, Put your finger on src File released under .
Add resource files to src Catalog ,- stay src Add a package res ,- hold png Copy the picture to res Next
Be careful ,bin\ and src\ Directories are synchronized ,Eclipse Will automatically copy a copy of
Loading of resource files :
Path to resource file :“/res/like.png”
Read resources :
InputStream res=this.getClass().getResourceAsStream(“/res/like.png”);// The return is an input stream
Load resources as pictures
Image image=ImageIO.read(res);
19. Package optimization :
Add one at a time try catch More trouble , So the loaded resource file is encapsulated
Optimize PictureView, add to 2 A way
PictureView.setImage(File file)
PictureView.setImage(String resourcePath)
20. Mouse events :
Mouse event use 3 Class listener :
- .addMouseListener(); Click on 、 Press down 、 lift 、 move 、 Removed from the
2.addMouseMotionListener(); Move 、 Drag the
3.addMouseWheeIListener() The mouse wheel turns
The following mouse actions are supported :
The mouse click mousePressed The mouse is raised mouseReleased
Mouse migration mouseEntered Mouse removal mouseExited
Mouse movement mouseMoved Mouse drag mouseDragged
Mouse wheel mouseWheeIMoved
Mouse events are basic events , All controls support , Custom controls are also supported
Parameters of mouse events :
MouseEvent Represents a mouse event
-getPoint() /getX() /getY(): The coordinates of the click , Relative to the upper left corner of the control
-getPointOnScreen()/getXOnScreen()/getYOnScreen(): Screen coordinates
-getSource(): Event source . That is, the control in the point
-getButton() : left-click 、 In the key , Right click
-getClickCount() : stand-alone 、 double-click 、 Three strikes
21.MouseAdapter, Mask mouse events , Used to simplify code
22. Mouse click event :
-mousePressed(); The mouse click
-mouseReleased() The mouse is raised
-mouseClicked() Mouse click , This event is triggered when the mouse is pressed and raised in place
MouseListener And ActionListener:
-MouseListener Low-level events
-ActionListener Senior event
about JButton, You can also use MouseListener
23. Mouse in and out :
-mouseEntered();
-mouseExited();
You can use settings to highlight the state when the mouse moves in , Different displays
24. Mouse movement events MouseMotionListener
-mouseMoved() Mouse movement
-mouseDragged() Press and hold the mouse and move , Drag the
26. Sine curve :
Math.sin(angle) Method can calculate an angle angle The sine of . It should be noted that , there angle To specify the radian value
Curve simulation : Take multiple points on the curve , Like a curve , Use these points drawLine(p1,p2) Method to connect , It is similar to a curve
Sampling point : The denser the sampling points , The closer the result is to a perfect curve , The parameter is called granularity
边栏推荐
- Are the consequences of securities account cancellation safe
- Mechanism and type of CPU context switch
- Learning summary on June 30, 2022
- Web foundation of network security note 02
- 构建外部模块(Building External Modules)
- activity工作流引擎
- sshd_ Discussion on permitrotlogin in config
- redis配置环境变量
- 小米手机解BL锁教程
- Can I open an account today and buy stocks today? Is it safe to open an account online?
猜你喜欢

TEMPEST HDMI泄漏接收 5

S7-1500PLC仿真

Explore the contour detection function findcontours() of OpenCV in detail with practical examples, and thoroughly understand the real role and meaning of each parameter and mode

图的理论基础

Introduction to unittest framework and the first demo

Abbirb120 industrial robot mechanical zero position

Acly and metabolic diseases

CPU 上下文切换的机制和类型 (CPU Context Switch)

CPI tutorial - asynchronous interface creation and use

TEMPEST HDMI泄漏接收 4
随机推荐
Epoll introduction
Ultra detailed black apple installation graphic tutorial sent to EFI configuration collection and system
Openinstall: wechat applet jump to H5 configuration service domain name tutorial
二叉堆(一) - 原理与C实现
Botu V15 add GSD file
陈珙:微服务,它还那么纯粹吗?
CAD如何设置标注小数位
Question: what professional qualities should test engineers have?
超详细黑苹果安装图文教程送EFI配置合集及系统
2022/6/30学习总结
Cann operator: using iterators to efficiently realize tensor data cutting and blocking processing
Xiaomi mobile phone unlocking BL tutorial
Redis启动与库进入
I'm in Zhongshan. Where is a better place to open an account? Is it actually safe to open an account online?
Flip the array gracefully
内核同步机制
Exposure: a white box photo post processing framework reading notes
开发说,“ 这个不用测,回归正常流程就行 “,测试人员怎么办?
Value/sortedset in redis
Redis startup and library entry