4
我想要一個簡單的程序,用滑塊改變矩形的寬度。 當我運行這個jpanel不能正常工作,因爲它只適合panel.width寬度,它不能正確重繪。JFrame繪圖不正確
import java.awt.*;
import javax.swing.*;
public class panel extends JPanel {
private int width = 50;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GRAY);
g.fillRect(20, 20, width, 25);
}
public void setWidth(int width) {
this.width = (width > 0) ? width : 0;
repaint();
}
public int getWidth() {
return width;
}
}
GUI:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class Gui extends JFrame {
private panel p;
private JSlider slider;
Gui() {
super("Draw program");
setDefaultCloseOperation(EXIT_ON_CLOSE);
p = new panel();
p.setBackground(Color.RED);
slider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, p.getWidth());
slider.setMajorTickSpacing(50);
slider.setPaintTicks(true);
add(p);
add(slider, BorderLayout.SOUTH);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
p.setWidth(slider.getValue());
}
});
}
}
請參閱編輯回答和評論在代碼中的答案。 –