fun*_*rax 3 java swing instantiation inner-classes
我不明白内部类 CHameleon 的功能。我不明白第8行理论上意味着什么。
我认为这意味着生成将在内部类外部访问的 JFrame 的重复版本,以便操作预期的 JFrame 对象。
编辑:代码带来空指针异常错误,因为 JFrame 对象从未被引用。解决方案:将JFrame框架修改为最终的JFrame框架。
这就提出了一个问题:如果有多个 JFrame 怎么办?
例如,如果我有一个班级花园,里面有不同的蔬菜,我创建了一个内部班级色板来为这些蔬菜着色。是创建针对特定蔬菜的特定类的唯一解决方案吗?因此,为了回答我自己的问题,在多个 JFrame 的情况下,它们会显示为不同类型的类,我的情况是?
public class LabelsButtonsPanelsandSnakes {
public static void main(String[] args){
final JFrame frame = new JFrame("Test");
JMenuBar menuBar = new JMenuBar(); //menubar
JMenu menu = new JMenu("Menu");
JMenuItem chameleon = new JMenuItem("Change Color");
class CHameleonaction implements ActionListener{ //inside class opens
JFrame frameHolder; //line 8
public void actionPerformed(ActionEvent e)
{
frame.getContentPane().setBackground(new Color(112,253,95));
}
} //inside class ends
chameleon.addActionListener(new CHameleonaction());
menuBar.add(menu);
frame.setJMenuBar(menuBar);
}
Run Code Online (Sandbox Code Playgroud)
您在 main 方法中做了太多的事情,并且大部分代码属于其他地方,因为 main 方法应该主要用于创建主要对象并启动它们运行,但除此之外就很少了。正如我的评论中所指出的,您当前的代码看起来会导致 NullPointerException,因为您试图在似乎从未初始化过的字段上调用方法。我同意您使用内部类来实现简单的侦听器接口,并且如上所述,匿名内部类可以正常工作,但您必须小心执行此操作。如果您需要引用外部类变量,您有几个选择:
getSource(),这通常会导致您获得非内部类引用。例如
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Foo2 extends JPanel {
private static final Color NEW_COLOR = new Color(112,253,95);
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
private JMenuBar menuBar = new JMenuBar();
public Foo2() {
JMenuItem chameleon = new JMenuItem(new ChangeColorAction("Change Color"));
JMenu menu = new JMenu("Menu");
menu.add(chameleon);
menuBar.add(menu);
}
public JMenuBar getMenuBar() {
return menuBar;
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class ChangeColorAction extends AbstractAction {
public ChangeColorAction(String name) {
super(name);
}
@Override
public void actionPerformed(ActionEvent e) {
setBackground(NEW_COLOR);
}
}
private static void createAndShowGui() {
Foo2 mainPanel = new Foo2();
JFrame frame = new JFrame("Foo2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.setJMenuBar(mainPanel.getMenuBar());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)