How can i add repeat background image in Jframe? - java

How can i add repeat background image in Jframe?
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class myGUI extends JFrame {
/**
* Create the frame.
*/
public myGUI() {
super.setResizable(false);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.setUndecorated(true);
super.setExtendedState(JFrame.MAXIMIZED_BOTH);
super.setVisible(true);
}
}
I tried many examples, but not found code that background with a repeat.
Update, that is my GUI and ImagePanel.
The GUI:
import java.awt.BorderLayout;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class GUI extends JFrame {
private JPanel logPanel = new LogPane();
private JPanel logotipPanel = new LogotipPane();
ImagePanel mainPanel = new ImagePanel(Toolkit.getDefaultToolkit().getImage( "C:/Users/Owner/workspace/Blackjack/bin/bg.png" ));
/**
* Create the frame.
*/
public GUI() {
logPanel.setOpaque(false);
logotipPanel.setOpaque(false);
mainPanel.add(logPanel, BorderLayout.EAST);
mainPanel.add(logotipPanel, BorderLayout.NORTH);
add(mainPanel);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setUndecorated(true);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setVisible(true);
}
}
The ImagePanel:
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
#SuppressWarnings("serial")
class ImagePanel extends JPanel {
private Image image;
ImagePanel(Image image) {
this.image = image;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int iw = image.getWidth(this);
int ih = image.getHeight(this);
if (iw > 0 && ih > 0) {
for (int x = 0; x < getWidth(); x += iw) {
for (int y = 0; y < getHeight(); y += ih) {
g.drawImage(image, x, y, iw, ih, this);
}
}
}
}
}
So, the matter with the background with repeat resolved, but in this way i cant use all of the BorderLayouts because i adding panels into ImagePanel and not to JFrame GUI.

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) throws IOException {
final Image image = ImageIO.read(new File("logo.png"));
final JFrame frame = new JFrame();
JPanel imagePanel = new ImagePanel(image);
imagePanel.setLayout(new BorderLayout()); // setting layout as BorderLayout
JPanel anotherPanel = new JPanel(); /// multiple panel,
anotherPanel.setSize(100, 290);
anotherPanel.setOpaque(false); // THIS IS VERY MUCH IMPORTANT
anotherPanel.add(new JButton("Alpesh Gediya"));
imagePanel.add(anotherPanel); //add panel to ImagePanel
frame.add(imagePanel);
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class ImagePanel extends JPanel {
private Image image;
private boolean tile;
ImagePanel(Image image) {
this.image = image;
this.tile = false;
final JCheckBox checkBox = new JCheckBox();
checkBox.setAction(new AbstractAction("Tile") {
public void actionPerformed(ActionEvent e) {
tile = checkBox.isSelected();
repaint();
}
});
add(checkBox, BorderLayout.SOUTH);
};
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (tile) {
int iw = image.getWidth(this);
int ih = image.getHeight(this);
if (iw > 0 && ih > 0) {
for (int x = 0; x < getWidth(); x += iw) {
for (int y = 0; y < getHeight(); y += ih) {
g.drawImage(image, x, y, iw, ih, this);
}
}
}
} else {
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
}
}
EDIT :
imagePanel.setLayout(new BorderLayout()); // setting layout as BorderLayout for panel as
// Jpanel have FlowLayout as Default LayoutManager.

Related

JSlider inside JPanel moves around when the value is changed

I have 2 JPanels inside JFrame border layout and in one JPanel I want to draw things and the other one I use to hold some JComponents(for now only JSlider). The problem is that when I change the value with the slider very weird things happen (the slider moves around and what not). Here is the whole class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Main extends JPanel {
static final int WIDTH = 800, HEIGHT = 800;
static final int pointsMin = 10, pointsMax = 300;
static JSlider sliderPoints;
static ArrayList<Point> points = new ArrayList<Point>();
public static void main(String[] args)
{
JFrame jf = new JFrame("Circle");
Main panel = new Main();
panel.setPreferredSize(new Dimension(800,650));
JPanel panel2 = new JPanel(null);
panel2.setPreferredSize(new Dimension(800,150));
Container pane = jf.getContentPane();
pane.add(panel2, BorderLayout.NORTH);
pane.add(panel,BorderLayout.CENTER);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
jf.setVisible(true);
jf.requestFocus();
sliderPoints = new JSlider(pointsMin, pointsMax, pointsMin);
sliderPoints.setLocation(64,64);
sliderPoints.setSize(128, 32);
panel2.add(sliderPoints);
sliderPoints.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
panel.recalculate();
}
});
panel.recalculate();
}
private void recalculate()
{
points.clear();
float angle = (float) (6.2856f / sliderPoints.getValue());
for(int i=0; i < sliderPoints.getValue(); i++)
{
int x = (int) (Math.cos(angle * i) * (100));
int y = (int) (Math.sin(angle * i) * (100));
points.add(new Point(x,y));
}
revalidate();
repaint();
}
public void paint(Graphics g)
{
g.setColor(Color.red);
for (int i=0; i < points.size(); i++)
{
g.fillRect(400 + points.get(i).x - 1, HEIGHT/2 + points.get(i).y - 1, 3, 3);
}
g.dispose();
}
}

