如标题中所述.我使用BorderLayout()在另一个上面有两个JPanel.
import java.awt.*; import javax.swing.*; public class myForm(){ public static void main(String[] args) { JFrame myFrame = new JFrame("SingSong"); myFrame.setLocation(100,100); myFrame.setSize(new Dimension(1024,800)); myFrame.setLayout(new BorderLayout()); JPanel jp = new JPanel(); jp.setBackground(new Color(0x00FF00FF)); JPanel jp2 = new JPanel(new BorderLayout()); jp2.setBackground(new Color(0x00000000)); jp.setPreferredSize(new Dimension(100,400)); jp2.setPreferredSize(new Dimension(100,400)); jp2.setLocation(0,512); myFrame.add(jp2,BorderLayout.SOUTH); myFrame.add(jp,BorderLayout.NORTH); } }
它们各占一半,但我怎么能设置它以便它们总是占用JFrame的一半,即使调整大小?
(P.S.我通常使用更好的变量名称,我只是把它作为SSCCE)
解决方法
试试GridLayout
JFrame myFrame = new JFrame("SingSong"); myFrame.setLocation(100,100); myFrame.setSize(new Dimension(1024,800)); GridLayout layout = new GridLayout(2,1); myFrame.setLayout(layout); JPanel jp = new JPanel(); jp.setBackground(new Color(0x00FF00FF)); JPanel jp2 = new JPanel(new BorderLayout()); jp2.setBackground(new Color(0x00000000)); myFrame.add(jp); myFrame.add(jp2); myFrame.setVisible(true);