【发布时间】:2016-06-26 17:36:53
【问题描述】:
我使用swing创建了一个简单的日历。我在框架内使用了两个面板。两个面板都具有空布局和框架。程序运行正常,但在我最大化或最小化窗口或调整窗口大小之前不会出现任何内容窗口。
这是我的代码:
import java.awt.Color;
import java.time.DayOfWeek;
import java.time.LocalDate;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CalendarTest {
JFrame f;
JLabel monthYearLbl;
JLabel[] dayLbl,dateLbl;
JPanel monthAndYear,dayAndDate;
LocalDate ld;
String month,year,day;
//constructor
public CalendarTest(){
f = new JFrame("Calender");
f.setSize(365,250);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public void showMonthAndYear(){
monthAndYear = new JPanel();
monthAndYear.setBounds(0,0,350,25);
f.add(monthAndYear);
monthAndYear.setBackground(Color.MAGENTA);
ld = LocalDate.now();
month = String.valueOf(ld.getMonth());
year = String.valueOf(ld.getYear());
monthYearLbl = new JLabel(month+"-"+year);
monthAndYear.add(monthYearLbl);
}
public void showDayAndDate(){
dayAndDate = new JPanel();
dayAndDate.setLayout(null);
dayAndDate.setBounds(0,27,350,185);
f.add(dayAndDate);
dayAndDate.setBackground(Color.cyan);
//getting the first day name of the current month
DayOfWeek dow = LocalDate.of(ld.getYear(),ld.getMonth(),1).getDayOfWeek();
int lengthOfMonth = LocalDate.of(ld.getYear(),ld.getMonth(),1).lengthOfMonth();
int friday=0;
dayLbl = new JLabel[8];
int xCord = 10;
for(int i=0;i<7;i++){
String s = String.valueOf(dow);//converting dow object to string
String formatedDay = String.format("%.3s",s);//formating day in short form
if(formatedDay== "FRI"){
friday = i;
}
dayLbl[i] = new JLabel(formatedDay);//creating jlabel
dow = dow.plus(1);//incrementing day name
dayLbl[i].setBounds(xCord,10,30,20);
dayAndDate.add(dayLbl[i]);
xCord = xCord+50;//dynamic positioning of day name
}
dateLbl = new JLabel[35];
int index = 1,ycord=35;
//loop for showing the date from 1 to endofmonth
for(int i=1;i<=5;i++){
int xcord = 15;
for(int j=0;j<7;j++){
dateLbl[index] = new JLabel(String.valueOf(index));
dateLbl[index].setBounds(xcord,ycord,20,20);
if(j==friday){
dateLbl[index].setBackground(Color.black);//indicating holiday
}
dayAndDate.add(dateLbl[index]);
xcord = xcord+50;
if(index==lengthOfMonth){
break;
}
index++;
f.add(dayAndDate);
}
ycord = ycord+25;
}
}
public static void main(String[] args) {
CalendarTest calendar = new CalendarTest();
calendar.showMonthAndYear();
calendar.showDayAndDate();
}
}
For better understanding click here to get the jar format of the program.
截图:
调整窗口大小之前
调整窗口大小后
【问题讨论】:
-
添加所有组件后调用
setVisible(true);。或者调用revalidate和repaint方法 -
@FastSnail 我试过 setVisible(true) 但它不起作用。我不知道“重新验证和重新绘制”是否类似于 setVisible 方法??
-
谢谢它现在可以工作了。在第一个面板上添加“重新验证”并在第二个面板上添加“重新绘制”之后..
-
1) Java GUI 必须在不同的语言环境中使用不同的 PLAF 在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或combinations of them 以及white space 的布局填充和边框。 2) 请参阅Detection/fix for the hanging close bracket of a code block 了解我无法再费心修复的问题。