gpt4 book ai didi

Java 按钮创建无法正常工作

转载 作者:行者123 更新时间:2023-12-01 07:35:16 27 4
gpt4 key购买 nike

这是我的程序。这个程序只是使用 java 中的 swing 创建一个框架,然后首先创建一个网格,然后向该框架添加按钮:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class one {
private static void createAndShowGUI() {
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400,400);
frame.getContentPane().setPreferredSize(new Dimension(500,500));
frame.pack();
frame.setVisible(true);
Container pane=frame.getContentPane();
pane.setLayout(new GridLayout(5,6));

JButton[] buttons = new JButton[26];

String b[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(int i = 0; i<buttons.length; i++) {
buttons[i] = new JButton(b[i]);
buttons[i].setSize(80, 80);
buttons[i].setActionCommand(b[i]);
buttons[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
JOptionPane.showMessageDialog(null, "You have clicked: "+choice);
}
});
System.out.println("adding button\n");
pane.add(buttons[i]);
}

}
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

程序编译得很好。但是在创建按钮时我只能看到一个“A”按钮,而其余按钮我在 Pane 中看不到。

最佳答案

事实证明,这似乎是一个竞争条件和/或系统相关类型问题,因为它适用于其他问题。无论如何,Javadoc for java.awt.Container.add()状态:

This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.

因此,您应该在添加所有组件后调用 pane.validate() (或者,如 MadProgrammer 所说,在添加所有组件后执行 setVisible() 调用)。

关于Java 按钮创建无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12949720/

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