我是非常新的Java,对任何愚蠢的问题都很抱歉。
这是我的问题:
我只想绘制一条线 - 如果我将JLabel
Myline()
直接添加到label
作为JFrame MyFrame
,那么它将显示在JFrame
中MyLine()
1}} - Dialogwindow,但是如果我将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);
}
}
,那么就没有Line。
为什么?
{{1}}
答案 0 :(得分:3)
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);
}
}