我正在尝试在单个jframe表单上添加三个面板。如果我只添加三个面板,则将显示它们,但是如果我在拆分窗格上添加面板在以下代码中提出错误
import javax.swing.*;
import java.awt.*;
class paneltest extends JFrame{
paneltest()
{
Container cp=this.getContentPane();
cp.setLayout(null);
panel1 p1= new panel1();
panel2 p2= new panel2();
panel3 p3= new panel3();
cp.add(p1);
cp.add(p2);
cp.add(p3);
Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
p1.setBounds(0,0,screenSize.width/3,screenSize.height);
p2.setBounds(screenSize.width/3,0,screenSize.width/3,screenSize.height);
p3.setBounds(2*(screenSize.width/3),0,screenSize.width/3,screenSize.height);
try{
JSplitPane splitPaneLeft = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
JSplitPane splitPaneRight = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitPaneLeft.setLeftComponent( p1 );
splitPaneLeft.setRightComponent( p2 );
splitPaneRight.setLeftComponent( splitPaneLeft );
splitPaneRight.setRightComponent( p3 );
JPanel panelSplit = new JPanel();
panelSplit.add(splitPaneRight);
cp.add(panelSplit);
panelSplit.setVisible(true);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"exception occured"+ex);
}
}
public static void main(String arsg[])
{
paneltest frm= new paneltest();
frm.show ();
}
}
class panel1 extends JPanel
{
panel1()
{
setLayout(new FlowLayout());
JLabel l1= new JLabel("panel1");
add(l1);
}
}
class panel2 extends JPanel
{
panel2()
{
setLayout(new FlowLayout());
JLabel l1= new JLabel("panel2");
add(l1);
}
}
class panel3 extends JPanel
{
panel3()
{
setLayout(new FlowLayout());
JLabel l1= new JLabel("panel3");
add(l1);
}
}
删除线cp.setLayout(null)
。这将解决最初的问题。
之后:
- 缩进代码
- 尊重Java命名约定
- 如果将它们添加到SplitPanes之后,请不要将面板添加到内容窗格中。可以将组件添加到单亲父母中。将它们添加到两个 上是没有意义的
- 不要使用
setBounds()
。这就是布局经理的角色 - 不要扩展jpanel和jframe。使用它们
- 尊重Swing的线程策略。
- 不要
catch (Exception)