How to resize a drawn oval in Java? - java

I need to resize a drawn oval in Java, I created this code for it:
FrameView.java
package tutorial;
import java.awt.*;
import javax.swing.*;
public class FrameView{
public static void main(String args[]){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BallCreation c = new BallCreation();
f.add(c);
f.setSize(500, 500);
f.setVisible(true);
}
}
BallCreation.java
package tutorial;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BallCreation extends JPanel{
private static final long serialVersionUID = 1L;
private int height = 10;
private int width = 10;
private JPanel panel;
private JButton button1;
public BallCreation(){
panel = new JPanel();
button1 = new JButton("Click");
add(button1);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
height = height + 2;
width = width + 2;
}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.WHITE);
g.setColor(Color.GREEN);
g.fillOval(10, 10, width, height);
}
}
The problem is is that it isn't working, I am not sure how I can make the oval refresh to its new size. I think it should be working, but for some reason the button doesn't parse the new height and width on to the paintComponent.

Just add a repaint() at the end of your actionPerformed method , or you won't see the change (unless you minimize then restore your window for instance, to force a repaint of the area).
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
height = height + 2;
width = width + 2;
repaint();
}
});

Related

Draw a ball in a Panel and move the ball using mouseDragged

I am practicing to draw a ball in the Panel and show the ball's coordinate when the ball is dragged.
This is my first time to practice a drawing exercise(?)
This is my code.
import java.awt.*;
import java.awt.event.*;
public class MovingBall extends Frame {
Panel ballPanel = new Panel();
Label ballLabel = new Label();
Panel coordinatePanel = new Panel();
Label coordinateLabel = new Label();
int x0=0,y0 =0, x=20,y=30;
int nowX, nowY;
Label nowXcoordinateLabel = new Label("Now X :"+nowX);
Label nowYcoordinateLabel = new Label("Now Y :"+nowY);
MovingBall(){
setLayout(new GridLayout(1,1));
ballPanel.add(ballLabel); coordinatePanel.add(coordinateLabel);
add(ballPanel);
add(coordinatePanel);
ballPanel.setBackground(Color.white);
coordinatePanel.setBackground(Color.LIGHT_GRAY);
nowXcoordinateLabel.setBackground(Color.WHITE);
nowYcoordinateLabel.setBackground(Color.WHITE);
coordinatePanel.add(nowXcoordinateLabel);
coordinatePanel.add(nowYcoordinateLabel);
setVisible(true);
setSize(400,400);
MouseMotionListener ml = new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
Point p = new Point();
nowX = (int) p.getX();
nowY = (int) p.getY();
}
};
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
}
);
}
public void paintComponent(Graphics2D gg){
// super.paintComponents(gg);
ballPanel.paintComponents(gg);
gg.setColor(Color.BLUE);
gg.fillOval(x0, y0, 10, 10);
}
public static void main(String[]arg){
MovingBall mb = new MovingBall();
}
}
I have two problems
I used fillOval and paintComponent to draw and display a ball but I don't see that on the screen. Why?
Any idea how to move the ball if I want to move that using mouseDragged? Do I need some thread?
Let's start with
Frame doesn't have a paintComponent method, so nothing is ever going to call it.
Even if it did, position 0x0 would paint the circle under the frame's borders, so you wouldn't see it
You should be getting the Point from the MouseEvent, not from the new Point object you've created
It's not the responsibility of the frame to manage the mouse dragged or painting, the frame is responsible for providing the initial container onto which everything else added
From that, you should move the functionality of the painting and mouse dragged management to it's own class. This provides you with two things, first, a surface onto which you can paint, and which will contained within the frame borders and the mouse events will automatically be converted to the panels context (0x0 will be the top left corner of the panel)
This raises the question about how to update the labels. Well, you could take a leaf from the AWT API and use a simple observer pattern to generate events when the coordinates are changed, for example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.Panel;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
public class MovingBall extends Frame {
BallPane ballPanel = new BallPane();
Label ballLabel = new Label();
int x0 = 0, y0 = 0, x = 20, y = 30;
int nowX, nowY;
Label nowXcoordinateLabel = new Label("Now X :" + nowX);
Label nowYcoordinateLabel = new Label("Now Y :" + nowY);
MovingBall() {
setLayout(new BorderLayout());
ballPanel.add(ballLabel);
add(ballPanel);
ballPanel.setBackground(Color.white);
nowXcoordinateLabel.setBackground(Color.WHITE);
nowYcoordinateLabel.setBackground(Color.WHITE);
setVisible(true);
setSize(400, 400);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
dispose();
}
});
Panel coordinates = new Panel(new FlowLayout());
coordinates.add(nowXcoordinateLabel);
coordinates.add(nowYcoordinateLabel);
coordinates.setBackground(Color.LIGHT_GRAY);
add(coordinates, BorderLayout.SOUTH);
ballPanel.addCoordinateListene(new CoordinateListener() {
#Override
public void coordinatesChanged(CoordinateEvent evt) {
nowXcoordinateLabel.setText("Now X: " + evt.getCoordinate().getX());
nowYcoordinateLabel.setText("Now X: " + evt.getCoordinate().getY());
revalidate();
repaint();
}
});
}
public static void main(String[] arg) {
MovingBall mb = new MovingBall();
}
public class CoordinateEvent extends EventObject {
private final Point p;
public CoordinateEvent(Object source, Point p) {
super(source);
this.p = p;
}
public Point getCoordinate() {
return p;
}
}
public interface CoordinateListener {
public void coordinatesChanged(CoordinateEvent evt);
}
public class BallPane extends Panel {
int x0 = 0, y0 = 0, x = 20, y = 30;
private List<CoordinateListener> coordinateListeners;
public BallPane() {
MouseMotionListener ml = new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
x0 = (int) e.getX();
y0 = (int) e.getY();
fireCoordinateChange(new Point(e.getPoint()));
repaint();
}
};
addMouseMotionListener(ml);
coordinateListeners = new ArrayList<>(5);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLUE);
g.fillOval(x0, y0, 10, 10);
}
public void addCoordinateListene(CoordinateListener listener) {
coordinateListeners.add(listener);
}
public void removeCoordinateListene(CoordinateListener listener) {
coordinateListeners.remove(listener);
}
protected void fireCoordinateChange(Point p) {
CoordinateEvent evt = new CoordinateEvent(this, p);
for (CoordinateListener listener : coordinateListeners) {
listener.coordinatesChanged(evt);
}
}
}
}
Make your class extending Panel and make it ready to drawing with overriding paint method and add the MouseMotionListener to listining your panel.Get X and Y coordinates for using in paint method, at last add your drawing panel to Frame.
Simple code : UPDATED
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestClass extends Panel {
/**
*
*/
private static final long serialVersionUID = 1L;
Panel ballPanel = new Panel();
Label ballLabel = new Label();
Panel coordinatePanel = new Panel();
Label coordinateLabel = new Label();
int nowX, nowY;
Label nowXcoordinateLabel = new Label("Now X :");
Label nowYcoordinateLabel = new Label("Now Y :");
TestClass() {
coordinatePanel.add(coordinateLabel);
nowXcoordinateLabel.setBackground(Color.WHITE);
nowYcoordinateLabel.setBackground(Color.WHITE);
nowXcoordinateLabel.setPreferredSize(new Dimension(100, 25));
nowYcoordinateLabel.setPreferredSize(new Dimension(100, 25));
coordinatePanel.setPreferredSize(new Dimension(400, 30));
coordinatePanel.setBackground(Color.LIGHT_GRAY);
coordinatePanel.add(nowXcoordinateLabel);
coordinatePanel.add(nowYcoordinateLabel);
MouseAdapter ml = new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
nowXcoordinateLabel.setText("Now X :" + e.getX());
nowYcoordinateLabel.setText("Now Y :" + e.getY());
nowX = e.getX();
nowY = e.getY();
repaint();
super.mouseMoved(e);
}
};
setLayout(new GridLayout(1, 1));
setBackground(Color.WHITE);
addMouseMotionListener(ml);
setVisible(true);
setSize(400, 400);
}
#Override
public void paint(Graphics g) {
Graphics2D gg = (Graphics2D) g;
gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
gg.setColor(Color.BLUE);
gg.fillOval(nowX, nowY, 20, 20);
}
public static void main(String[] arg) {
TestClass mb = new TestClass();
Frame frame = new Frame("Test drawing");
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
frame.dispose();
super.windowClosing(e);
}
});
frame.setLayout(new GridLayout(1, 1));
frame.add(mb);
frame.add(mb.coordinatePanel);
frame.setSize(800, 600);
frame.setVisible(true);
}
}
To get the position of the mouse instead of:
nowX = (int) p.getX();
Write this:
nowX = (int) e.getX();
You also need to redraw the oval every time the user triggers a Mouse Drag event

