我在Java中非常新,所以对任何愚蠢的问题感到抱歉。
这是我的问题:
我只想画一条线-如果将JLabel
Myline()
直接作为label
添加到JFrame MyFrame
,则它将显示在生成的JFrame
-Dialogwindow中,但是如果添加MyLine()
到JPanel
panel
和panel
到MyFrame
,则没有行。
为什么?
package examples;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class Bsp {
public static void main(String[] args) {
JFrame frame = new MyFrame();
}
}
class MyFrame extends JFrame {
private class MyLine extends JLabel {
int width;
public MyLine(int width) {
this.width=width;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawLine(0, 0, getWidth(), 0);
g.dispose();
}
}
public MyFrame() {
JLabel label=new MyLine(getWidth());
JPanel panel=new JPanel(new GridBagLayout());
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 1));
panel.add(label);
add(new JButton("A"));
add(new JButton("B"));
add(panel);
pack();
setVisible(true);
}
}
最佳答案
MyFrame
没有首选大小,直到pack()
询问封闭组件的首选大小。赋予MyLine
首选大小以查看效果。另请参见Initial Threads。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Bsp {
public static void main(String[] args) {
JFrame frame = new MyFrame();
}
}
class MyFrame extends JFrame {
private class MyLine extends JLabel {
int width;
public MyLine(int width) {
this.width = width;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawLine(0, 0, getWidth(), getHeight());
g.dispose();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(width, 16);
}
}
public MyFrame() {
JLabel label = new MyLine(32);
System.out.println(getWidth());
JPanel panel = new JPanel(new GridBagLayout());
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 1));
panel.add(label);
add(new JButton("A"));
add(new JButton("B"));
add(panel);
pack();
setVisible(true);
}
}
关于java - 在JLabel中绘制线条并在JFrame中添加为JPanel不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24472260/