drawString on large JPanel turns messy on Linux but not on Windows

I've experienced a problem on the Graphics drawString method. Briefly, I observe unexpected behaviour of drawString on Linux where the string goes messy if the panel size is large.
As an example. I have modified the ScrollDemo2 class from Oracle to draw strings on the drawingPane:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class ScrollDemo2 extends JPanel
{
private Dimension area;
private JPanel drawingPane;
public ScrollDemo2() {
super(new BorderLayout());
area = new Dimension(100000,1000);
drawingPane = new DrawingPane();
drawingPane.setBackground(Color.white);
drawingPane.setPreferredSize(area);
drawingPane.revalidate();
drawingPane.repaint();
JScrollPane scroller = new JScrollPane(drawingPane);
scroller.setPreferredSize(new Dimension(500,500));
add(scroller, BorderLayout.CENTER);
}
public class DrawingPane extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// drawString gives correct results in Windows but gives messy strings in Linux; drawLine gives correct lines in both Windows and Linux
for (int i = 0; i < 100000; i += 100)
g.drawString("Mark " + i, i, 20);
for (int i = 0; i < 100000; i += 100)
g.drawLine(i, i % 1000 / 10 + 25, i, i % 1000 / 10 + 35);
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("ScrollDemo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new ScrollDemo2();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Program runs on Windows 7
The program displays correct strings on Windows 7.
Program runs on Linux 14.04
The program displays messy strings on Linux.
A drawLine method is added in addition to the drawString method, and the drawLine method works properly in both Windows and Linux.
Why is it? How should I rewrite the code to solve the problem on Linux?
As noted in comments, if drawing a static (stable unchanging background image) use a BufferedImage. For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class ScrollDemo2B extends JPanel
{
private static final int IMG_W = 100000;
private static final int IMG_H = 1000;
// private Dimension area;
private JPanel drawingPane;
private BufferedImage img = new BufferedImage(IMG_W, IMG_H, BufferedImage.TYPE_INT_ARGB);
public ScrollDemo2B() {
super(new BorderLayout());
Graphics2D g2 = img.createGraphics();
g2.setColor(Color.BLACK);
for (int i = 0; i < 100000; i += 100) {
g2.drawString("Mark " + i, i, 20);
}
for (int i = 0; i < 100000; i += 100) {
g2.drawLine(i, i % 1000 / 10 + 25, i, i % 1000 / 10 + 35);
}
g2.dispose();
drawingPane = new DrawingPane();
drawingPane.setBackground(Color.white);
drawingPane.revalidate();
drawingPane.repaint();
JScrollPane scroller = new JScrollPane(drawingPane);
scroller.setPreferredSize(new Dimension(500,500));
add(scroller, BorderLayout.CENTER);
}
public class DrawingPane extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet() || img == null) {
return super.getPreferredSize();
}
int w = img.getWidth();
int h = img.getHeight();
return new Dimension(w, h);
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("ScrollDemo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new ScrollDemo2B();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Then if you have mobile sprites or dynamic images, you would draw them within the paintComponent method.

How to set size for custom-made panel that will work with gridbaglayout?

this is my problem, I hope you will help me somehow. I have one class that extends JPanel, and that class is creating a rectangle with a paintComponent method. When I add that class to JPanel who has gridBagLayout,first is not appearing. But, when I set Dimension.getPreferredSize() in that class, I can see the rectangle...and the problem is when I call MouseListener and see that rectangle is only moving in little square in the frame. So I think that somehow that method getPreferredSize() is controlling the place where will rectangle move and be.
Here is pic of my problem:
move3
limitet showing/moving4
Here is code:
Main:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PrikazGUI {
JFrame frejm;
JPanel k;
JButton b1,b2;
public PrikazGUI(){
frejm = new JFrame("Lala");
k = new JPanel();
k.setLayout(new GridBagLayout());
Kvadrat l = new Kvadrat();
JPanel a = new JPanel();
a.add(l);
k.add(a);
frejm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frejm.setSize(1900, 1000);
frejm.getContentPane().add(k);
frejm.setVisible(true);
}
public static void main(String[] args) {
PrikazGUI a = new PrikazGUI();
}
Second class:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class KvadratPravi extends JPanel {
int sizeH = 60;
int sizeW = 60;
#Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
g.setColor(Color.PINK);
g.drawRect(0, 0, sizeH, sizeW);
g.fillRect(0, 0, sizeH, sizeW);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(sizeH,sizeW);
}
}
Third class:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Kvadrat extends JPanel {
JButton b1,b2;
JPanel panel;
KvadratPravi s1 = new KvadratPravi();
int x,y;
public Kvadrat(){
GridBagConstraints cst = new GridBagConstraints();
panel = new JPanel();
panel.setLayout(new GridBagLayout());
final KvadratPravi s = new KvadratPravi();
cst.gridx = 0;
cst.gridy = 0;
s.setPreferredSize(new Dimension(40,40));
s.setBounds(0, 0, 400, 400);
panel.add(s,cst);
JosJedanKvadrat j = new JosJedanKvadrat();
j.setPreferredSize(new Dimension(40,40));
j.setBounds(0, 0, 400, 400);
cst.gridx = 0;
cst.gridy = 4;
panel.add(j,cst);
s.setPreferredSize(new Dimension(400,400));
s.setBounds(400, 400, 400, 1000);
s.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if(!e.isMetaDown()){
x = e.getX();
y = e.getY();
}
}
});
s.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if(!e.isMetaDown()){
Point p = s.getLocation();
s.setLocation(p.x + e.getX() - x,
p.y + e.getY() - y);
}
}
});
cst.gridx = 2;
cst.gridy =4;
panel.add(s1,cst);
JPanel k = new JPanel();
k.add(panel);
add(k);
}
}
Fourth class:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class JosJedanKvadrat extends JPanel {
int sizeH = 60;
int sizeW = 60;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawOval(0, 0, sizeH, sizeW);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(sizeH,sizeW);
}
}