Display JPanel on another JFrame

Current state:
I have a JPanel object which contains complex components(3D-canvas written by myself).
Problem:
There is two screen devices now. I want to use one for control, another just for display, just like PowerPoint. How can I display this JPanel on another screen efficiently(static view is enough, but I want it to reflect the change on control screen?
What I have tried:
I have tried to draw the static picture to another JPanel every 200ms.
Graphics2D g2 = (Graphics2D) contentPanel.getGraphics();
g2.translate(x, y);
g2.scale(scale, scale);
displayPanel.paintAll(g2);
Notes: contentPanel is in a JFrame of display screen, displayerPanel is the panel I want to copy
But I get a problem that the display screen flicker so seriously that I can not accept this...Is it the problem of my CPU or graphics card? Or is these any efficient method I can use? Please help, thanks so much!
And here is the MCVE (sorry, this is my first time asking question in stackoverflow, but I am touched by your helps! Thanks again!)
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.Timer;
public class DisplayWindow {
private static JFrame frame = new JFrame();
private static JPanel contentPanel = new JPanel();
private static JPanel displayPanel = null;
private static Timer timerDisplay = null;
static {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(50, 50, 1366, 768);
frame.getContentPane().add(contentPanel);
frame.setVisible(true);
if (timerDisplay == null) {
timerDisplay = new java.util.Timer();
timerDisplay.schedule(new DisplayAtFixedRate(), 1000, 250);
}
}
public static void display(JPanel panel) {
displayPanel = panel;
}
private static class DisplayAtFixedRate extends TimerTask {
#Override
public void run() {
if (displayPanel != null && displayPanel.getWidth() != 0) {
double windowWidth = frame.getWidth();
double windowHeight = frame.getHeight();
double panelWidth = displayPanel.getWidth();
double panelHeight = displayPanel.getHeight();
double scale = Math.min(windowWidth / panelWidth, windowHeight / panelHeight);
int x = (int) (windowWidth - panelWidth * scale) / 2;
int y = (int) (windowHeight - panelHeight * scale) / 2;
Graphics2D g2 = (Graphics2D) contentPanel.getGraphics();
g2.translate(x, y);
g2.scale(scale, scale);
displayPanel.paintAll(g2);
}
}
}
public static void main(String[] args) {
JFrame controlFrame = new JFrame();
controlFrame.setBounds(50, 50, 1366, 768);
JPanel controlPanel = new JPanel();
controlFrame.getContentPane().add(controlPanel, BorderLayout.CENTER);
controlPanel.add(new JLabel("Hello Stackoverflow!"));
controlFrame.setVisible(true);
DisplayWindow.display(controlPanel);
}
}
Here is an example for you:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.WindowConstants;
public class PaintImage {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
startUI();
}
});
}
private static void startUI() {
final JFrame mainFrm = new JFrame("Main");
final JFrame paintFrame = new JFrame("Copy");
mainFrm.add(new JScrollPane(new JTree()), BorderLayout.WEST);
mainFrm.add(new JScrollPane(new JTextArea("Write your text here...")), BorderLayout.CENTER);
mainFrm.pack();
mainFrm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainFrm.setLocationRelativeTo(null);
final JLabel label = new JLabel("");
paintFrame.add(label);
paintFrame.setSize(mainFrm.getSize());
paintFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
mainFrm.setVisible(true);
paintFrame.setVisible(true);
final Timer t = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final Image img = getScreenShot(mainFrm.getContentPane());
label.setIcon(new ImageIcon(img));
}
});
t.start();
}
public static BufferedImage getScreenShot(Component component) {
final BufferedImage image = new BufferedImage(
component.getWidth(),
component.getHeight(),
BufferedImage.TYPE_INT_RGB
);
// call the Component's paint method, using
// the Graphics object of the image.
component.paint( image.getGraphics() ); // alternately use .printAll(..)
return image;
}
}
Origin of method getScreenShot is here
The painting can be done by passing the displayPanel to draw itself.
class DuplicatePanel extends JPanel {
private final JPanel displayPanel;
DuplicatePanel(JPanel displayPanel) {
this.displayPanel = displayPanel;
}
#Override
public void paintComponent(Graphics g) {
displayPanel.paintComponent(g);
}
}
To trigger the repaints, like repaint(50L) either use a SwingTimer or your own manual repaints.

