JAVA JLabel不显示怎么回事 【JL1.setText("怎么不显示我");】这段代码不显示
发布网友
发布时间:2022-04-23 02:07
我来回答
共1个回答
热心网友
时间:2023-10-11 03:18
【JL1.setText("怎么不显示我");】这段代码不显示,是因为你没有给JL1指定在JFrame中的位置(你的布局管理器设为了null),还有就是你需要在paint函数第一句,加上super.paint(g);。这样【JL1.setText("怎么不显示我");】才能完美的显示出来。
完整的程序如下:(改动的地方见注释,一共就加了两句,另外,加上了main主函数)
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
class myMouseListener implements MouseMotionListener{
private JLabel lab;//创建一个JLabel
public myMouseListener(JLabel lab){
this.lab=lab;
}
public void mouseMoved(MouseEvent e){
// int x=e.getX();
// int y=e.getY();
// String s = "鼠标坐标:"+x+","+y;
// lab.setText(s);
int x=e.getX();
int y=e.getY();
lab.setText("鼠标坐标:"+x+","+y);
}
public void mouseDragged(MouseEvent e){};
}
public class FiveChessFrame extends JFrame implements MouseListener {
// 取得屏幕的宽度
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
// 取得屏幕的高度
int height = Toolkit.getDefaultToolkit().getScreenSize().height;
public FiveChessFrame() {
//JFrame JF = new JFrame();
JLabel JL=new JLabel();
JLabel JL1=new JLabel();
this.setLayout(null);
// 设置标题
this.setTitle("GAME");
// 设置窗体大小
this.setSize(500, 500);
// 设置窗体出现位置
this.setLocation((width - 500) / 2, (height - 500) / 2);
// 将窗体设置为大小不可改变
this.setResizable(true);
// 将窗体的关闭方式设置为默认关闭后程序结束
// 为窗体加入*
this.addMouseListener(this);
JL.setForeground(Color.red);
//设置字体颜色
JL.setText("鼠标坐标");
JL.setBounds(145,5,130,15);
this.add(JL);
JL1.setText("怎么不显示我");
JL1.setBounds(300,5,130,15);//这里加一句
this.add(JL1);
//JL.setText("鼠标坐标");
//JL.setBounds(170,5,130,15);
//JF.add(JL);
this.addMouseMotionListener(new myMouseListener(JL));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 将窗体显示出来
this.setVisible(true);
}
public void paint(Graphics g){
super.paint(g);//这里加一句
//Graphics g2 = this.getGraphics();
//g2.setColor(Color.red);
//
//for (int i = 0; i < 4; i++) {
//g2.drawLine(10, 70 + 20 * i, 370, 70 + 20 * i);
//g2.drawLine(10 + 20 * i, 70, 10 + 20 * i, 430);
//}
Graphics g1 = this.getGraphics();
g1.setColor(Color.black);
for(int i=0;i<4;i++){
g1.drawLine(15,70+120*i,375,70+120*i);
g1.drawLine(15+120*i,70,15+120*i,430);
}
}
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
new FiveChessFrame();
}
}