我有一个JFrame
,有三个区域:
单击列表中的项目时,将填充面板上的文本字段,并创建第二个滚动条上的标签。我的代码有两个问题:
这里我试着举个例子:
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
JPanel geral = new JPanel();
JPanel lista = new JPanel();
JPanel dados = new JPanel();
JPanel paneHist = new JPanel();
JPanel historico = new JPanel();
GridLayout gridLay = new GridLayout(0, 2, 5, 10);
geral.setLayout(gridLay);
dados.setLayout(gridLay);
historico.setLayout(new BorderLayout());
lista.setLayout(new BorderLayout());
paneHist.setLayout(gridLay);
this.setLayout(new BorderLayout());
this.add(geral);
geral.add(lista, BorderLayout.WEST);
geral.add(dados, BorderLayout.EAST);
geral.add(historico, BorderLayout.SOUTH);
DefaultListModel listModel = new DefaultListModel();
listModel.addElement("just testing");
final JList list = new JList(listModel);
list.setLayoutOrientation(JList.VERTICAL);
list.setVisible(true);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(100, 500));
lista.add(scroll, BorderLayout.CENTER);
JTextField jtf = new JTextField();
dados.add(new JLabel("test:"));
dados.add(jtf);
list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent lse) {
jtf.setText("clicked");
paneHist.add(new JLabel("texttexttext"));
paneHist.add(new JLabel("texttexttext"));
}}
);
JScrollPane scrollHist = new JScrollPane(paneHist);
scrollHist.setPreferredSize(new Dimension(500, 100));
historico.add(new JLabel("Historico:"), BorderLayout.NORTH);
historico.add(scrollHist, BorderLayout.EAST);
//list.setCellRenderer(new CellRenderer());
this.validate();
this.repaint();
}
答案 0 :(得分:1)
无法从发布的代码中真正说出你在做什么。
一些一般性意见:
不要使用setPreferredSize()。让每个组件确定其首选大小。对于JList,您可以使用setVisibleRowCount(...)
方法,以便JList可以计算合理的大小。
在ListSelectionListener中,当您从可见的GUI添加/删除组件时,您需要revalidate()
和repaint()
面板。