paintComponent() method not drawing to JPanel

The JFrame and JPanel show up, but the paintComponent method isn't drawing on the JPanel. I only see the JLabel, JTextField and JButton that I added but not what should be drawn on the JPanel.
update; question has been answered: The circles actually were being drawn to the JPanel but I got the coordinates wrong so they were being drawn outside of the frame.
JFrame class:
package h02;
import javax.swing.*;
public class Circles extends JFrame {
public Circles() {
// JFrame and its properties
JFrame frame = new JFrame();
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100, 100);
frame.setTitle("Circles");
frame.add(new CirclesPanel());
frame.setVisible(true);
}
public static void main(String[] args) {
new Circles();
}
}
JPanel class:
package h02;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CirclesPanel extends JPanel implements ActionListener {
// Fields
private JTextField enterDiameter;
private JButton drawButton;
private int diameter;
private final int Y = 470;
// making the panel
public CirclesPanel() {
enterDiameter = new JTextField("100", 5);
enterDiameter.addActionListener(this);
drawButton = new JButton("Teken");
drawButton.addActionListener(this);
add(new JLabel("Diameter"));
add(enterDiameter);
add(drawButton);
}
// find the diameter
public void findDiameter() {
int diameterString = Integer.parseInt(enterDiameter.getText());
diameter = diameterString;
}
// draw circles
public void paintComponent(Graphics g) {
super.paintComponent(g);
int centre = getWidth() / 2;
g.drawLine(30, Y, Y , Y);
g.setColor(Color.ORANGE);
g.fillOval(centre, Y, diameter, diameter);
g.setColor(Color.BLACK);
g.drawOval(centre, Y, diameter, diameter);
g.drawOval(centre, Y, diameter / 2, diameter);
}
// on action performed...
public void actionPerformed(ActionEvent e) {
findDiameter();
repaint();
}
}
The problem is with your "Y" in CirclesPanel. Elements are drawn but outside the frame, try reducing Y, than surely you'll see your elements.
Alternatively increase the frame size.

