Java Swing Repaint slow or not working - java

I am trying to draw graphics based on a button click using boolean flags. Before, I set the boolean value as a public static boolean type in the ShapeGUI class, and called it in ShapeListener using Shape.draw and that worked, although it took around 10 seconds to conjure a drawing.
Now I set the boolean flag inside the ShapeListener class itself. Now its either not repainting or is very slow. How can I make a drawing appear instantly when I click a button?
public class ShapeGUI extends JFrame
{
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public ShapeGUI()
{
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setLayout(new FlowLayout());
setLocationRelativeTo(null);
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
menu.add(file);
JMenuItem save = new JMenuItem("Save Information");
JMenuItem exit = new JMenuItem("Exit");
file.add(save);
file.add(exit);
setJMenuBar(menu);
ShapeListener test = new ShapeListener();
JButton button = new JButton("Hello");
test.setBackground(Color.CYAN);
button.addActionListener(new ShapeListener());
test.add(button);
add(test);
//followed this person's advice
//First off, your drawing should be done in a paintComponent method override that is held in a class that extends JPanel. Next, this class could have a boolean variable that the paintComponent uses to decide if it will draw a rectangle or not. The button press simply sets the boolean variable and calls repaint on the drawing JPanel.
}
}
public class ShapeListener extends JPanel implements ActionListener
{
boolean draw = false;
Shape s = new Circle();
Shape a = new Rectangle();
#Override
public void actionPerformed(ActionEvent e)
{
draw = true;
repaint();
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(draw)
{
s.draw(g);
}
else
{
a.draw(g);
}
}
}

Your logic is a little off...
ShapeListener test = new ShapeListener(); // First instance
JButton button = new JButton("Hello");
test.setBackground(Color.CYAN);
button.addActionListener(new ShapeListener()); // Second instance...
test.add(button);
add(test);
You create two instance of the ShapeListener class, add one to the container and use the other as the action listener. Neither will know about each other, meaning that you can click to the cows come home, the first instance of ShapeListener will never change.
Also, unless you're planning to override the preferredSize method of the ShapeListener pane, I'd use something like a BorderLayout on the frame, to ensure that the panel is properly laid out, otherwise it will look like the panel isn't being painted...
Try something like...
public class ShapeGUI extends JFrame {
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public ShapeGUI() {
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
menu.add(file);
JMenuItem save = new JMenuItem("Save Information");
JMenuItem exit = new JMenuItem("Exit");
file.add(save);
file.add(exit);
setJMenuBar(menu);
setLayout(new BorderLayout());
ShapeListener test = new ShapeListener();
JButton button = new JButton("Hello");
test.setBackground(Color.CYAN);
button.addActionListener(test);
test.add(button);
add(test);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
new ShapeGUI();
}
});
}
public class ShapeListener extends JPanel implements ActionListener {
Shape s = new Ellipse2D.Float(0, 0, 20, 20);
Shape a = new Rectangle2D.Float(0, 0, 20, 20);
private Shape paintMe = a;
#Override
public void actionPerformed(ActionEvent e) {
paintMe = s;
repaint();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x = (getWidth() - paintMe.getBounds().width) / 2;
int y = (getHeight() - paintMe.getBounds().height) / 2;
Graphics2D g2d = (Graphics2D) g.create();
g2d.translate(x, y);
g2d.draw(paintMe);
g2d.dispose();
}
}
}
instead...

Related

Simple paint program using JPanel shows random images of JButtons

