我想创建一个按钮,它会在string
内部无法显示时自动调整大小(它太大了)。
我得到了类似的东西:
public class ResizingButton extends JButton {
public ResizingButton(String txt) {
super(txt);
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
setText(JOptionPane.showInputDialog("Text"));
}
});
}
@Override
public void setText(String arg0) {
super.setText(arg0);
FontMetrics metrics = getFontMetrics(getFont());//nullPointerException !!!
int width = metrics.stringWidth(getText());
int height = metrics.getHeight();
Dimension newDimension = new Dimension(width + 40, height + 10);
setPreferredSize(newDimension);
setBounds(new Rectangle(getLocation(), getPreferredSize()));
}
}
我想使用那个类:
public class Zadanie2 extends JFrame {
public Zadanie2() {
createGUI();
}
private void createGUI() {
setSize(200, 80);
//setLayout(new GridLayout());
add(new ResizingButton("tekst"));
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Zadanie2();
}
}
但是我在setText()
方法中得到空指针异常?为什么会发生这种情况,我该如何修复它?getFont()
返回 null 然后getFontMetrics(null)
抛出异常。
堆栈跟踪:
Exception in thread "main" java.lang.NullPointerException
at java.util.concurrent.ConcurrentHashMap.hash(Unknown Source)
at java.util.concurrent.ConcurrentHashMap.get(Unknown Source)
at sun.font.FontDesignMetrics.getMetrics(Unknown Source)
at sun.swing.SwingUtilities2.getFontMetrics(Unknown Source)
at javax.swing.JComponent.getFontMetrics(Unknown Source)
at ResizingButton.setText(ResizingButton.java:26)
at javax.swing.AbstractButton.init(Unknown Source)
at javax.swing.JButton.<init>(Unknown Source)
at javax.swing.JButton.<init>(Unknown Source)
at ResizingButton.<init>(ResizingButton.java:13)
at Zadanie2.createGUI(Zadanie2.java:14)
at Zadanie2.<init>(Zadanie2.java:8)
at Zadanie2.main(Zadanie2.java:20)