gpt4 book ai didi

java - 用于显示 JPanel 列表的组件/布局管理器

转载 作者:行者123 更新时间:2023-12-01 17:29:11 24 4
gpt4 key购买 nike

有没有办法显示 JPanels 列表并重新排列它们?创建列表可以使用 BoxLayout 来完成,但是如何交换两个 JPanel 呢?小组保持互动也很重要。

我会尝试一个例子:

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

public class PanelList {

private static final class Entry extends JPanel {

public Entry(final int i) {
super();
final JButton button = new JButton("Dialog '" + i + "'");
button.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(Entry.this, "Hello World '"
+ i + "'");
}
});
this.add(button);
}
}

public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame("PanelList");
f.setLayout(new GridLayout(1, 2));
f.add(new BoxLayoutList());
f.add(new JListList());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
});
}

private static final class BoxLayoutList extends JPanel {
private final List<Entry> entries = new ArrayList<>();

public BoxLayoutList() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
int i = 0;
while (i < 10) {
final Entry entry = new Entry(i);
this.add(entry);
this.entries.add(entry);
i++;
}
}
}

private static final class JListList extends JPanel {
private final DefaultListModel<Entry> entries = new DefaultListModel<>();

public JListList() {
final JList<Entry> entryComponent = new JList<>(this.entries);
this.add(entryComponent);
entryComponent.setCellRenderer(new ListCellRenderer<Entry>() {
@Override
public Component getListCellRendererComponent(
JList<? extends Entry> list, Entry value, int index,
boolean isSelected, boolean cellHasFocus) {
return value;
}
});
int i = 0;
while (i < 10) {
final Entry entry = new Entry(i);
this.entries.addElement(entry);
i++;
}
// Example: Swap entries 4 and 2
final Entry buffer = this.entries.get(4);
this.entries.set(4, this.entries.get(2));
this.entries.set(2, buffer);
}
}
}

现在 BoxLayout 是交互式的,但我不知道如何交换条目,就像我对 JList 替代方案中的条目 4 和 2 所做的那样。但在那里我无法与组件交互。

最佳答案

使用 JList1 进行拖放2 重新排序。

  1. How to Use Lists
  2. Drag and Drop and Data Transfer: Intro

关于java - 用于显示 JPanel 列表的组件/布局管理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12675642/

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