Need to learn more about an N by N square (n = user input)

I need to draw a square, from user input. After the user input, a frame pops up, and a button says "click me". I need the click to generate the square.
How do I make the button generate the square when I click it?
UPDATE
my code is as follows!
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.*;
//All of these imports are required, in the case of BorderLayout, and JFrame, etc.
public class Gooey implements ActionListener // implements the ActionListener (the button click)
{
private static int n; // make the n variable as in the lab, used for height and width of square
private static JFrame frame; //make the frame non-accessible from any other classes, simply because
// we don't want a bunch of frames running with the same stuff!
public static void main(String[] args)
{
frame = new JFrame(); //create the frame! DUH!
JButton button = new JButton("DrawSquare!"); //make the button!
button.addActionListener(new Gooey()); //adds the actionListener to it can respond to a button click
JLabel label = new JLabel("Draw Your Square!"); //Make the label set to DrawSquare
JPanel panel = new JPanel();
panel.add(button); //add the button to the panel!
panel.add(label); // add the label to the panel!
frame.getContentPane().add(panel, BorderLayout.NORTH); //set the panel of the frame to the "north"
Scanner user_input = new Scanner(System.in);
System.out.println("Enter The Size Of Your Square. Make sure it's not too big!!");
n = user_input.nextInt(); //set 'n' to equal the width and height of the drawSquare method
int FRAME_WIDTH = (n + 50); //make sure the width fits the square
int FRAME_HEIGHT = (n + 100); // make sure the height fits the square
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); //set the frame width and height, to fit square.
frame.setTitle("A nice "
+ n
+ " by "
+ n
+ " Square!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //make sure the frame exits and resets when closed.
frame.setVisible(true); //make it visible on the foreground!
}
#Override //recommended. Keeps from making program all wacky!
public void actionPerformed(ActionEvent arg0) {
JPanel p = new JPanel() //obviously, a new JPanel!
{
protected void paintComponent(Graphics g) //start making the square itself, and color it !!!
{
super.paintComponent(g);
int height = n;
int width = n;
g.setColor(Color.blue);
g.drawRect(10, 10, height, width);
};
};
frame.getContentPane().add(p, BorderLayout.CENTER); //center the Square inside the frame.
frame.getContentPane().revalidate(); //Recalculate the layout.
}
}
This is finished!
1)Read more about custom Paintings. Do your paintings in paintComponent(Graphics g) method of JPanel for example.
2)Your FrameViewer haven't paint(Graphics g) method because of you can't override it.
3)Your FrameViewer implements ActionListener but you don't override actionPerformed() because you get compilation error.
4) You button do nothing, you forgot to add an ActionListener to that.
I fixe your code, examine it:
public class Form implements ActionListener {
private static int n;
private static JFrame frame;
public static void main(String[] args) {
frame = new JFrame();
JButton button = new JButton("Click Me!");
button.addActionListener(new Form());
JLabel label = new JLabel("DrawSquare");
JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
frame.getContentPane().add(panel,BorderLayout.NORTH);
Scanner user_input = new Scanner(System.in);
System.out.println("Enter The Size Of Your Head! Or Square. Whichever!");
n = user_input.nextInt();
int FRAME_WIDTH = (n + 600);
int FRAME_HEIGHT = (n + 400);
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("A nice "
+ n
+ " by "
+ n
+ " Square! Just click the button and watch the instantanious magic!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel p = new JPanel(){
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int height = n;
int width = n;
g.setColor(Color.blue);
g.drawRect(10, 10, height, width);
};
};
frame.getContentPane().add(p,BorderLayout.CENTER);
frame.getContentPane().revalidate();
}
}

