【发布时间】:2016-01-24 15:33:22
【问题描述】:
当用户使用 JFrame 在 java 中单击菜单项时更改显示的形状时遇到问题。谁能建议我如何解决这个问题?以下是我的代码:
public class PlayingWithShapes implements ActionListener
{
protected JMenuItem circle = new JMenuItem("Circle");
protected String identifier = "circle";
public PlayingWithShapes()
{
JMenuBar menuBar = new JMenuBar();
JMenu shapes = new JMenu("Shapes");
JMenu colors = new JMenu("Colors");
circle.addActionListener(this);
shapes.add(circle);
menuBar.add(shapes);
menuBar.add(colors);
JFrame frame = new JFrame("Playing With Shapes");
frame.setSize(600,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(new Shapes());
frame.setJMenuBar(menuBar);
}
public static void main(String args[])
{
Runnable runnable = new Runnable() {
@Override
public void run() {
new PlayingWithShapes();
}
};
EventQueue.invokeLater(runnable);
}
我想在点击圆形menuItem时将形状改为圆形
@Override
public void actionPerformed(ActionEvent click) {
if(click.getSource() == circle){
Shapes shape = new Shapes();
}
}
public class Shapes extends JPanel
{
然后我怎样才能调用矩形?
@Override
public void paintComponent(Graphics shapes)
{
circle(shapes);
}
public void circle(Graphics shapes)
{
shapes.setColor(Color.yellow);
shapes.fillOval(200,100, 100, 100);
}
public void rectangle(Graphics shapes)
{
shapes.setColor(Color.MAGENTA);
shapes.fillRect(200,100,100,100);
}
}
}
非常感谢任何帮助。
【问题讨论】:
-
问题标签已更改:您的问题实际上与 NetBeans(IDE)无关,而与 Swing(图形库)有关。
标签: java swing shape paintcomponent menubar