我正在尝试在Java中构建一个日历作为我想到的一个小项目,但是我似乎不能每次单击Next按钮时都更改月份的名称。这是我的代码!
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
组件添加组件,因为这些组件将覆盖所绘制的内容。