如何使嵌入的Jpanel转到WEST



我在java swing中创建了一个应用程序,并在其中制作了我认为称为嵌入式Jpanel的应用程序,这是我对Jpanel内部Jpanel的理解。为了简单起见,我们将使用面板名称有内容、侧边栏和内容侧边栏

侧边栏是带有按钮的应用程序的侧边栏

内容是应用程序的主要内容

内容侧边栏是内容内部的侧边栏,我使用它是为了使我的设置页面在常规侧边栏之外有自己的侧边栏。

我设置侧边栏向西对齐,内容居中

content.add(contentSidebar, BorderLayout.WEST);之后,它不会使内容侧边栏向西移动,我不知道为什么。

这是我的源代码

package Assets.Settings;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Security implements ActionListener{
JFrame Security;
JPanel sideBar;
JPanel content;
//for sidebar
JButton volume;
JButton security;
JButton contactUs;
JPanel contentSidePanel;
//    JButton twoStep;
//    JButton changePassword;

public void security(){
Security = new JFrame();
sideBar = new JPanel();
content = new JPanel();
contentSidePanel = new JPanel();
sideBar.setPreferredSize(new Dimension(125, 700));
content.setPreferredSize(new Dimension(1000, 700));
content.setBackground(Color.YELLOW);
Security.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Security.setTitle("Anonyomail Security Settings");
Security.setSize(1152, 700);
Security.setLayout(new java.awt.BorderLayout());
contentSidePanel.setLayout( new java.awt.BorderLayout());
volume = new JButton();
security = new JButton();
contactUs = new JButton();
//        twoStep = new JButton();
//        changePassword = new JButton();
volume.addActionListener(this);
contactUs.addActionListener(this);
volume.setText("Volume");
security.setText("Security");
contactUs.setText("Contact Us");
//        changePassword.setText("Change Password");
//        twoStep.setText("2-Step");
security.setBackground(Color.decode("#24a0ed"));


contentSidePanel.setPreferredSize(new Dimension(100, 700));
contentSidePanel.setBackground(Color.BLACK);
//        contentSidePanel.add(changePassword);
//        contentSidePanel.add(twoStep);
content.add(contentSidePanel, BorderLayout.WEST);
sideBar.add(volume);
sideBar.add(security);
sideBar.add(contactUs);

Security.add(sideBar, BorderLayout.WEST);
Security.add(content, BorderLayout.CENTER);
Security.pack();
Security.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == volume){
//open volume
}else if(e.getSource() == contactUs){
//open contact us
}
}
}

编辑

问题是我没有给内容一个边框布局

您调用content.add(contentSidePanel, BorderLayout.WEST),但是您从未将content的布局管理器设置为BorderLayout。我相信JPanel的默认布局管理器是FlowLayout,因此BorderLayout.WEST没有任何含义。

另一个注意事项,似乎你只添加一个东西,contentSidePanel,content。我相信BorderLayoutcontent的大小设置为与contentSidePanel相同的大小,并且指定BorderLayout.WEST将没有效果,因为在中心或东部没有任何东西。尝试将测试JPanel添加到content并将其布局设置为BorderLayout.CENTER,看看我是否正确。

注意:BorderLayout的位置常量在JDK 1.4中从罗盘位置(NORTH,EAST,…)更新为更复杂的常量(PAGE_START,PAGE_END,LINE_START,LINE_ENDCENTER)。因此,应该用BorderLayout.LINE_START代替BorderLayout.WEST的使用。-选自《如何使用BorderLayout》

最新更新