I'm trying to make a simple paint program in Java. It has 3 colors and a JField to enter the thickness. It works, except every time I enter a button, an image of that button shows up in the JPanel that contains the drawing portion.
I know that I can set the paintPane JPanel to opaque, but it relies on drawing over it self for the painting to work - otherwise it just drags a point around the screen. Thanks!!!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class SimplePainting
{
//The main method simply creates a frame, and terminates the program
//once that frame is closed.
public static void main (String [] args)
{
PaintFrame frame = new PaintFrame();
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
}
class PaintFrame extends JFrame implements ActionListener
{
JPanel pane;
PaintPane drawPane;
Color paintColor = Color.black;
private int radius = 5;
//holds the thickness of the line
JTextField thick;
public PaintFrame ()
{
//We use the JFrame consturctor to add a title to the frame
super("Windows Paint");
//set the main content pane
pane = (JPanel)getContentPane();
pane.setLayout(new BorderLayout());
//make a pane to hold the drawing
drawPane = new PaintPane();
drawPane.addMouseMotionListener(drawPane);
//Make a JPanle to hold all of the buttons
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new GridLayout(1,6));
//add the buttons
JButton black = new JButton("Black");
buttonPane.add(black);
JButton red = new JButton("Red");
buttonPane.add(red);
JButton green = new JButton("Green");
buttonPane.add(green);
//Make a field to re-enter the thickness
thick = new JTextField(3);
thick.setText("5");
JButton thickness = new JButton("Reset Thickness");
thickness.addActionListener(this);
buttonPane.add(thickness);
buttonPane.add(thick);
JButton reset = new JButton("New Drawing");
reset.addActionListener(this);
buttonPane.add(reset);
black.addActionListener(this);
red.addActionListener(this);
green.addActionListener(this);
pane.add(drawPane, BorderLayout.CENTER);
pane.add(buttonPane, BorderLayout.SOUTH);
setSize(500,200);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Black"))
paintColor = Color.black;
else if (e.getActionCommand().equals("Red"))
paintColor = Color.red;
else if (e.getActionCommand().equals("Green"))
paintColor = Color.green;
else if (e.getActionCommand().equals("Reset Thickness"))
{
if (thick.getText() != "")
{
int lineThickness = Integer.parseInt(thick.getText());
radius = lineThickness;
}
}
else if (e.getActionCommand().equals("New Drawing"))
{
drawPane.startPaint = false;
drawPane.repaint();
}
}
class PaintPane extends JPanel implements MouseMotionListener
{
private int x;
private int y;
// don't paint a point until mouse is dragged
boolean startPaint = false;
public PaintPane()
{
setBackground(Color.white);
}
//paints a circle centered at x,y
public void paint(Graphics g)
{
//recall that the frist (x,y) coordiantes represent the top left
//corner of a box holding the circle
g.setColor(paintColor);
if (startPaint)
g.fillOval(x-radius,y-radius, 2*radius, 2*radius);
else
super.paintComponent(g);
}
public void mouseDragged(MouseEvent e)
{
startPaint = true;
x = e.getX();
y = e.getY();
repaint();
}
public void mouseMoved(MouseEvent e)
{
}
}
}

Round JButton with icon; gets clicked when not directly pointer at; setting cursor to HAND_CURSOR works on area outside the icon

So, I have JFrame with JPanel on it. JPanel has two JToggleButtons. Each button is displayed as an icon of a round button. When the cursor hovers above a button it is supposed to turn into a hand.
public class UserInterface extends JFrame {
int width;
int height;
JPanel panel;
public static void main(String[] args) {
run();
}
public UserInterface() {
setup();
}
private void setup() {
width=800;
height=600;
panel=new UserInterfacePanel();
add(panel);
setSize(width, height);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void run() {
UserInterface gui=new UserInterface();
gui.setVisible(true);
}
}
class UserInterfacePanel extends JPanel {
private JToggleButton startButton;
private JToggleButton stopButton;
public static void main(String[] args) {
}
public UserInterfacePanel() {
setup();
}
private void setup() {
setLayout(new GridLayout(1,2));
setupButtons();
setupButtonsActions();
add(startButton);
add(stopButton);
}
private void setupButtons() {
ImageIcon iconStartButton = new ImageIcon("C:\\Users\\parsecer\\Desktop\\imgs\\greenReleased.png");
ImageIcon iconStopButton=new ImageIcon("C:\\Users\\parsecer\\Desktop\\imgs\\redReleased.png");
startButton=new JToggleButton(iconStartButton);
stopButton=new JToggleButton(iconStopButton);
startButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
stopButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
startButton.setHorizontalAlignment(JButton.CENTER);
stopButton.setHorizontalAlignment(JButton.CENTER);
startButton.setAlignmentX(CENTER_ALIGNMENT);
stopButton.setAlignmentX(CENTER_ALIGNMENT);
startButton.setAlignmentY(CENTER_ALIGNMENT);
stopButton.setAlignmentY(CENTER_ALIGNMENT);
setupButtonIcon(startButton);
setupButtonIcon(stopButton);
ImageIcon iconStartButtonPressed=new ImageIcon("C:\\Users\\parsecer\\Desktop\\imgs\\greenPressed.png");
startButton.setDisabledIcon(iconStartButton);
startButton.setPressedIcon(iconStartButtonPressed);
startButton.setSelectedIcon(iconStartButtonPressed);
ImageIcon iconStopButtonPressed=new ImageIcon("C:\\Users\\parsecer\\Desktop\\imgs\\redPressed.png");
stopButton.setDisabledIcon(iconStopButton);
stopButton.setPressedIcon(iconStopButtonPressed);
stopButton.setSelectedIcon(iconStopButtonPressed);
}
private void setupButtonIcon(JToggleButton button) {
button.setBorder(BorderFactory.createEmptyBorder());
button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setFocusable(false);
button.setPreferredSize(new Dimension(80, 80));
button.setFocusPainted(false);
button.setOpaque(false);
}
}
The problem is, the cursor changes into a hand way beyond the icon itself. The same goes for clicking the button - the button get pressed wherever I click vertically - given it's in the same column as the button or when I get relatively close to it horizontally.
I suppose the first problem might be linked to button image, but the background is deleted. Can the second be linked to the GridLayout?
I would do something like this:
Define the shape of your buttons, presumably a circle/ellipse.
In your click- and motionlisteners check if the event occured inside of that shape. If so, do your thing.
Put into code it would go (for the motionlistener) like this:
Cursor handCursor = new Cursor(Cursor.HAND_CURSOR);
Cursor normalCursor = new Cursor(Cursor.DEFAULT_CURSOR);
// create your shape here
Shape shape = new Ellipse2D.Float(0, 0, 30, 30);
MouseMotionAdapter motionListener = new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
JToggleButton src = (JToggleButton) e.getSource();
if (shape.contains(e.getPoint())) {
src.setCursor(handCursor);
} else {
src.setCursor(normalCursor);
}
}
};
startButton.addMouseMotionListener(motionListener);
stopButton.addMouseMotionListener(motionListener);

