私が持っているコードは、セットボタンを作成しますが、垂直方向に配置されています
今私がしたいのは、このパネルに 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)