Reputation: 287
I am trying to create my own component for swing, but when i try to paint the border of it with drawRect, it only draws the left and top edges! Why is that, and how can it be fixed? Here is my paintComponent method:
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.red);
g.drawRect(0, 0, getWidth(), getHeight());
}
Screenshot:
Upvotes: 1
Views: 1380
Reputation: 4562
Maybe this will help you as a starting point:
package de.professional_webworkx.graphics;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DrawFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = -1285962479945295143L;
private JPanel northPanel;
public DrawFrame() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Draw");
this.setLayout(new BorderLayout());
this.getContentPane().add(createNorthPanel(), BorderLayout.BEFORE_FIRST_LINE);
this.getContentPane().add(new DrawPanel(), BorderLayout.CENTER);
this.setSize(1024, 768);
this.setVisible(true);
}
public JPanel createNorthPanel() {
northPanel = new JPanel();
northPanel.setBackground(Color.MAGENTA);
JLabel jLabel = new JLabel("XXXXXXXXXXXX");
jLabel.setForeground(Color.WHITE);
northPanel.add(jLabel);
return northPanel;
}
public static void main(String[] args) {
new DrawFrame();
}
}
DrawPanel.class
package de.professional_webworkx.graphics;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 4949248244138855737L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.drawRect(10, 10, getWidth()/2, getHeight()/2);
g.setColor(Color.YELLOW);
g.fillRect(11, 11, getWidth()/2-1, getHeight()/2-1);
g.draw3DRect(10, getHeight()/2+20, 600, 280, true);
}
}
Patrick
UPDATE: Thanks to camickr.
Upvotes: 1
Reputation: 324078
I am trying to create my own component for swing, but when i try to paint the border of it with drawRect,
Why are you trying to draw a Border. Swing supports borders. if your component needs a border then you should be using:
setBorder( new LineBorder(Color.RED) );
and let swing draw the border for you.
it only draws the left and top edges!
I think you should be using:
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
Upvotes: 4