How do i get my action listener to remove the contents from the current JPanel?

I am trying to add a button which will when pressed, clear the contents off the JPanel and return the panel back to its original set-up. How would i go about doing this? I have tried to revalidate, removeall etc but none have worked for me so far. Any suggestions on how i can do this? I will attach the code below, Help would be greatly appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class WindowBlind extends JFrame
implements ChangeListener, ActionListener {
private JSlider slider;
private int sliderValue = 0;
private JPanel panel;
private JButton open;
private JButton close;
private JButton exit;
private boolean clear;
public static void main(String[] args) {
WindowBlind applic = new WindowBlind();
applic.setLocation(100,100);
applic.setVisible(true);
} // main
public WindowBlind() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("WindowBlind");
setSize(300,300);
Container window = getContentPane();
window.setLayout(new FlowLayout());
panel = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
paintScreen(g);
} // paintComponent
};
panel.setPreferredSize(new Dimension(200, 200));
panel.setBackground(Color.white);
window.add(panel);
slider = new JSlider(JSlider.VERTICAL,0,100,0);
slider.setInverted(true); // 0 will be at top, not bottom, of vertical slider
window.add(slider);
slider.addChangeListener(this); // Register for slider events
JButton open = new JButton("Open Slider");
window.add(open);
open.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton close = new JButton("Close Slider");
window.add(close);
close.addActionListener(this);
JButton exit = new JButton("Exit Slider");
window.add(exit);
exit.addActionListener(this);
} // WindowBlind constructor
public void paintScreen(Graphics g) {
g.setColor(Color.cyan);
g.fillRect(70, 40, 60, 100); // The blue sky
g.setColor(Color.lightGray);
g.fillRect(70, 40, 60, sliderValue); // The blind, partially closed
g.setColor(Color.black);
g.drawRect(70, 40, 60, 100); // The window frame
} // paintScreen
// When the slider is adjusted, this method is called automatically
public void stateChanged(ChangeEvent e) {
sliderValue = slider.getValue(); // Fetch the slider's current setting
repaint(); // Force a screen refresh (paintComponent is called indirectly)
} // stateChanged
#Override
public void actionPerformed(ActionEvent e) {
}
}
I'm taking a HUGE guess and assuming you want to reset the slider to it's "default" state, which would suggest that you need to change the sliderValue, something like...
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sliderValue = 0;
slider.repaint();
}
});
A better solution would be to generate a self contained class which encapsulated all this functionality, for example...
public class SliderPane extends JPanel {
private double sliderValue;
public double getSliderValue() {
return sliderValue;
}
public void setSliderValue(double sliderValue) {
this.sliderValue = Math.max(Math.min(1.0, sliderValue), 0);
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
g.setColor(Color.cyan);
g.fillRect(0, 0, width, height); // The blue sky
g.setColor(Color.lightGray);
g.fillRect(0, 0, width, (int)(sliderValue * height)); // The blind, partially closed
g.setColor(Color.black);
g.drawRect(0, 0, width, height); // The window frame
}
}
Then you could control the slider value through the setSliderValue method.
This also allows you to specify the slider value as percentage, meaning that the size of the component doesn't matter as the area filled is a percentage of the height
This is because you always call paintScreen from the panel's paintComponent method. I would suggest this midification:
panel = new JPanel() {
boolean drawMe = true;
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(drawMe)
paintScreen(g);
} // paintComponent
};
Whenever you want to clear the panel, do this:
panel.drawMe=false;
panel.invalidate();