Java application creating Rectangle when button is pressed

The intention of my code is to create a rectangle when the button is clicked. The button works fine but the rectangle itself is not showing up on the screen, and there are no errors. Thank you for helping btw.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Tester {
static JButton button;
static JFrame frame;
static JPanel panel;
static Rectangle rec;
static void init(){
button = new JButton();
frame = new JFrame();
panel = new JPanel();
rec = new Rectangle(30,30,30,30);
button.setVisible(true);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
panel.setVisible(true);
frame.setSize(200, 200);
button.setBackground(Color.GREEN);
button.setBounds(30, 30, 20, 20);
}
public static void main(String[] args) {
init();
ActionListener listener = new RectangleMover();
button.addActionListener(listener);
}
static class RectangleMover implements ActionListener{
#Override
public void actionPerformed(ActionEvent arg0) {
RectanglePainter r = new RectanglePainter();
r.add(rec);
}
}
static class RectanglePainter extends JPanel{
void add(Rectangle r){
rec = r;
repaint();
}
protected void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
Random r = new Random();
int i =r.nextInt(2);
if (i==1)
g2.setColor(Color.BLUE);
else
g2.setColor(Color.RED);
g2.fill(rec);
g2.draw(rec);
}
}
}
Your generally approach is slightly skewed, rather than using another JComponent to "act" as the shape, you should be using it to paint all the shapes through it's paintComponent method
From my "red rectangle" period...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Tester {
public static void main(String[] args) {
new Tester();
}
public Tester() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel panel;
private JButton button;
private JLabel label;
private ShapePane shapePane;
public TestPane() {
setLayout(new BorderLayout());
button = new JButton("Rectangle");
panel = new JPanel();
label = new JLabel();
button.setVisible(true);
panel.add(button);
panel.add(label);
shapePane = new ShapePane();
add(shapePane);
add(panel, BorderLayout.SOUTH);
class ClickListener implements ActionListener {
private int X = 20;
private int Y = 20;
#Override
public void actionPerformed(ActionEvent arg0) {
int width = shapePane.getWidth();
int height = shapePane.getHeight();
int x = (int)(Math.random() * (width - 20)) + 10;
int y = (int)(Math.random() * (height - 20)) + 10;
int w = (int)(Math.random() * (width - x));
int h = (int)(Math.random() * (height - y));
shapePane.add(new Rectangle(x, y, w, h));
}
}
ActionListener listener = new ClickListener();
button.addActionListener(listener);
}
}
public class ShapePane extends JPanel {
private List<Shape> shapes;
public ShapePane() {
shapes = new ArrayList<>(25);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void add(Rectangle rectangle) {
shapes.add(rectangle);
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
for (Shape shape : shapes) {
g2.draw(shape);
}
}
}
}
As to answer your basic question, you could have tried calling revalidate and repaint, but because of the BorderLayout I doubt it would have worked as you would have basically been trying to replace the panel with your ShapeChanger component, and there are better ways to do that

