我想要实现的是
创建一个自定义组件(mypanel
),该组件JPanel
扩展JLabel
,其中JButton
和GridBagLayout
通过JFrame
排列。
让mypanel
在垂直堆叠中显示多个mypanel
并使其高度相应更改,具体取决于添加JFrame
的数量(宽度) mypanel
= JFrame
的宽度。
当mypanel
的高度大于屏幕高度时,会显示一个垂直滚动条以进行滚动
我已成功创建JFrame
,但在添加 this.window = new JFrame("ADesktop Notifications");
this.window_panel = new JPanel();
this.window_panel_scroll = new JScrollPane(this.window_panel);
this.window.setBounds(this.top_left_x,this.top_left_y, this.width, this.height);
this.window_panel.setLayout(new FlowLayout());
this.window_panel.setAutoscrolls(true);
this.window.add(this.window_panel);
并设置其大小,滚动条部分方面遇到了很多麻烦。
这是我的jframe的代码
{{1}}
答案 0 :(得分:2)
尝试这个例子(用于动态扩展JFrame)。
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class DynaFrame extends JFrame{
private JPanel basePnl = new JPanel();
public DynaFrame(){
this.setTitle("Dynamic panel addition");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.setSize(600, 700);
this.add(getMainPanel());
this.setLocationRelativeTo(null);
this.pack();
this.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DynaFrame();
}
});
}
public JPanel getMainPanel(){
basePnl.setLayout(new BoxLayout(basePnl, BoxLayout.Y_AXIS));
basePnl.add(getRowPanel());
return basePnl;
}
public JPanel getRowPanel(){
JPanel pnl = new JPanel();
GridLayout gLayout = new GridLayout();
gLayout.setColumns(4);
gLayout.setRows(1);
pnl.setLayout(gLayout);
pnl.add(new JLabel("Filetype"));
pnl.add(new JTextField());
pnl.add(new JButton("Browse"));
JButton addBtn = new JButton("Add");
addBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
basePnl.add(getRowPanel());
DynaFrame.this.pack();
}
});
pnl.add(addBtn);
return pnl;
}
}