im very new in Java so sorry for any stupid question.
Here is my problem:
I just want to draw a line - if I add the JLabel
Myline()
directly as label
to the JFrame MyFrame
, then it will be showing in the resulting JFrame
-Dialogwindow, but if I add MyLine()
to the JPanel
panel
and panel
to MyFrame
then there is no Line.
Why?
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);
}
}