GUI Application that allows the user to choose the shape and color of a drawing

I need to create a program that allows the user to select a color from a list of checkboxes, red and blue, and then a shape from a
list of radio buttons, square or circle. When the “Draw” button is pressed the selected
shape and color are drawn. If both red and blue are chosen, the shape is drawn in purple.
should look like the following picture:
This is about as far i've gotten, stumped as to how to create the circle and print it when that option is chosen. Also how do I reorganize the labels and buttons?
any help is appreciated
import java.awt.GridBagLayout;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Shapes
{
public static JFrame window = new JFrame("Shapes");
public static JPanel panel = new JPanel(new GridBagLayout());
public static void main(String[] args)
{
window.setBounds(0, 0,300, 300);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(panel);
MApp m = new MApp();
m.setBounds(100,100,100,100);
window.add(m);
Draw d = new Draw(panel) ;
d.setBounds(0, 0, window.getWidth(), 90);
window.add(d);
window.setVisible(true);
}
}
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JPanel;
public class MApp extends JPanel implements MouseListener
{
private boolean clicked;
private Rectangle r;
public MApp()
{
clicked = false;
r = new Rectangle(15, 15, 50, 50);
addMouseListener(this);
}
public void paintComponent(Graphics g)
{
if(clicked)
{
g.setColor(Color.BLUE);
}
else
{
g.setColor(Color.RED);
}
g.fillRect((int)r.getX(), (int)r.getY(),
(int)r.getWidth(), (int)r.getHeight());
}
public void mouseClicked (MouseEvent e)
{
Point p = new Point(e.getX(),e.getY());
if(r.contains(p))
{
clicked = !clicked;
}
repaint();
}
public void Circle()
{
g.fillOval(0, 0, s, s);
}
public void mousePressed (MouseEvent evnt) {}
public void mouseReleased (MouseEvent evnt) {}
public void mouseEntered (MouseEvent evnt) {}
public void mouseExited (MouseEvent evnt) {}
}
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class Draw extends JPanel implements ActionListener
{
JTextField tfInfo;
JLabel lblColor, lblShapes;
JCheckBox cbRed, cbBlue;
ButtonGroup shapes;
JRadioButton rbCircle, rbSquare;
JButton btnSubmit;
public Draw(JPanel panel)
{
GridBagConstraints c = new GridBagConstraints();
tfInfo = new JTextField("Color", 15);
tfInfo = new JTextField("Shapes", 50);
lblColor = new JLabel("Colors:");
cbRed = new JCheckBox("Red");
cbBlue = new JCheckBox("Blue");
lblShapes = new JLabel("Shapes:");
shapes = new ButtonGroup();
rbCircle = new JRadioButton("Circle");
rbSquare = new JRadioButton("Square");
btnSubmit = new JButton("Draw");
btnSubmit.addActionListener(this);
this.setBackground(Color.WHITE);
add(lblColor);
add(cbRed);
add(cbBlue);
add(lblShapes);
add(rbCircle);
add(rbSquare);
add(btnSubmit);
shapes.add(rbCircle);
shapes.add(rbSquare);
}
public void actionPerformed(ActionEvent a)
{
if(a.getSource() == btnSubmit)
{
if(cbRed.isSelected()&&cbBlue.isSelected())
{
if(rbCircle.isSelected())
{
}
else if(rbSquare.isSelected())
{
}
}
else if(cbRed.isSelected())
{
if(rbCircle.isSelected())
{
}
else if(rbSquare.isSelected())
{
}
}
else if(cbBlue.isSelected())
{
if(rbCircle.isSelected())
{
}
}
else if(rbSquare.isSelected())
{
}
}
repaint();
}
}
Start by separating your "management" code from you "painting" code
You should have a single class that only handles the painting of the shape, nothing else, it just does what it's told.
You should then have a second class which takes input from the user and when they press the Draw button, it tells the "paint" class what it should be paint, for example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DrawStuff extends JFrame {
public static void main(String[] args) {
new DrawStuff();
}
public DrawStuff() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ControlPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ControlPane extends JPanel {
private JRadioButton circle;
private JRadioButton square;
private DrawPane drawPane;
public ControlPane() {
setLayout(new GridBagLayout());
ButtonGroup bg = new ButtonGroup();
circle = new JRadioButton("Circle");
square = new JRadioButton("Square");
bg.add(circle);
bg.add(square);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
JPanel shape = new JPanel();
shape.add(circle);
shape.add(square);
add(shape, gbc);
JButton draw = new JButton("Draw");
draw.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (circle.isSelected()) {
drawPane.setDrawableShape(DrawableShape.CIRCLE);
} else if (square.isSelected()) {
drawPane.setDrawableShape(DrawableShape.SQUARE);
}
}
});
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(draw, gbc);
drawPane = new DrawPane();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = gbc.BOTH;
add(drawPane, gbc);
}
}
public enum DrawableShape {
CIRCLE,
SQUARE
}
public class DrawPane extends JPanel {
private DrawableShape drawableShape;
public DrawPane() {
}
public void setDrawableShape(DrawableShape drawableShape) {
this.drawableShape = drawableShape;
repaint();
}
public DrawableShape getDrawableShape() {
return drawableShape;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
DrawableShape shape = getDrawableShape();
if (shape != null) {
int width = getWidth() - 20;
int height = getHeight() - 20;
int size = Math.min(width, height);
int x = (getWidth() - size) / 2;
int y = (getHeight() - size) / 2;
if (shape == DrawableShape.CIRCLE) {
g2d.fillOval(x, y, size, size);
} else if (shape == DrawableShape.SQUARE) {
g2d.fillRect(x, y, size, size);
}
}
g2d.dispose();
}
}
}
I'll leave you to add in the color management.
Have a closer look at:
How to Use Buttons, Check Boxes, and Radio Buttons
How to Write an Action Listeners
Painting in AWT and Swing
Performing Custom Painting
2D Graphics
for more details

Categories