나는 시간이 지남에 따라 커지는 컬러 막대를 그리려고합니다. 그것은 기본 layoutmanager를 사용할 때 작동하지만, GridBagLayout을 사용하여이를 구현하려고 시도하면 작동하지 않습니다. 문제가 무엇인지 조사하기 위해 테스트 목적으로 테스트 프로젝트를 작성했습니다. graphics2D 객체와 별도로 몇 가지 버튼을 추가 했으므로 실제 프로젝트 인 것처럼 보입니다. 그러나 며칠 후, 나는 단서가 없다는 것을 인정해야한다. 무엇이 잘못 될지. 누군가가 나를 도울 수 있기를 바랍니다!GridBagLayout을 사용하여 프레임의 Grahpics2D 객체 그리기
사전에 코드에 사용 된 일부 단어로 혼동하지 마십시오. 내 모국어는 영어가 아닙니다.
import java.awt.*;
import javax.swing.*;
import java.util.TimerTask;
import java.util.Timer;
public class FarbBalkenTest extends JPanel {
static Timer timer = new Timer();
static TimerTask task ;
static int time;
public static void main(String[] args) {
FarbBalkenTest fbt = new FarbBalkenTest();
fbt.init();
}
public static void addComponent(Container cont, GridBagLayout gbl, Component c, int x, int y, int width, int height, double weightx, double weighty){
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx=x;
gbc.gridy=y;
gbc.gridwidth=width;gbc.gridheight=height;
gbc.weightx=weightx;gbc.weighty=weighty;
gbl.setConstraints(c,gbc);
cont.add(c);
}
public void init(){
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(new Color(230,230,230));
Container c = frame.getContentPane();
GridBagLayout gbl = new GridBagLayout();
c.setLayout(gbl);
ZeichenTest z_test = new ZeichenTest();
addComponent(c,gbl, new Button("top left"), 0,0,1,1,1.0,1.0);
addComponent(c,gbl, new Button("top right"), 2,0, 1,1,1.0,1.0);
addComponent(c, gbl,z_test, 1,1,1,1,1.0,1.0);
addComponent(c,gbl, new Button("down left"),0,2,1,1,1.0,1.0);
addComponent(c,gbl, new Button("down right"),2,2,1,1,1.0,1.0);
frame.setSize(500,500);
frame.setVisible(true);
task = new TimerTask(){
public void run(){
frame.repaint();
time+= 20;
System.out.println(time);
}
};
timer.scheduleAtFixedRate(task, 0, 1000);
}
public class ZeichenTest extends JComponent {
public void paintComponent (Graphics g){
Graphics2D g2d = (Graphics2D) g;
Color startgreen = new Color(50,205,50);
Color endred = new Color (255, 97, 3);
GradientPaint startend = new GradientPaint(0,25 , startgreen, 400, 25 , endred);
g2d.setPaint (startend);
g2d.fillRect(50, 200 , time, 50);
}
}
}
문제는 무엇인가에
main
코드를 포장? –문제는 내가 끌고 싶었던 바를 볼 수 없었다는 것입니다. 하지만 문제가 해결되면서 버튼을 오버레이하지 않으므로 직사각형의 위치를 (0,0)으로 변경해야했습니다. – CarlCosinus