gpt4 book ai didi

java - 每次点击 JList 都会重新绘制 JPanel

转载 作者:行者123 更新时间:2023-11-29 05:36:01 25 4
gpt4 key购买 nike

每次单击 JList 项目时,我需要清除并刷新当前面板并加载另一个面板,该面板通过方法“populateWithButtons()”返回。 temp 是一个 int 变量,用于存储在 JList 中单击的内容。我该如何纠正以下问题?

        list_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {

//refresh + populate JPanel
Food food = new Food();
JPanel panel2 = new JPanel();
JPanel pane11 = new JPanel();


panel2.add(panel1);
panel1.validate();
panel1.repaint();
panel1.setBounds(153, 74, 281, 269);

panel1.add(food.populateWithButtons(temp));
contentPane.add(panel2);
}

最佳答案

  1. 不要使用NullLayout

  2. 添加 ListSelectionListenerJList而不是 MouseListener , 否则你需要将点从鼠标转换为 JList 中的项目

  3. 使用 CardLayout而不是添加,删除JPanel s 在运行时,然后从 ListSelectionListener 中选择(ListSelectionModelSINGLE...)以切换准备好的卡片(JPanel有一些内容)

编辑

enter image description here

.

enter image description here

.

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class CardlayoutTest {

private Color[] colors = new Color[]{Color.BLACK, Color.RED, Color.GREEN, Color.BLUE};
private JFrame frame = new JFrame();
private JList list = new JList();
private JPanel panel = new JPanel();
private CardLayout card = new CardLayout();

public CardlayoutTest() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setLayout(card);
Vector<String> items = new Vector<String>();
for (int x = 0; x < colors.length; x++) {
JPanel pnl = new JPanel(new BorderLayout());
pnl.setBackground(colors[x]);
panel.add(pnl, colors[x].toString());
items.add(colors[x].toString());
}
list = new JList(items);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
String card = list.getSelectedValue().toString();
CardLayout cL = (CardLayout) (panel.getLayout());
cL.show(panel, card);
}
}
});
frame.add(new JScrollPane(list), BorderLayout.WEST);
frame.add(panel);
frame.setPreferredSize(new Dimension(400, 150));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CardlayoutTest();
}
});
}
}

关于java - 每次点击 JList 都会重新绘制 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19510789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com