【发布时间】:2015-10-24 00:51:10
【问题描述】:
由于工作变动,我不得不从 Python TKinter 迁移到 Java Swing。
我遇到的问题是:
如何在JTabbedFrame 的左上角定位包含标签和文本字段等对象的面板。
如果 frame 本身比 panel 大,JPanel 在页面上默认居中。
到目前为止,这是我的代码:
public class GUI {
//Constructor
GUI(){
//Craete a new frame
//borderlayout
JFrame jfrm = new JFrame("Tabbed Demo");
//Intialize size
jfrm.setSize(500, 250);
//Terminate program
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create Tabbed Frame
JTabbedPane jtp = new JTabbedPane(JTabbedPane.TOP);
//Create a panel to place on tabbed page
JPanel jpnl = new JPanel();
jpnl.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5,5,5,5);
jpnl.setOpaque(true);
jpnl.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
//create a 3 labels horizontally
gbc.gridx=1;
gbc.gridy=0;
JLabel title= new JLabel(" Tracking System ");
title.setFont(new Font("Serif", Font.PLAIN, 40));
jpnl.add(title,gbc);
gbc.gridx=0;
gbc.gridy=1;
JLabel subtitle= new JLabel("First");
subtitle.setFont(new Font("Serif", Font.PLAIN, 18));
jpnl.add(subtitle,gbc);
gbc.gridx=1;
gbc.gridy=1;
JTextArea firstText = new JTextArea("Type Here!");
firstText.setFont(new Font("Serif", Font.PLAIN, 18));
jpnl.add(firstText,gbc);
gbc.gridx=0;
gbc.gridy=2;
JLabel subtitle2= new JLabel("Last");
jpnl.add(subtitle2,gbc);
subtitle2.setFont(new Font("Serif", Font.PLAIN, 18));
//add to Tab
jtp.addTab("Demo", jpnl);
//make visible
jfrm.getContentPane().add(jtp);
jfrm.setVisible(true);
}
public static void main(String[] args) {
// launch app
//create the frame on the event dispaytching thread
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new GUI();
}
});
}
}
结果如下图
我想要做的是将JPanel的位置移动到左上角,无论框架有多大,例如标签页的位置0,0。覆盖JPanel的居中。
我正在使用GridBaglayout 经理。
【问题讨论】:
-
GridBagLayout 有点烂。我建议改用 MigLayout。它可以做 GBL 可以做的所有事情,甚至更多,而且使用起来更加简洁和易于管理。
-
有什么好的MIGLayout教程可以提供链接
-
只需查看主页上的快速入门指南和备忘单:miglayout.com
-
您可以通过设置最后一个组件的 weightx 和 weighty 属性来使用 GridBagLayout 来实现这一点
标签: java swing jpanel gridbaglayout jtabbedpane