我目前正在开发一个java程序,它有一个JCombo框,用户可以在其中选择一个形状,并且该形状是随机生成的多次。我正在使用命令行来运行它并使用记事本。我正在使用最新的JDK版本。如何修改我的代码以便在新版本上编译..?
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.Random;
import javax.swing.*;
public class Hw1b extends JFrame
{
public Hw1b()
{
super("Hw1b");
final ComboPanel comboPanel = new ComboPanel();
String[] shapeItems = {
"Square", "Oval", "Rectangle", "Circle"
//"Circle", "Square", "Oval", "Rectangle"
};
JComboBox shapeBox = new JComboBox(shapeItems);
shapeBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
String item = (String)e.getItem();
if(item.equals("Square"))
comboPanel.makeSquares();
if(item.equals("Oval"))
comboPanel.makeOvals();
if(item.equals("Rectangle"))
comboPanel.makeRectangles();
if(item.equals("Circle"))
comboPanel.makeCircles();
/*
if(item.equals("Circle"))
comboPanel.makeSquares();
if(item.equals("Square"))
comboPanel.makeOvals();
if(item.equals("Oval"))
comboPanel.makeRectangles();
if(item.equals("Rectangle"))
comboPanel.makeCircles();
*/
}
}
});
//position and set size of Jpanel
JPanel southPanel = new JPanel();
southPanel.add(shapeBox);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().add(comboPanel, "Center");
getContentPane().add(southPanel, "South");
setSize(600,400);
setLocation(200,200);
setVisible(true);
}
private class ComboPanel extends JPanel
{
int w, h;
Random seed;
static final int
OVAL = 0,
RECT = 1;
int shapeType = -1;
public ComboPanel()
{
seed = new Random();
setBackground(Color.white);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int width = getWidth();
int height = getHeight();
int x, y;
Shape s = null;
for(int i = 0; i < 20; i++)
{
x = seed.nextInt(width - w);
y = seed.nextInt(height - h);
switch(shapeType)
{
case OVAL:
s = new Ellipse2D.Double(x, y, w, h);
break;
case RECT:
s = new Rectangle2D.Double(x, y, w, h);
}
if(shapeType > -1)
g2.draw(s);
}
}
public void makeSquares()
{
shapeType = RECT;
w = 50;
h = 50;
repaint();
}
public void makeOvals()
{
shapeType = OVAL;
w = 80;
h = 60;
repaint();
}
public void makeRectangles()
{
shapeType = RECT;
w = 80;
h = 40;
repaint();
}
public void makeCircles()
{
shapeType = OVAL;
w = 75;
h = 75;
repaint();
}
}
public static void main(String[] args)
{
new Hw1b();
}
}
答案 0 :(得分:0)
JComboBox
是“原始”类型,这意味着您需要提供它将要使用的实际类型。您关注的消息不是错误,而是试图引起您的注意:
JComboBox shapeBox = new JComboBox(shapeItems);
为了使您的代码类型安全,您需要明确说明您的JComboBox将与字符串一起使用:
JComboBox<String> shapeBox = new JComboBox<>(shapeItems);
如果您希望了解有关原始类型和泛型的更多信息,我建议您浏览this post。