I have in a JFrame, one main JPanel, and only in the left half of JFrame, a second JPanel.
When i click in a JButton in a main JPanel, the second JPanel becomes visible.
I'm going to create a paintComponent in main JPanel class, to draw a immage, and one circle and all work.
The problem arises when I go to change a color of this circle. I change R-G-B every time that i repaint();
The color of circle change , but if I click on a JButton in main JPanel to open the Second JPanel I saw it for a little time and it becomes invisible.
I suppose because it redraws the main JPanel above the second..
How i fix this problem? Thank's you!.
P.S.
I use super.paintComponent(g);
and in the costructor of JPanel i do this.repaint() to bring up immediately the components of the first page, otherwise I should minimize and make the window reappear.
//Panel extends JPanel
//at the end of Constructor
this.repaint();
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
setOpaque(true);
g.drawImage(img, 210, 50, 580,580,this);
g.setColor(Color.black);
g.drawOval(480,40,40,40);
g.fillOval(480,40,40,40); //Various..
repaint(); //With this i can't saw the second JPanel that it's overlapped
} //whit the main JPanel
Alessandro Amedei, Florence.
27-01-2015
This is my code..
MAIN PANEL
package a;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
// #author Alessandro Amedei
public class FirstPanel extends JPanel{
Image img = null;
FirstPanel(){
LotL LotL = new LotL();
FPListener FPL = new FPListener();
this.setVisible(true);
this.setSize(1000,1000);
this.setLayout(null);
this.setBackground(Color.white);
this.addMouseListener(FPL);
Main.f1.add(this);
Button start = new Button("Start Game!");
Button options = new Button("Options");
start.setVisible(true);
start.setSize(200,80);
start.setLayout(null);
start.setLocation(400,650);
start.addActionListener(LotL);
start.setBackground(Color.green);
start.identificatore=1;
this.add(start);
options.setVisible(true);
options.setSize(200,70);
options.setLayout(null);
options.setLocation(400,750);
options.addActionListener(LotL);
options.setBackground(Color.green);
options.identificatore=2;
this.add(options);
img= Toolkit.getDefaultToolkit().getImage("ok.jpg");
this.repaint();
}
int B=30;
int R=80;
int G=90;
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
setOpaque(true);
g.drawImage(img, 210, 65, 580,580,this);
g.setColor(new Color(R,G,B));
g.drawOval(455,20,90,90);
g.fillOval(455,20,90,90);
if(B==150)
B=0;
if(R==170)
R=0;
if(G==160)
G=0;
try {
Thread.sleep(5);
} catch (InterruptedException ex) {
}
B++;
R++;
G++;
repaint();
}
}
SECOND PANEL
package a;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
//#author Alessandro Amedei
public class OptionsPanel extends JPanel {
static JSlider rgb1 = new JSlider(0,255);
static JSlider rgb2 = new JSlider(0,255);
static JSlider rgb3 = new JSlider(0,255);
static SpinnerNumberModel noba = new SpinnerNumberModel();
static JTextField fg1 = new JTextField();
static JTextField fg2 = new JTextField();
OptionsPanel(){
this.setVisible(false);
this.setSize(350,1000);
this.setLayout(null);
this.setBackground(new Color(255,150,0));
Main.f1.add(this);
JSpinner nob = new JSpinner(noba);
JLabel l1= new JLabel("Options");
JLabel l2= new JLabel("Background Color");
JLabel g1= new JLabel("Left Button Color");
JLabel g2= new JLabel("Right Button Color");
JLabel nob1 = new JLabel("Number of Checkers for Player");
JLabel ng1= new JLabel("Name of Left Player");
JLabel ng2= new JLabel("Name of Right Player");
rgb1.setVisible(true);
rgb1.setSize(240,40);
rgb1.setLocation(55,90);
this.add(rgb1);
rgb1.setBackground(new Color(rgb1.getValue(),255,0));
rgb1.addChangeListener(new SListener());
rgb2.setVisible(true);
rgb2.setSize(240,40);
rgb2.setLocation(55,180);
this.add(rgb2);
rgb2.setBackground(new Color(255,0,rgb1.getValue()));
rgb2.addChangeListener(new SListener());
rgb3.setVisible(true);
rgb3.setSize(240,40);
rgb3.setLocation(55,270);
this.add(rgb3);
rgb3.setBackground(new Color(0,rgb1.getValue(),255));
rgb3.addChangeListener(new SListener());
nob.setVisible(true);
nob.setSize(60,30);
nob.setLocation(55,360);
noba.setMaximum(10);
noba.setMinimum(3);
noba.setValue(3);
this.add(nob);
fg1.setVisible(true);
fg1.setSize(150,30);
fg1.setLocation(55,450);
this.add(fg1);
fg2.setVisible(true);
fg2.setSize(150,30);
fg2.setLocation(55,540);
this.add(fg2);
Font f= new Font("arial",Font.ITALIC,20);
Font f2= new Font("arial",Font.BOLD,13);
l1.setVisible(true); //Etichetta OPTIONS
l1.setSize(70,20);
l1.setLocation(140,10);
l1.setFont(f);
this.add(l1);
l2.setVisible(true);
l2.setSize(120,30);
l2.setLocation(55,65);
l2.setFont(f2);
this.add(l2);
g1.setVisible(true);
g1.setSize(150,30);
g1.setLocation(55,155);
g1.setFont(f2);
this.add(g1);
g2.setVisible(true);
g2.setSize(150,30);
g2.setLocation(55,245);
g2.setFont(f2);
this.add(g2);
nob1.setVisible(true);
nob1.setSize(200,30);
nob1.setLocation(55,335);
nob1.setFont(f2);
this.add(nob1);
ng1.setVisible(true);
ng1.setSize(200,30);
ng1.setLocation(55,425);
ng1.setFont(f2);
this.add(ng1);
ng2.setVisible(true);
ng2.setSize(200,30);
ng2.setLocation(55,515);
ng2.setFont(f2);
this.add(ng2);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
}
Ok so, If I change the color of the circle in the main JPanel using repaint(); i can't show the Options Panel I think because of the refresh caused by the repaint() method of the Main JPanel.
How I can change the color of the circle in Main JPanel and visualize the Options Panel at the same time? (exluding creating another panel where I draw the circle).
Sorry for my bad English!
Thank's you very much.
Alessandro Amedei,Florence.
Related
I've made a code to draw a simple oval in a panel and then according to the button clicked (left or right) or arrow button, it will move accordingly. This code I have here doesn't seem to make the shape appear in the yellow background. Is there anything that I can change?
Also, I will also link the made oval into two separate keyboard and button click events. Is using KeyAdaptor method and lambda expression on the mouse event a good measure here? Thank you in advance!
private JButton btnLeftMvmt, btnRightMvmt;
class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponents(g);
int width = getWidth()/2;
int top = (getHeight() - HEIGHT) / 2;
/* Code above is a vain attempt to center the oval to the yellow
background.
Is this correct, as well?*/
g.fillOval(width, top, 150, 150);
g.setColor(Color.RED);
}
}
public MyFrame(){
setTitle("Red Oval Translator");
setSize(500, 200);
setLayout(new BorderLayout());
JPanel panel1, panel2;
panel1 = new JPanel();
panel2 = new JPanel();
panel1.add(new MyPanel());
panel1.setBackground(Color.YELLOW);
btnLeftMvmt = new JButton("Left Translation");
btnRightMvmt = new JButton("Right Translation");
panel2.add(btnLeftMvmt);
panel2.add(btnRightMvmt);
add(panel1);
add(panel2, BorderLayout.SOUTH);
setLocationRelativeTo(null);
setVisible(true);
I assume you wanted something like that:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class MyPanel extends JPanel {
public MyPanel() {
setPreferredSize(new Dimension(300, 250));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponents(g);
int width = getWidth()/2;
int top = (getHeight() - HEIGHT) / 2;
g.setColor(Color.RED); //need to apply color before painting
g.fillOval(width, top, 150, 150);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(()->new MyFrame());
}
}
class MyFrame extends JFrame{
private JButton btnLeftMvmt, btnRightMvmt;
public MyFrame() {
setTitle("Red Oval Translator");
setLayout(new BorderLayout()); //BorderLayout for JFrame
JPanel panel2 = new JPanel();
btnLeftMvmt = new JButton("Left Translation");
btnRightMvmt = new JButton("Right Translation");
panel2.add(btnLeftMvmt);
panel2.add(btnRightMvmt);
add(new MyPanel());
add(panel2, BorderLayout.SOUTH);
setLocationRelativeTo(null);
pack();
setVisible(true);
}
}
Always post mcve
One problem with your code is that you should swap the order of g.fillOval(width, top, 150, 150); and g.setColor(Color.RED); to get a red oval and not a default-colored oval.
I want to add a jPanel which is semi transparent. But other components which are placed inside the jPanel such as buttons and labels should be displayed with 100% opacity. I am using netbeans to design the GUIs. Normally i drag and drop the swing components in the palette to design the GUI(I don't code them). I can't see any property in properties window to achieve this. Please help me. As I am quite new to java please give me a detailed answer. Thanks in advance.
You can use
JPanel.setBackground(Color bg);
to make the panel semi-transparent. What matter is the color's property.
You can construct a color with alpha values to set the transparent degree of the color.
panel.setBackground(new Color(213, 134, 145, 123));
The last parameter is actual the alpha value and you can adjust it to see the effect.
Here is the code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class PanelTest {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
PanelTest test = new PanelTest();
test.createUI();
}
};
SwingUtilities.invokeLater(runnable);
}
public void createUI(){
JFrame frame = new JFrame("Panel Test");
JPanel panel = new JPanel();
panel.setBackground(new Color(213, 134, 145, 123));
JButton button = new JButton("I am a button");
JLabel label = new JLabel("I am a label");
label.setFont(new Font("Arial", Font.BOLD, 15));
JTextField textField = new JTextField();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(button);
panel.add(Box.createVerticalStrut(20));
panel.add(label);
panel.add(Box.createVerticalStrut(20));
panel.add(textField);
panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
BottomPanel buttomPanel = new BottomPanel();
buttomPanel.add(panel);
frame.add(buttomPanel,BorderLayout.CENTER);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#SuppressWarnings("serial")
class BottomPanel extends JPanel{
#Override
protected void paintComponent(Graphics g) {
for (int y = 0; y < 200; y = y + 20) {
g.drawString("I am the string on the bottom", 5, y);
}
}
}
}
Here is the effect and hope it can help you.
You can simply create your jPanel using drag and drop, as you always do and then for changing the panel's color and making it transparent or semi-transparent you can use this code:
panel.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.5f));
You can change the color by changing first three parameters of Color constructor, which represent RGB and you can change transparency by changing fourth parameter, which is the alpha value of color.
I am very new in Java Swing develompment and I have the following problem.
I have to create a JFrame window that have a background immage.
So I have perform the following operation to do it:
1) I have create a class named JPanelWithBackground that extends JPanel:
package com.test.login;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class JPanelWithBackground extends JPanel {
private Image backgroundImage;
// Some code to initialize the background image.
// Here, we use the constructor to load the image. This
// can vary depending on the use case of the panel.
public JPanelWithBackground(String fileName) throws IOException {
backgroundImage = ImageIO.read(new File(fileName));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the background image.
// g.drawImage(backgroundImage, 0, 0, this);
g.drawImage(backgroundImage, 0, 0, 550, 230, this);
}
}
As you can see this class read an immage file and put its reference into an Image object named backgroundImage and then draw it on a Graphics object.
2) Then I have create a class named LoginFrame2:
package com.test.login;
import javax.swing.JButton;
import java.awt.Container;
import java.awt.Dimension;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu.Separator;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import net.miginfocom.swt.MigLayout;
import org.jdesktop.application.SingleFrameApplication;
public class LoginFrame2 extends SingleFrameApplication {
private static final int FIXED_WIDTH = 550;
private static final Dimension INITAL_SIZE = new Dimension(FIXED_WIDTH, 230);
public static void main(String[] args) {
System.out.println("DENTRO: LoginFrame() ---> main()");
launch(LoginFrame2.class, args);
}
#Override
protected void startup() {
// TODO Auto-generated method stub
System.out.println("Inside startup()");
JFrame mainFrame = this.getMainFrame(); // main JFrame that represents the Windows
mainFrame.setTitle("Chilli Login");
mainFrame.setPreferredSize(INITAL_SIZE);
mainFrame.setResizable(false);
Container mainContainer = mainFrame.getContentPane(); // main Container into the main JFrame
// JPanel creation and settings of the MigLayout on it:
// JPanel externalPanel = new JPanel();
JPanelWithBackground externalPanel = null;
try {
externalPanel = new JPanelWithBackground("/home/andrea/Immagini/logo2.jpg");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
externalPanel.setLayout(new net.miginfocom.swing.MigLayout("fill"));
externalPanel.add(new JLabel("Username"), "w 50%, wrap");
JTextField userNameTextField = new JTextField(20);
externalPanel.add(userNameTextField, "w 90%, wrap");
externalPanel.add(new JLabel("Password"), "w 50%, wrap");
JTextField pswdTextField = new JTextField(20);
externalPanel.add(pswdTextField, "w 90%, wrap");
JButton loginButton = new JButton("Login");
externalPanel.add(loginButton, "w 25%, wrap");
mainContainer.add(externalPanel);
//mainFrame.add(mainContainer);
show(mainFrame);
}
}
This class extends SingleFrameApplication abstract class of the JDesktop Swin framework that provide me a JFrame istance.
This class simply create the JPanelWithBackground object by the line:
externalPanel = new JPanelWithBackground("/home/andrea/Immagini/logo2.jpg");
and put in this object some Swing component.
This is my result:
My doubt/problem is: as you can see the JLabel that show the string Password is on the red part of the immage (of my chilli logo) and so is not very readable.
What can I do to make it more readable? For example can I set in some way that the background of my JLabel have to be white?
Tnx
Andrea
You could set the background of the JLabel, but that would look ugly. I would suggest just changing the foreground of only the Password label to be white. Possibly increase the size of font of both labels as well to help readability.
JLabel password = new JLabel("Password");
password.setForeground(Color.WHITE);
More extreme mods: would be to extend the label to output white text that is outlined by black, or to use images for the words in nice fonts that have transparency.
EDIT:
Here is how to set the background to white.
password.setBackground(Color.WHITE);
password.setOpaque(true);
You could change the opacity of the back ground image...
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g.create();
// Draw the background image.
// g.drawImage(backgroundImage, 0, 0, this);
g2d.setComposite(AlphaComposite.SrcOvr.derive(0.5f));
g2d.drawImage(backgroundImage, 0, 0, 550, 230, this);
g2d.dispose();
}
I am trying to create a GUI that will take in the number of circles to draw, and draw them in drawPanel with random locations/sizes. On my actionListener, when I try to draw the circle, it gives me red lines on my drawOval
1st class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
/**
*
* #author Chris
*
*/
public class CirclesPanel extends JPanel{
private JButton draw, clear;
private JTextArea textArea;
private JPanel panel, drawPanel, buttonPanel;
private int count;
/**constructor
* builds the frame
*/
public CirclesPanel(){
//creates buttons and textArea
draw = new JButton("Draw");
clear = new JButton("Clear");
textArea = new JTextArea(1,10);
textArea.setBorder(BorderFactory.createTitledBorder("Circles"));
//creats panel
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
setPreferredSize(new Dimension(620, 425));
//creates subpanel drawPanel
JPanel drawPanel = new JPanel();
drawPanel.setPreferredSize(new Dimension(450,400));
drawPanel.setBackground(Color.BLACK);
//creates subpanel buttonPanel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(3,1));
//adds all the content to the frame
add(panel);
add(buttonPanel, BorderLayout.WEST);
add(drawPanel, BorderLayout.EAST);
buttonPanel.add(textArea);
buttonPanel.add(draw);
buttonPanel.add(clear);
//reads if the draw button is clicked
draw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
count =Integer.parseInt(textArea.getText());//takes the count in
repaint();//repaints the picture to add the circles
}
});
//reads if the clear button is clicked
clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
count=0;//sets the count to 0 so nothing is painted
repaint();//repaints the window
}
});
}
/**Paint component
* draws the random circles
*/
public void paintComponent(Graphics g) {
Random generator = new Random();
int x, y, diameter;
for(int i = 0; i < count; i++){ //loop that takes the count and does this "x" times
g.setColor(Color.BLUE);//sets color to blue
x = generator.nextInt(90);//random location for x
y = generator.nextInt(90);//random location for y
diameter = generator.nextInt(30);//random size
g.fillOval(x, y, diameter, diameter);//draws the circle
}
}
}
2nd class
import javax.swing.JFrame;
public class Circles {
public static void main(String[]args){
JFrame frame = new JFrame("Cicles HW9");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new CirclesPanel());
frame.pack();
frame.setVisible(true);
}
}
So in your, I did little addition, first of all, I made the whole program in one class(CIRLCES PANEL), IF You want to use the second class, you can use it....
Problem is coming, your program is not the reading the ActionPerformed method for the drawing, means it is not located with the button, now I directly added it with your button(DRAW), now whenever you click on the button, it automatically reads the your textArea value, and draw your circles. I made your text area FINAL, So you can use it anywhere......
Now things that you need to do----
- this program is drawing circle on the whole frame, means not on your drawing Panel, you need to set the values, so it will draw on your draw panel area
- Also you need to add color for your oval, because it will either draw black color circle, which you will not able to see.....
and also one thing I forget to mentioned you, is that your, you also need to add code for your clear method...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class CirclesPanel extends JPanel{
private JButton draw, clear;
private JTextArea textArea;
private JPanel panel, drawPanel, buttonPanel;
private int count;
public CirclesPanel(){
JButton draw = new JButton("Draw");
JButton clear = new JButton("Clear");
final JTextArea textArea = new JTextArea(1,10);
textArea.setBorder(BorderFactory.createTitledBorder("Circles"));
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
setPreferredSize(new Dimension(620, 425));
JPanel drawPanel = new JPanel();
drawPanel.setPreferredSize(new Dimension(450,400));
drawPanel.setBackground(Color.BLACK);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(3,1));
add(panel);
add(buttonPanel, BorderLayout.WEST);
add(drawPanel, BorderLayout.EAST);
buttonPanel.add(textArea);
buttonPanel.add(draw);
buttonPanel.add(clear);
draw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
count =Integer.parseInt(textArea.getText());
repaint();
}
});
}
public void paintComponent(Graphics g) {
Random generator = new Random();
int x, y, diameter;
for(int i = 0; i < count; i++){
x = generator.nextInt(90);
y = generator.nextInt(90);
diameter = generator.nextInt(30);
g.drawOval(x, y, diameter, diameter);
}
}
}
What you want to do is drawing some random circles on the drawPanel when button clicked. I write you a simplified version to show how things work.
I only keep the drawButton and paintPanel to keep things simple.
public class PaintFrame extends JFrame {
private JPanel content = new JPanel();
private JButton drawButton = new JButton("Draw");
private PaintPanel paintPanel = new PaintPanel();
public PaintFrame() {
getContentPane().add(content);
content.setLayout(new BorderLayout());
drawButton.setSize(100, 500);
drawButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// drawButton is fired, repaint the paintPanel
paintPanel.repaint();
}
});
content.add(drawButton, BorderLayout.WEST);
content.add(paintPanel, BorderLayout.CENTER);
}
}
You need a new class extending the JPanel and override the paintComponent method to do the paint job for you. This makes sure you are drawing on the panel.
class PaintPanel extends JPanel {
public PaintPanel() {
setSize(500, 500);
setBackground(Color.BLACK);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Random random = new Random();
g.setColor(Color.WHITE);
// draw 5 random circles
int count = 5;
for (int i = 0; i < count; i++) {
g.drawOval(random.nextInt(250), random.nextInt(250),
random.nextInt(250), random.nextInt(250));
}
}
}
Main class
public class DrawMain {
public static void main(String[] args) {
JFrame frame = new PaintFrame();
frame.setDefaultCloseOperation(PaintFrame.EXIT_ON_CLOSE);
frame.setSize(600, 500);
frame.setVisible(true);
}
}
I am a beginner, starting a simple project on GUI. The RectangleComponent should draw a Rectangle on the form with a button click. A rectangle won't draw with the following code, but if I put the same 2 lines of code outside the listener, it certainly works. I would appreciate any help.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class EllipseRectViewer {
/**
* #param args
*/
public static void main(String[] args)
{
final JFrame frame = new JFrame();
final int FRAME_WIDTH = 400;
final int FRAME_HEIGHT = 400;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("Rectangle and Ellipse Draw");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel panel = new JPanel();
frame.add(panel, BorderLayout.NORTH);
class RectangleDrawListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
RectangleComponent r2 = new RectangleComponent();
frame.add(r2);
}
}
JButton rectButton = new JButton("Rectangle");
ActionListener rectDrawListener = new RectangleDrawListener();
rectButton.addActionListener(rectDrawListener);
panel.add(rectButton);
frame.setVisible(true);
}
}
import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class RectangleComponent extends JComponent
{
Rectangle rect;
public RectangleComponent()
{
rect = new Rectangle(20, 20, 30, 30);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.draw(rect);
}
}
Thank you.
After adding the RectangleComponent to the frame, either revalidate the newly added component or the frame's root pane:
public void actionPerformed(ActionEvent event) {
RectangleComponent r2 = new RectangleComponent();
frame.add(r2);
// Option 1
r2.revalidate();
// Option 2
frame.getRootPane().revalidate();
}
Note1: the frame itself can't be revalidated (upto JDK 1.6)
Note2: the frame itself can be revalidated (JDK 1.7+)
i think you need to revalidate() the frame.
frame.revalidate();
put it like this:
public void actionPerformed(ActionEvent event)
{
RectangleComponent r2 = new RectangleComponent();
frame.add(r2);
frame.revalidate();
}
Try to use LineBorder. Create a JPanel with LineBorder and add the JButton to the JPanel.
rect = new Rectangle(20, 20, 30, 30);
A second problem is that your component doesn't have a preferred size. Your component displays in a simple frame because you add the comonent to the center of a BorderLayout so the preferred size of the component is ignored. However, this won't work if you try to use the component when using other layout managers.
You should also override the getPreferredSize() method to return the preferred size of your component at a minimum you need to use:
return new Dimension(50, 50);
to accomodate the size and location of the painted rectangle.