gpt4 book ai didi

java - 如何动态添加新的自定义按钮?

转载 作者:行者123 更新时间:2023-12-02 07:52:49 26 4
gpt4 key购买 nike

我试图让我的界面在单击按钮时动态生成自定义按钮。我搜索了几个这样的答案,但不知何故它不起作用。我当前的下面的代码有什么错误吗?

  public class MainWindow {

private JFrame frame;
private JPanel panel;
private JPanel panel_1;
private JPanel panel_2;
private JSplitPane splitPane;
private JButton btnSearch;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application.
*/
public MainWindow() {
initialize();
}

/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 645, 438);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

splitPane = new JSplitPane();
panel.add(splitPane);

panel_1 = new JPanel();
splitPane.setLeftComponent(panel_1);

btnSearch = new JButton("Search");

GridBagConstraints gbc_btnSearch = new GridBagConstraints();
gbc_btnSearch.gridx = 0;
gbc_btnSearch.gridy = 10;
panel_1.add(btnSearch, gbc_btnSearch);

panel_2 = new JPanel();
splitPane.setRightComponent(panel_2);

btnSearch.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
addButton();
}
});
}
protected void addButton() {
MyButton hahaButton = new MyButton("haha");
panel_2.add(hahaButton);
panel_2.add(new JButton());
panel_2.revalidate();
panel_2.repaint();
}

这是 MyButton 的定义:

    public class MyButton extends JButton {

private static final long serialVersionUID = 1L;

private Color circleColor = Color.BLACK;

public MyButton(String label) {
super(label);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

Dimension originalSize = super.getPreferredSize();
int gap = (int) (originalSize.height * 0.2);
int x = originalSize.width + gap;
int y = gap;
int diameter = originalSize.height - (gap * 2);

g.setColor(circleColor);
g.fillOval(x, y, diameter, diameter);
}

@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width += size.height;
return size;
}

}

最佳答案

我刚刚尝试了您的源代码,它按预期工作:每次我单击拆分 Pane 左侧的搜索按钮时,都会在面板右侧的面板中添加 2 个按钮(其中一个按钮填充黑色)圆圈和一个没有标签的按钮)。

什么对你不起作用?我在 Mac OSX 上使用 java 1.6,但这也应该适用于其他平台上的早期版本......

关于java - 如何动态添加新的自定义按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10017875/

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