java中drawLine无法画线,求解。。。
以下是书上的例子,结果如图,而书本上的结果应该是窗口左上到Banner有条线的,求解释啊,谢谢importjavax.swing.*;importjava.awt.Gra...
以下是书上的例子,结果如图,而书本上的结果应该是窗口左上到Banner有条线的,求解释啊,谢谢
import javax.swing.*;
import java.awt.Graphics;
public class TestGetGraphics extends JFrame{
private JLabel jlblBanner = new JLabel("Banner");
TestGetGraphics(){
add(jlblBanner);
System.out.println(jlblBanner.getGraphics());
}
public static void main(String[] args){
TestGetGraphics frame = new TestGetGraphics();
frame.setTitle("TestGetGraphics");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,100);
frame.setVisible(true);
//JOptionPane.showMessageDialog(null,"Delay on purpose\nClick OK to dismiss the dialog");
Graphics graphics = frame.jlblBanner.getGraphics();
graphics.drawLine(0,0,50,50);
}
} 展开
import javax.swing.*;
import java.awt.Graphics;
public class TestGetGraphics extends JFrame{
private JLabel jlblBanner = new JLabel("Banner");
TestGetGraphics(){
add(jlblBanner);
System.out.println(jlblBanner.getGraphics());
}
public static void main(String[] args){
TestGetGraphics frame = new TestGetGraphics();
frame.setTitle("TestGetGraphics");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,100);
frame.setVisible(true);
//JOptionPane.showMessageDialog(null,"Delay on purpose\nClick OK to dismiss the dialog");
Graphics graphics = frame.jlblBanner.getGraphics();
graphics.drawLine(0,0,50,50);
}
} 展开
展开全部
1. 把JLabel替换为Label对象吧、如果不设置文字、就会划出直线了
2. 重写JLabel的paint方法,在paint方法里面划线就可以了
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
public class TestGetGraphics extends JFrame {
private JLabel jlblBanner = new JLabel() {
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.red);
g.drawLine(0, 0, 50, 50);
}
};
TestGetGraphics() {
jlblBanner.setBackground(null);
jlblBanner.setForeground(null);
jlblBanner.setOpaque(true);
add(jlblBanner);
}
public static void main(String[] args) {
TestGetGraphics frame = new TestGetGraphics();
frame.setTitle("TestGetGraphics");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 100);
frame.setVisible(true);
}
}
2. 重写JLabel的paint方法,在paint方法里面划线就可以了
import javax.swing.*;
import java.awt.Color;
import java.awt.Graphics;
public class TestGetGraphics extends JFrame {
private JLabel jlblBanner = new JLabel() {
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.red);
g.drawLine(0, 0, 50, 50);
}
};
TestGetGraphics() {
jlblBanner.setBackground(null);
jlblBanner.setForeground(null);
jlblBanner.setOpaque(true);
add(jlblBanner);
}
public static void main(String[] args) {
TestGetGraphics frame = new TestGetGraphics();
frame.setTitle("TestGetGraphics");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 100);
frame.setVisible(true);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询