我拥有的代码创建了一组按钮,但垂直对齐
现在我想做的是在这个面板中添加一个 JLabel,但是当我创建一个新的 JPanel 时,我在运行它时遇到错误,但代码不会给我任何冲突。如果可能的话,我想重新排列流程布局中的按钮。
我的完整代码:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public final class CharSearch extends Box {
int i = 0;
int error = 0;
static JPanel panel;
String original = "Dinosaur";
String secret = new String(new char[original.length()]).replace('\0', '-');
public CharSearch() {
super(BoxLayout.Y_AXIS);
for (char i = 'A'; i <= 'Z'; i++) {
String buttonText = new Character(i).toString();
JButton button = getButton(buttonText);
add(button);
}
JLabel label = new JLabel(secret);
JPanel panel = new JPanel();
panel.add(label);
}
public JButton getButton(final String text) {
final JButton button = new JButton(text);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (original.indexOf(text) != -1) {
JOptionPane.showConfirmDialog(null,
"Your word does contain" + text);
} else {
JOptionPane.showConfirmDialog(null, "There is no" + text);
}
// If you want to do something with the button:
button.setText("Clicked"); // (can access button because it's
// marked as final)
}
});
return button;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setContentPane(new CharSearch());
frame.pack();
frame.setVisible(true);
new CharSearch();
}
});
}
}
这是我运行它时遇到的错误
Exception
是:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at org.informatica.com.CharSearch$2.run(CharSearch.java:50)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)