使用MenuBar编译并弹出panelMain。我可以推送编辑并转到subMenu,然后单击“首选项”。它出现了一个错误,指出“线程中的异常”AWT-EventQueue-0“java.lang.NullPointerException”。单击“首选项”后我想要发生的是创建一个新的JFrame,它为我提供了为mainPanel选择三种不同背景颜色的选项。
的图表的绘图import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class P4App extends JFrame
{
P4File fileFrame;
JPanel panelMain;
JPanel panelselect;
public P4App()
{
panelMain = new JPanel();
panelMain.setLayout(new BorderLayout());
JMenuBar menubar = new JMenuBar();
JMenu edit = new JMenu("Edit");
edit.setMnemonic(KeyEvent.VK_E);
menubar.add(edit);
JMenuItem pref = new JMenuItem("Preferences");
pref.setMnemonic(KeyEvent.VK_P);
edit.add(pref);
setJMenuBar(menubar);
this.setSize(400,150);
this.setLocation(400,200);
panelMain.setBackground(Color.RED);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
fileFrame = new P4File(this);
pref.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
remove(menubar);
remove(pref);
add(panelselect);
revalidate();
repaint();
}
});
}
public static void main(String [] args) {
new P4App();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class P4File extends JFrame
{
JRadioButton radiored;
JRadioButton radioblue;
JRadioButton radiogreen;
JPanel panelMain;
JButton buttonok;
JButton buttoncancel;
JPanel panelselect;
JPanel pbuttons;
P4App parent;
public P4File(P4App parent)
{
super("P4File");
this.parent = parent;
ActionHandler actionHandler = new ActionHandler();
panelselect = new JPanel();
panelselect.setLayout(new GridLayout(4,1,5,5));
panelselect.add(radiored = new JRadioButton("Red"));
panelselect.add(radioblue = new JRadioButton("Blue"));
panelselect.add(radiogreen = new JRadioButton("Green"));
ButtonGroup group = new ButtonGroup();
group.add(radiored);
group.add(radioblue);
group.add(radiogreen);
panelselect.add(radiored);
panelselect.add(radioblue);
panelselect.add(radiogreen);
pbuttons = new JPanel();
pbuttons.setLayout(new FlowLayout(FlowLayout.RIGHT,2,2));
pbuttons.add(buttonok = new JButton("OK"));
pbuttons.add(buttoncancel = new JButton("CANCEL"));
panelselect.add(buttonok, BorderLayout.SOUTH);
panelselect.add(buttoncancel, BorderLayout.SOUTH);
buttoncancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panelMain.setBackground(Color.RED);
System.exit(0);
}
});
}
private class ActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
setColor();
}
}
public void setColor() {
if(radiored.isSelected())
{
setBackground(Color.RED);
}
if(radiogreen.isSelected())
{
setBackground(Color.GREEN);
}
if(radioblue.isSelected())
{
setBackground(Color.BLUE);
}
}
}