Integrating mouseListener, JRadioButton, and paintComponent into selecting then creating shapes in JPanel

Not familiar with the MouseListener and paintComponent tools but i have to use them in creating a GUI which is able to create shapes (by selecting one first) at every mouse click location without using applets. First time here, dont know how to properly post the syntax as well.sorry.
Create.java
public class Create extends JFrame implements ActionListener{
static int x, y;
static int sSelection;
JPanel blankSlate, shapeChoice, topMenu;
JMenuBar scBar, utilityBar;
JMenu fileMenu, shapeMenu;
JMenuItem menuiSave, menuiLoad, menuiNew;
JRadioButtonMenuItem triA, rectA, circle;
public Create(){
//container block
Container container=getContentPane();
container.setLayout(new BorderLayout());
//creation block
topMenu=new JPanel();
topMenu.setLayout(new GridLayout(1,3));
blankSlate=new JPanel();
blankSlate.setLayout(new BorderLayout());
shapeChoice=new JPanel();
shapeChoice.setLayout(new GridLayout(1,3));
//utilities block
utilityBar=new JMenuBar();
setJMenuBar(utilityBar);
fileMenu=new JMenu("File");
menuiSave=new JMenuItem("Save");
menuiLoad=new JMenuItem("Load");
menuiNew=new JMenuItem("New");
fileMenu.add(menuiNew);
fileMenu.add(menuiSave);
fileMenu.add(menuiLoad);
utilityBar.add(fileMenu);
//adding bars to sections block
topMenu.add(utilityBar);
//Blank Slate block
//need to add mouselistener and paintComponent according to selection of shapes
AL a1=new AL();
//shape choice block
scBar=new JMenuBar();
setJMenuBar(scBar);
shapeMenu=new JMenu("Shapes");
triA=new JRadioButtonMenuItem("Triangle");
circle=new JRadioButtonMenuItem("Circle");
rectA=new JRadioButtonMenuItem("Rectangle");
shapeMenu.add(triA);
shapeMenu.add(circle);
shapeMenu.add(rectA);
ButtonGroup gr= new ButtonGroup();
gr.add(triA);
gr.add(circle);
gr.add(rectA);
triA.addActionListener(this);
circle.addActionListener(this);
rectA.addActionListener(this);
scBar.add(shapeMenu);
//adding bars to sections block
shapeChoice.add(scBar);
//adding sections to container
container.add(BorderLayout.NORTH, topMenu);
container.add(BorderLayout.CENTER,blankSlate);
container.add(BorderLayout.SOUTH,shapeChoice);
}
public void formula()
{
if(sSelection==1){
ShapeRect r1=new ShapeRect();}
else if(sSelection ==2){}
else if(sSelection==3){}
}
and
public void actionPerformed(ActionEvent e){
if(e.getSource()==triA){
//triA formula selected
}
if(e.getSource()==circle){
//circ formula
}
if(e.getSource()==rectA){
//rectA formula
sSelection=1;
formula();
}
}
public void drawing(int xx, int yy){
x=xx;
y=yy;
repaint();
}
other class
class AL extends MouseAdapter{
public void mouseClicked(MouseEvent e){
x=e.getX();
y=e.getY();
drawing(x, y);
}
}
}
Test.java
public class Test extends JFrame{
public static void main(String[]args){
Create fr = new Create ();
fr.setSize(500, 500);
fr.setDefaultCloseOperation(EXIT_ON_CLOSE);
fr.setLocationRelativeTo(null);
fr.setTitle("Create");
fr.setVisible(true);
}
}
ShapeRect
public class ShapeRect extends Shape{
static int x, y;
public void paintComponent(Graphics g) {
paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(x, y, 20, 20);
}
}

Drawing multiple shapes depending on user Java Swing

