Java小程序中的重写结果
我想开发一个显示排序可视化的Java小程序。所以我写了这样的代码Java小程序中的重写结果,java,swing,jbutton,japplet,Java,Swing,Jbutton,Japplet,我想开发一个显示排序可视化的Java小程序。所以我写了这样的代码 public class SortNumbersGUI extends JApplet { private static final long serialVersionUID = 1L; List<Integer> randomList; JLabel numberLabel; JButton sortButton; @Override public void ini
public class SortNumbersGUI extends JApplet {
private static final long serialVersionUID = 1L;
List<Integer> randomList;
JLabel numberLabel;
JButton sortButton;
@Override
public void init() {
randomList = MyRandom.myRandom();
setSize(400, 400);
setLayout(new FlowLayout());
sortButton = new JButton("Sort");
sortButton.setBounds(50, 0, 50, 10);
sortButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Collections.sort(randomList);
removeAll();
repaint();
}
});
this.add(sortButton);
super.init();
}
@Override
public void paint(Graphics g) {
int y = 20;
for (Integer i : randomList) {
g.drawString(i.toString(), 0, y + 10);
g.fillRect(20, y, (i * 10) / 10, 5);
y = y + 20;
}
}
}
public类SortNumbersGUI扩展了JApplet{
私有静态最终长serialVersionUID=1L;
随机列表;
JLabel编号label;
JButton-sortButton;
@凌驾
公共void init(){
randomList=MyRandom.MyRandom();
设置大小(400400);
setLayout(新的FlowLayout());
sortButton=新JButton(“排序”);
收进边界(50,0,50,10);
addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
集合。排序(随机列表);
removeAll();
重新油漆();
}
});
this.add(排序按钮);
super.init();
}
@凌驾
公共空间涂料(图g){
int y=20;
用于(整数i:随机列表){
g、 抽绳(i.toString(),0,y+10);
g、 fillRect(20,y,(i*10)/10,5);
y=y+20;
}
}
}
但是,我在这里面临两个问题
提前谢谢。您的问题是您正在覆盖paint而不是paintComponent,而且您没有调用super.paint/Component(这也是一种很好的做法,尽管这里可能不是100%必要) 由于覆盖了paint(),所以在绘制JApplet时,不会自动绘制按钮
@Override
public void paint(Graphics g) {
// ..
应该是:
@Override
public void paint(Graphics g) {
super.paint(g); // paints **BG**, border etc.
// ..
“您正在覆盖绘制而不是绘制组件”与JComponent
不同,像JFrame
和JApplet
这样的顶级容器没有paintComponent(Graphics)
方法。(其中一个原因是,最好在JPanel
中进行自定义绘制,然后将面板添加到框架或小程序中。)