Layering a button over a painting

There is a window in which I want to place a button, and then paint the whole area beneath it. In other words, button should cover a piece of painting.
import java.awt.*;
import javax.swing.*;
class Window
{
private JFrame frame;
private JButton launchButton;
private JPanel pnllaunchButton;
private JPanel paintingPanel;
//width and height of client area
private Rectangle dim;
//w,h - width and height of the whole window
public Window(String title,int w,int h)
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(0,0);
frame.setMinimumSize( new Dimension(110,110));
frame.setSize(w, h);
frame.setVisible(true);
frame.setTitle(title);
frame.setResizable(false);
addLaunchButton();
}
private void addLaunchButton()
{
pnllaunchButton = new JPanel();
launchButton = new JButton("Plot!");
dim = new Rectangle();
frame.getContentPane().getBounds(dim);
pnllaunchButton.setBounds(dim.width-100,dim.height-25,100,25);
launchButton.setBounds(dim.width-100,dim.height-25,100,25);
pnllaunchButton.setLayout(null);
pnllaunchButton.add(launchButton);
frame.getContentPane().add(pnllaunchButton);
frame.getContentPane().setComponentZOrder(pnllaunchButton, new Integer(2));
}
public void drawCoordinateSystem()
{
paintingPanel = new JPanel();
paintingPanel.add(new CoordinateSystem());
frame.getContentPane().add(paintingPanel);
frame.getContentPane().setComponentZOrder(paintingPanel,new Integer(3));
}
}
class CoordinateSystem extends JPanel
{
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Dimension size = this.getSize();
g.setColor(Color.BLACK);
g.drawLine(0,size.height/2,size.width, size.height/2);
g.drawLine(size.width/2, 0, size.width/2, size.height);
}
}
public class GC {
public static void main(String[] args)
{
Window h = new Window("GC",800,600);
h.drawCoordinateSystem();
}
}
This code doesn't fulfill the specification. Program creates an empty window and outputs:
run:
Exception in thread "main" java.lang.IllegalArgumentException: illegal component position
at java.awt.Container.checkAdding(Container.java:504)
at java.awt.Container.setComponentZOrder(Container.java:759)
at Window.addLaunchButton(Window.java:46)
at Window.<init>(Window.java:26)
at GC.main(GC.java:10)
Could you point out my mistake? setComponentZOrder() method doesn't seem to be described precisely in javadoc.
Rename your class. The Window class is already part of the standard core Java libraries, and your class name could cause present or future problems.
Don't us null layouts and setBounds(...). This is bad, bad, bad, and will make it very difficult to maintain or upgrade your application. Instead, learn about and use the layout managers.
Consider making a JLabel the contentPane, make it opaque, give it a layout and an ImageIcon and add your components to it.
The ImageIcon can hold a BufferedImage with a grid.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class MyWindow {
private static final int PREF_W = 800;
private static final int PREF_H = 600;
private static final Color COLOR0 = Color.red;
private static final Color COLOR1 = Color.blue;
private static final float COLOR_REPEAT_DIST = 30f;
private JLabel backGroundLabel = new JLabel();
public MyWindow() {
backGroundLabel.setOpaque(true);
backGroundLabel.setLayout(new BorderLayout());
int eb = 15;
BufferedImage bkgrndImg = createBkgrndImage();
ImageIcon icon = new ImageIcon(bkgrndImg);
backGroundLabel.setIcon(icon);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(SwingConstants.RIGHT, eb, eb));
bottomPanel.setOpaque(false);
bottomPanel.add(new JButton("Plot"));
backGroundLabel.add(bottomPanel, BorderLayout.PAGE_END);
}
private BufferedImage createBkgrndImage() {
BufferedImage img = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setPaint(new GradientPaint(0f, 0f, COLOR0, COLOR_REPEAT_DIST, COLOR_REPEAT_DIST, COLOR1, true));
g2.fillRect(0, 0, PREF_W, PREF_H);
g2.dispose();
return img;
}
public JComponent getMainPane() {
return backGroundLabel;
}
private static void createAndShowGui() {
MyWindow mainPanel = new MyWindow();
JFrame frame = new JFrame("MyWindow");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel.getMainPane());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Which looks like so:
Pass an int instead of an Integer to the setComponentZOrder method.
private void addLaunchButton()
{
pnllaunchButton = new JPanel();
launchButton = new JButton("Plot!");
dim = new Rectangle();
frame.getContentPane().getBounds(dim);
pnllaunchButton.setBounds(dim.width-100,dim.height-25,100,25);
launchButton.setBounds(dim.width-100,dim.height-25,100,25);
pnllaunchButton.setLayout(null);
pnllaunchButton.add(launchButton);
frame.getContentPane().add(pnllaunchButton);
frame.getContentPane().setComponentZOrder(pnllaunchButton, 2);
}

Categories

Resources