Tóm Tắt
Java Swing How to – Position JPanel in the middle of the JFrame
- Back to Layout ↑
Question
We would like to know how to
position JPanel in the middle of the JFrame.
Answer
import
java.awt.Dimension;import
java.awt.GridBagLayout;/
*
w
w
w
.
j
a
v
a
2
s
.
c
o
m
*
/
import
javax.swing.BorderFactory;import
javax.swing.JFrame;import
javax.swing.JPanel;public
class
Main {public
static
void
main(String[] args) { JFrame frame =new
JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(new
MyContentPane()); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); } }class
MyContentPaneextends
JPanel {int
PREF_W = 700;int
PREF_H = 550;public
MyContentPane() { setLayout(new
GridBagLayout()); add(new
JPanelOfInterest()); } @Overridepublic
Dimension getPreferredSize() {return
new
Dimension(PREF_W, PREF_H); } }class
JPanelOfInterestextends
JPanel {int
PREF_W = 400;int
PREF_H = PREF_W;public
JPanelOfInterest() { setBorder(BorderFactory.createTitledBorder("Title"
)); } @Overridepublic
Dimension getPreferredSize() {return
new
Dimension(PREF_W, PREF_H); } }