I am trying to implement a menu based graph - wherein i will represent a vertex by a circle and each circle will have an index provided by the user.The user has to go to File menu and click on Addvertex to create a new node with an index.The Problem though is - The circle is drawn only once - any subsequent clicks to addVertex does not result in drawing of a circle -Can't understand Why...
Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.*;
public class FileChoose extends JFrame {
public FileChoose() {
JMenuBar l=new JMenuBar();
JMenu file=new JMenu("File");
JMenuItem open=new JMenuItem("Addvertex");
open.addActionListener(new Drawer());
JMenuItem close=new JMenuItem("Exit");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JMenu tools=new JMenu("Tools");
file.add(open);
file.add(close);
this.setJMenuBar(l);
l.add(tools);
l.add(file);
this.setSize(new Dimension(200, 200));
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
}
void HelloHere(String p) {
Draw d = new Draw(p);
this.add(d);
setExtendedState(MAXIMIZED_BOTH);
}
class Drawer extends JFrame implements ActionListener {
Integer index;
public void actionPerformed(ActionEvent e) {
JPanel pn = new JPanel();
JTextField jt = new JTextField(5);
JTextField jt1 = new JTextField(5);
pn.add(jt);
pn.add(jt1);
int result=JOptionPane.showConfirmDialog(null, pn, "Enter the values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
index = Integer.parseInt(jt.getText());
System.out.println(jt1.getText());
}
this.setVisible(true);
this.setSize(500, 500);
this.setLocationRelativeTo(null);
HelloHere(index.toString());
}
}
public static void main(String [] args) {
FileChoose f = new FileChoose();
f.setVisible(true);
}
}
class Draw extends JPanel {
String inp;
public Draw(String gn) {
inp = gn;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Random r = new Random();
int x = r.nextInt(100);
g2.drawOval(x, x * 2, 100, 100);
g2.drawString(inp, x + (x / 2), x + (x / 2));
}
}
Some pointers:
Use EDT for creation and manipulation of Swing Components.
Dont extend JFrame class unnecessarily.
Use anonymous Listeners where possible/allowed
Make sure JFrame#setVisible(..) is the last call on JFrame instance specifically pointing here:
this.setVisible(true);
this.setSize(500, 500);
this.setLocationRelativeTo(null);
HelloHere(index.toString());
Call pack() on JFrame instance rather than setSize(..)
Do not use multiple JFrames see: The Use of Multiple JFrames: Good or Bad Practice?
The problem you are having is here:
Draw d = new Draw(p);
this.add(d);
You are creating a new instance of Draw JPanel each time and then overwriting the last JPanel added with the new one (this is default the behavior of BorderLayout). To solve this read below 2 points:
Call revalidate() and repaint() on instance after adding components to show newly added components.
Use an appropriate LayoutManager
As I am not sure of you expected results I have done as much fixing of the code as I could hope it helps:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class FileChoose {
JFrame frame;
public FileChoose() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar l = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem open = new JMenuItem("Addvertex");
open.addActionListener(new ActionListener() {
Integer index;
#Override
public void actionPerformed(ActionEvent e) {
JPanel pn = new JPanel();
JTextField jt = new JTextField(5);
JTextField jt1 = new JTextField(5);
pn.add(jt);
pn.add(jt1);
int result = JOptionPane.showConfirmDialog(null, pn, "Enter the values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
index = Integer.parseInt(jt.getText());
System.out.println(jt1.getText());
}
HelloHere(index.toString());
}
});
JMenuItem close = new JMenuItem("Exit");
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JMenu tools = new JMenu("Tools");
file.add(open);
file.add(close);
frame.setJMenuBar(l);
l.add(tools);
l.add(file);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
void HelloHere(String p) {
Draw d = new Draw(p);
frame.add(d);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.revalidate();
frame.repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
FileChoose f = new FileChoose();
}
});
}
}
class Draw extends JPanel {
String inp;
public Draw(String gn) {
inp = gn;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Random r = new Random();
int x = r.nextInt(100);
g2.drawOval(x, x * 2, 100, 100);
g2.drawString(inp, x + (x / 2), x + (x / 2));
}
}
UPDATE:
Declare this globally in your Draw class: Random r=new Random(); as if you iniate a new Random instance each time you call paintComponent() the distributions will not be significant/random enough
Every time the user creates a new node you create a new JPanel that is added to the JFrame of your application. In the absence of a specific layout it uses a BorderLayout. BorderLayout does not allow for more than one component to be added at each location. Your other calls to add are probably ignored.

Categories