gpt4 book ai didi

java - 按下日历中的按钮后不会重新绘制不同的月份

转载 作者:太空宇宙 更新时间:2023-11-04 06:45:41 24 4
gpt4 key购买 nike

我正在尝试用 Java 构建一个日历作为我想到的一个小项目,但我似乎无法在每次单击“下一步”按钮时更改月份的名称。这是我的代码!

package drawing;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
public class Drawing_something extends JPanel{
int[] calender_squares = {1, 2, 3, 4, 5, 6, 7};
String[] Month = {"January", "February", "March", "April","May","June","July",
"August","September","October","November","December"};
int i = 0;
Graphics c;
@Override
public void paintComponent(Graphics c){
super.paintComponent(c);
this.setBackground(Color.WHITE);
int WIDTH = 55, HEIGHT = 65;

for (int in: calender_squares) {
for (int counter = 0; counter < 7; counter++){
c.drawRect(50, 50, 100, 100);
c.drawRect(50, 50, 700, 500);
c.copyArea(50, 50, 600, 500, 100, 0);
c.copyArea(50, 50, 600, 400, 0, 100);
}
}

for (int date = 1; date <= 30; date++) {
String s = String.valueOf(date);
c.drawString(s, WIDTH, HEIGHT);
if (date <= 6){
WIDTH += 100;
} else if (date == 7){
WIDTH = 55;
HEIGHT = 165;
}else if (date <= 13){
WIDTH += 100;
}else if (date == 14){
WIDTH = 55;
HEIGHT = 265;
}else if (date <= 20){
WIDTH += 100;
}else if (date == 21){
WIDTH = 55;
HEIGHT = 365;
}else if (date <= 27){
WIDTH += 100;
}else if (date == 28){
WIDTH = 55;
HEIGHT = 465;
}else if (date <= 30){
WIDTH += 100;
}
}
c.setFont(new Font("default", Font.BOLD, 40));
c.drawString(Month[i], 320, 45);
}

public Drawing_something(){
setLayout(new BorderLayout());
JButton N = new JButton("NEXT");
JButton B = new JButton("BACK");
JPanel P = new JPanel();

P.add(B);
P.add(N);

add(P, BorderLayout.SOUTH);

B.addActionListener(new HandlerClass());
N.addActionListener(new NextClass());
}
public class HandlerClass implements ActionListener{
public void actionPerformed(ActionEvent e){
}
}
public class NextClass implements ActionListener{
public void actionPerformed(ActionEvent e){
if (i == 11){
i = 0;
}
i = i + 1;
c.drawString(Month[i], 320, 45);
}
}

public static void main(String[] args){
JFrame mainFrame = new JFrame("Calender");
mainFrame.add(new Drawing_something());
mainFrame.setSize(850, 650);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
}

如果有人可以提供帮助,我将不胜感激!

提前致谢!!

最佳答案

不要维护对用于绘制组件的Graphics上下文的引用,这不是自定义绘制的完成方式。

相反,一旦更新了 i 值,就调用 repaint

您实际上不应该向 Draw_Something 组件添加组件,因为这些组件将覆盖已绘制的内容。

相反,将所有组件添加到单独的容器中,并使用 setter 和 getter 来更改日历 Pane 的状态

关于java - 按下日历中的按钮后不会重新绘制不同的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24026372/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com