2 paintcomponents in 2 Jpanels
Hello all,
i am working via the model view controller method...
My situation is that i want swimmers to swim in a swimming pool.
I have a class SwimmingpoolView and a class Swimmerview they are both JPanels
now am i using in both classes
*public void paintComponent { }*
The swimmers must move in the swimming pool i do that by decresing the Y as. But when i decrese the Y as the swimmer multiply.
To solve that i went to the swimmerview class and added by the paintComponent "super.paintComponent(g)" .
Well it seems to work :) there are no multiple swimmers. But now my swimming pool is gone what happend????
I will post my files ..
SwimmingPool.java
{code}package zwembad;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ZwemmerView extends JPanel {
private Zwemmer zwemmer;
/** Creates a new instance of ZwemmerView */
public ZwemmerView (Zwemmer zwemmer) {
this.zwemmer = zwemmer;
public void paintComponent (Graphics g)
zwemmer.tekenZwemmer(g);
{code}
*Swimmer.java*
{code}package zwembad;
import javax.swing.*;
import java.awt.*;
public class ZwembaanView extends JPanel{
private Zwembaan zwembaan1;
/** Creates a new instance of ZwembaanView */
public ZwembaanView (Zwembaan zwembaan1)
this.zwembaan1 = zwembaan1;
if(zwembaan1.getAantalBanen() == 7)
JOptionPane.showMessageDialog(ZwembaanView.this,"Niet meer dan 7 zwemmers zijn toegestaan in het Zwembad","Foutmelding",JOptionPane.ERROR_MESSAGE);
public void paintComponent (Graphics g)
super.paintComponent (g);
// teken het zwembaden
zwembaan1.tekenZwembad(g);
}{code}
What happend?
Thank you
I already have that. this portion works.
what I want is when I call the main number on CME1 ex: 123 456 7890 and autoattendant takes over, when I try to reach a 41xxx extension it tells me INVALID NUMBER.
so: hello welcome to xyz if you know your parties ext dial it now.
if I do 2xx extension it works but if I do 41xxx it says invalid number.
Similar Messages
-
Help with adding a JPanel with multiple images to a JFrame
I'm trying to make a program that reads a "maze" and displays a series of graphics depending on the character readed. The input is made from a file and the output must be placed in a JFrame from another class, but i can't get anything displayed. I have tried a lot of things, and i am a bit lost now, so i would thank any help. The input is something like this:
20
SXXXXXXXXXXXXXXXXXXX
XXXX XXXXXXXXXXX
X XXXXX
X X XX XXXXXXXXXXXX
X XXXXXXXXX XXX
X X XXXXXXXXX XXXXX
X XXXXX XXXXX XXXXX
XX XXXXX XX XXXX
XX XXXXX XXXXXXXX
XX XX XXXX XXXXXXXX
XX XX XXXXXXXX
XX XXX XXXXXXXXXXXXX
X XXXXXXXXXXXXX
XX XXXXXXX !
XX XXXXXX XXXXXXXXX
XX XXXXXXX XXXXXXXXX
XX XXXXXXXX
XX XXXX XXXXXXXXXXXX
XX XXXX XXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
Generated by the Random Maze Generator
And the code for the "translator" is this:
package project;
import java.io.*;
import java.awt.*;
import javax.swing.*;
public class Translator extends JFrame {
private FileReader Reader;
private int size;
Image wall,blank,exit,start,step1,step2;
public Translator(){}
public Translator(File F){
try {
Reader=new FileReader(F);}
catch (IOException e){
JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
try {
size=Reader.read();
System.out.write(size);}
catch (IOException e){
JOptionPane.showMessageDialog(null,"Error Opening File","Error",JOptionPane.ERROR_MESSAGE);}
Toolkit theKit=Toolkit.getDefaultToolkit();
wall=theKit.getImage("wall.gif");
blank=theKit.getImage("blanktile.jpg");
exit=theKit.getImage("exit.jpg");
start=theKit.getImage("start.jpg");
step1=theKit.getImage("start.jpg");
step2=theKit.getImage("step1.jpg");
JPanel panel=new JPanel(){
public void paintComponent(Graphics g) {
super.paintComponents(g);
int ch=0;
System.out.print("a1 ");
int currentx=0;
int currenty=0;
try {ch=Reader.read();
System.out.write(ch);}
catch (IOException e){}
System.out.print("b1 ");
while(ch!=-1){
try {ch=Reader.read();}
catch (IOException e){}
System.out.write(ch);
switch (ch){
case '\n':{currenty++;
break;}
case 'X':{System.out.print(">x<");
g.drawImage(wall,(currentx++)*20,currenty*20,this);
break;}
case ' ':{
g.drawImage(blank,(currentx++)*20,currenty*20,this);
break;}
case '!':{
g.drawImage(exit,(currentx++)*20,currenty*20,this);
break;}
case 'S':{
g.drawImage(start,(currentx++)*20,currenty*20,this);
break;}
case '-':{
g.drawImage(step1,(currentx++)*20,currenty*20,this);
break;}
case 'o':{
g.drawImage(step2,(currentx++)*20,currenty*20,this);
break;}
case 'G':{ch=-1;
break;}
}//Swith
}//While
}//paintComponent
};//Panel
panel.setOpaque(true);
setContentPane(panel);
}//Constructor
}//Classforget all those systems.out and that stuff, that is just for the testing
i call it in another class in this way:
public Maze(){
firstFrame=new JFrame("Random Maze Generator");
firstFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
(...)//more constructor code here
Translator T=new Translator(savefile);
firstFrame.add(T);
firstFrame.getContentPane().add(c);
firstFrame.setBounds(d.width/3,d.height/3,d.width/2,d.height/4);
firstFrame.setVisible(true);
c.setSize(d.width/2,d.height/4);
c.show();
}i know it may be a very basic or concept problem, but i can't get it solved
thanks for any helpTry this. It's trivial to convert it to use your images.
If you insist on storing the maze in a file, just read one line at a
time into an ArrayList than convert to an array and pass that to the
MazePanel constructor.
Any questions, just ask.
import java.awt.*;
import javax.swing.*;
public class CFreman1
static class MazePanel
extends JPanel
private final static int DIM= 20;
private String[] mMaze;
public MazePanel(String[] maze) { mMaze= maze; }
public Dimension getPreferredSize() {
return new Dimension(mMaze[0].length()*DIM, mMaze.length*DIM);
public void paint(Graphics g)
g.setColor(Color.BLACK);
g.fillRect(0, 0, getSize().width, getSize().height);
for (int y= 0; y< mMaze.length; y++) {
String row= mMaze[y];
for (int x= 0; x< row.length(); x++) {
Color color= null;
switch (row.charAt(x)) {
case 'S':
color= Color.YELLOW;
break;
case 'X':
color= Color.BLUE;
break;
case '!':
color= Color.RED;
break;
if (color != null) {
g.setColor(color);
g.fillOval(x*DIM, y*DIM, DIM, DIM);
public static void main(String[] argv)
String[] maze= {
"SXXXXXXXXXXXXXXXXXXX",
" XXXX XXXXXXXXXXX",
"X XXXXX",
"X X XX XXXXXXXXXXXX",
"X XXXXXXXXX XXX",
"X X XXXXXXXXX XXXXX",
"X XXXXX XXXXX XXXXX",
"XX XXXXX XX XXXX",
"XX XXXXX XXXXXXXX",
"XX XX XXXX XXXXXXXX",
"XX XX XXXXXXXX",
"XX XXX XXXXXXXXXXXXX",
"X XXXXXXXXXXXXX",
"XX XXXXXXX !",
"XX XXXXXX XXXXXXXXX",
"XX XXXXXXX XXXXXXXXX",
"XX XXXXXXXX",
"XX XXXX XXXXXXXXXXXX",
"XX XXXX XXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXX"
JFrame frame= new JFrame("CFreman1");
frame.getContentPane().add(new MazePanel(maze));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
} -
JPanel hiden behind JFrame decoration
Hi, I have a JFrame and a JPanel.
The JPanel is going to be double buffered with my own code(active rendering) and will consume the whole JFrame. I want to add other panels later on top of the JPanel. and a pop up menu aswell. So I create a buffer graphic, paint on it and show it on the JPanel.
When I set the JPanel as contentPane or add it in the center then a part of the Panel is hiden by the frame decorations. How can I force the Jpanel to display totaly, without a part being hiden.
I know one solution: create a top cst make it 30 pixels and everytime i paint add it to the y var. But then again... that isn't a 'real' solution.
I would like to be 0,0 the left top of my Jpanel and not 0,0 hiden behind the decoration...
So when I typ contentPane.setLayout(new FlowLayout(FlowLayout.CENTER)); then I would like to see the button i would add.
pauseButton = new JButton("pause");
pauseButton.setIgnoreRepaint(true);
// Create the space where the play/pause buttons go.
playButtonSpace = new JPanel(new BorderLayout());
playButtonSpace.setOpaque(false);
playButtonSpace.add(pauseButton);
contentPane.add(playButtonSpace);Now I can see a small part of the button the rest is hiden behind the frame decoration.
public test() {
gamePanel = new JPanel();
gamePanel.setPreferredSize(new Dimension(500, 600));
gamePanel.setMinimumSize(new Dimension(500, 600));
gamePanel.setMaximumSize(new Dimension(500, 600));
JFrame frame = new JFrame("Hello world!");
frame.setContentPane(gamePanel);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
Graphics g = frame.getGraphics(); // quick test
g.drawString("can you see me1?", 0, 0);
g.drawString("can you see me2?", 0, 20);
g.drawString("can you see me3?", 0, 50);
public static void main(String[] args) {
new test();
}can you see me3 is visible the rest is not.
I use:
frame.getLayeredPane().paintComponents(g);to do my custom painting.
How do i show the panel completely?Usually we draw overriding the method "paintComponent":
* Test.java
import java.awt.*;
import javax.swing.*;
class Test {
public Test() {
JPanel gamePanel = new JPanel() {
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
int h = g.getFontMetrics().getHeight();
for (int row = 1; row < 10; row++) {
g.drawString("can you see me" + row + "?", 0, row * h);
JFrame frame = new JFrame();
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(gamePanel, BorderLayout.CENTER);
frame.setVisible(true);
public static void main(final String[] args) {
new Test();
} -
Hi all,
This is the current code that I have to handle the drawing of images
on my JPanels
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.drawToken(g);
public void drawToken(Graphics g) {
if (move) {
if (player_color == 0) {
g.drawImage(blue_token,posx,posy,this);
else if (player_color == 1) {
g.drawImage(red_token,posx,posy,this);
// reset move
move = false;
So user clicks on the GUI and an image should be drawn based on where the user has clicked. That works fine. The problem I'm having is that when a new image is painted, the previous one gets erased of the JPanel. Why is it doing that and how can I rectify the problem ??
Thanks a bunch.Your paintComponent() method is:
super.paintComponent(g);
this.drawToken(g);
The super.paintComponents will paint the background of you panel.
The drawToken will paint a new image.
If you want more than one image then:
1) remove the super.paintComponent()
2) change to drawToken() method to keep track of multiple images and redraw each image every time.
Here's a thread that show how you might implement suggestion 2:
http://forum.java.sun.com/thread.jsp?forum=57&thread=304939 -
Drawing 2D Graphics in the center of a JPanel
Hi,
Below is my GUI. The basic idea is, I want this to create a neat UI on any machine with any monitor resolution settings. Because I dont really know what will be the resolution of the target machine, I do not perform a setPreferred size on any component. I have several problems here.
1. My DiagramPanel.paintComponent method relies on the Panel's preferred size to draw a rectangle in the center of the panel. When a panel is layed out using BorderLayout, it expands it to fit the space. So is there some method I can use to know, what space the component panel is occupying (its dimension) ?
2. Also, when the frame is maximized or resized, the DiagramPanel's dimension changes. So I want to be able to redraw the diagram in the new center position. How can I do this ?
4. I am using the Frame size to be the screen dimension and set it to be maximized. So when I try to restore the window, it takes up the whole screen even the space including the windows taskbar. Is there someway to get the screen dimension leaving out the space for the taskbar ?
3. I dont set the DividerLocation of the contentPane because, I want it to be set automatically based on the contents of the leftPanel. But when i print out the dividerLocation after creating the UI, it prints -1. How can I get the current divider location then ?
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.Toolkit;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
@SuppressWarnings("serial")
public class MainFrame extends JFrame {
public MainFrame() {
createAndShowGUI();
private void createAndShowGUI() {
initMainFrame();
initMenus();
initPanels();
initContentPane();
setVisible(true);
System.out.println("Divider location "+ contentPane.getDividerLocation());
private void initMainFrame() {
setTitle("Main Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setState(JFrame.NORMAL);
//GETS SCREEN SIZE
Dimension screen_Dimension = Toolkit.getDefaultToolkit().getScreenSize();
setSize(screen_Dimension.width, screen_Dimension.height);
setExtendedState(MAXIMIZED_BOTH);
private void initContentPane() {
getContentPane().add(contentPane);
contentPane.setEnabled(false); / *prevent the divider location from being moved* /
contentPane.setLeftComponent(leftpanel);
contentPane.setRightComponent(rightpanel);
contentPane.setOpaque(true);
private void initMenus() {
exitMenu.setActionCommand(EXIT_COMMAND);
file.add(exitMenu);
menub.add(file);
setJMenuBar(menub);
private void initPanels() {
initLeftPanel();
initRightPanel();
private void initLeftPanel() {
leftpanel.setLayout(new FlowLayout(FlowLayout.CENTER));
leftpanel.add(new Button("Click"));
private void initRightPanel() {
LayoutManager border = new BorderLayout();
rightTab.setLayout(border);
scrollingDiagram = new JScrollPane(diagramPanel);
diagramDescriptionPanel.setLayout(new BorderLayout());
diagramDescriptionPanel.add(diagDescTextArea, BorderLayout.CENTER);
rightTab.add(scrollingDiagram, BorderLayout.CENTER);
rightTab.add(diagramDescriptionPanel, BorderLayout.SOUTH);
rightpanel.addTab("Right Tab", rightTab);
public static void main(String args[]) {
try {
new MainFrame();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
private JSplitPane contentPane = new JSplitPane();
private JMenuBar menub = new JMenuBar();
private JMenu file = new JMenu("File");
private JMenuItem exitMenu = new JMenuItem("Exit");
private JPanel leftpanel = new JPanel();
private JTabbedPane rightpanel = new JTabbedPane();
private JPanel rightTab = new JPanel();
private JScrollPane scrollingDiagram;
private DiagramPanel diagramPanel = new DiagramPanel();
private JPanel diagramDescriptionPanel = new JPanel();
private JTextArea diagDescTextArea = new JTextArea(18, 45);
public static final String EXIT_COMMAND = "Exit";
@SuppressWarnings("serial")
class DiagramPanel extends JPanel{
public static int RECT_WIDTH = 100;
public static int RECT_HEIGHT = 75;
public void paintComponent(Graphics g) {
super.paintComponents(g);
Coordinates centerOfPanel = getCenterCoordinates();
g.drawRoundRect(centerOfPanel.x, centerOfPanel.y, RECT_WIDTH, RECT_HEIGHT, 10, 10);
public Coordinates getCenterCoordinates() {
Dimension panelDimension = getPreferredSize();
int x = (panelDimension.width - RECT_WIDTH) / 2;
int y = (panelDimension.width - RECT_HEIGHT) / 2;
return new Coordinates(x,y);
class Coordinates {
int x;
int y;
Coordinates(int x, int y) {
this.x = x;
this.y = y;Hi,
The getSize worked perfectly for me. But what I tried doing now is that, instead of just the simple centering of the rectangle, i did this
1. When the dimension of the rectangle is smaller than the Panel.getSize(), do centering as usual
2. else when the rectangle is bigger, say because its width was longer than Panel.getSize().getWidth(), I center the rectangle only on its Height, and set the preferred size of the Panel to (rectangle.getWidth(), panel.getSize().getHeight()). And I call revalidate, so that the scrollbars appear.
Problem im running into now is that, once I do a setPreferredSize, everytime I use a getSize later on, i always get the same size. But what I want to see is that, when the rectangle can fit in the panel, i want it centered without any scrollbars, but when it cannot fit on the width, i want it to appear centered on height, but have a horizontal scroll bar.
I'd be really grateful, if you could help me with this.
Here is the code
public void paintComponent(Graphics g) {
super.paintComponents(g);
Coordinates centerOfPanel = getCenterCoordinates();
g.drawRoundRect(centerOfPanel.x, centerOfPanel.y, RECT_WIDTH, RECT_HEIGHT, 10, 10);
//preferredSize might have changed, call revalidate
revalidate();
public static final int PANEL_MARGIN = 50;
public Coordinates getCenterCoordinates() {
setPreferredSize(null);
Dimension panelDimension = getSize();
Dimension myPreferredSize = new Dimension();
if (panelDimension.width > RECT_WIDTH)
myPreferredSize.width = panelDimension.width;
else
myPreferredSize.width = RECT_WIDTH + 2 * PANEL_MARGIN; // MARGIN on left end and right end
if (panelDimension.height > RECT_HEIGHT)
myPreferredSize.height = panelDimension.height;
else
myPreferredSize.height = RECT_HEIGHT + 2 * PANEL_MARGIN; // MARGIN on top and bottom
System.out.println("Panel size is " + getSize());
setPreferredSize(myPreferredSize);
System.out.println("Preferred size is " + myPreferredSize);
//center of the panel.
int x = (myPreferredSize.width - RECT_WIDTH) / 2;
int y = (myPreferredSize.height - RECT_HEIGHT) / 2;
return new Coordinates(x,y);
} -
Hmm..repaint, refresh jpanel?
Hi,
I had a problem and i dun have codes to show. All I can say are just descriptions.
Well, here it goes. I had use jPanel to display Unicode characters. It is able to display but when another frame, say msn, overlaps the jPanel, partial of the character drawn on it will disappear.
This is dependent on the amount of overlapping of that particular frame. If the whole jpanel is covered, then the whole character would be gone when the overlapping is removed.
What can I do to enable the character to be displayed even when i remove the overlapping?
Hope my descriptions are vivid to you all.
ShokerHi,
Thanks for your replies!
Well after searching through the forum, I realised that my problem lies with 'getGraphics()'. This function only stores the data temporary. Therefore, when a frame overlaps it, the that overlapped portion is erased. Shown below are my codes:
Graphics g2 = null;
g2 = jPanel8.getGraphics(); //problem
jPanel8.paint(g2);
g2.setFont(new Font("Arial",Font.PLAIN,12));
g2.drawString(rClassify[count_rClass],10,10);
g2.dispose();
I tried using 'super.paintComponents(g2)' but during runtime, there is an error regarding some null pointers. Hence, the problem still exist.
Would appreciate greatly if you guys can enlighten me!
Thanks.
Shoker -
JFrames / JPanels....Am I being stupid here?
I am creating an application for an assignment. I want the button I click to display another screen in the center panel (displayPanel).
But, I get nothing. Nothing displayed, no runtime error, nothing returned on the catch & even if I do a System.out.println() I get nothing in the command prompt.
So, if I am not getting errors etc...where is my display? Any help?
import java.awt.*;
import java.awt.event.*;
import java.awt.Toolkit.*;
import javax.swing.*;
import javax.swing.event.*;
public class Examiner extends JFrame implements ActionListener{
Screen1 sc=new Screen1();
StudentScreen ss=new StudentScreen();
Container content;
Icon stu_icon=new ImageIcon("../hat.jpeg");
Icon staff_icon=new ImageIcon("../prof.jpeg");
Icon course_icon=new ImageIcon("../course.jpeg");
Icon units_icon=new ImageIcon("../units.jpeg");
JButton stu=new JButton(stu_icon);
JButton staff=new JButton(staff_icon);
JButton course=new JButton(course_icon);
JButton units=new JButton(units_icon);
JPanel buttonPanel=new JPanel();
JPanel menuPanel=new JPanel();
JPanel displayPanel=new JPanel();
public Examiner() {
content=getContentPane();
content.setLayout(new BorderLayout());
buttonPanel.setLayout(new GridLayout(6,1));
buttonPanel.add(stu);
buttonPanel.add(staff);
buttonPanel.add(course);
buttonPanel.add(units);
content.add("North",menuPanel);
content.add("West",buttonPanel);
content.add("Center",displayPanel);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}// end examiner() constructor
public void actionPerformed(ActionEvent clicked){
if(clicked.getSource()==stu){
try{
test();
catch(Exception e){e.printStackTrace();
}// end if
}//end actionperformed
public void paint(Graphics g){
this.paintComponents(g);
super.paint(g);
}//end paint
public void test(){
displayPanel.add(units);
public static void main(String args[]) {
Examiner mainFrame = new Examiner();
mainFrame.setSize(mainFrame.getToolkit().getScreenSize());
mainFrame.setTitle("Examiner");
mainFrame.setVisible(true);
}// end main
}//end Examiner classI have tried to get this to work by calling it from another class (StudentScreen) and also as shown above by simply trying to get it to display one of the icons again. Could use some pointers here
Thanks<<<< falls over>>>>
Now I am really embarrassed. I should have seen that a long time ago. Guess I need to take a break lol
thanks very much for the help. -
How to repaint a JPanel in bouncing balls game?
I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
The first class defines a BALL as a THREAD
If anyone knows how to correct the code please to write....
package fuck;
//THE FIRST CLASS
class CollideBall extends Thread{
int width, height;
public static final int diameter=15;
//coordinates and value of increment
double x, y, xinc, yinc, coll_x, coll_y;
boolean collide;
Color color;
Rectangle r;
bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
//the constructor
public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
width=w;
height=h;
this.x=x;
this.y=y;
this.xinc=xinc;
this.yinc=yinc;
this.balls=balls;
color=c;
r=new Rectangle(150,80,130,90);
public double getCenterX() {return x+diameter/2;}
public double getCenterY() {return y+diameter/2;}
public void move() {
if (collide) {
x+=xinc;
y+=yinc;
//when the ball bumps against a boundary, it bounces off
//bounce off the obstacle
public void hit(CollideBall b) {
if(!collide) {
coll_x=b.getCenterX();
coll_y=b.getCenterY();
collide=true;
public void paint(Graphics gr) {
Graphics g = gr;
g.setColor(color);
//the coordinates in fillOval have to be int, so we cast
//explicitly from double to int
g.fillOval((int)x,(int)y,diameter,diameter);
g.setColor(Color.white);
g.drawArc((int)x,(int)y,diameter,diameter,45,180);
g.setColor(Color.darkGray);
g.drawArc((int)x,(int)y,diameter,diameter,225,180);
g.dispose(); ////////
///// Here is the buggy code/////
public void run() {
while(true) {
try {Thread.sleep(15);} catch (Exception e) { }
synchronized(balls)
move();
balls.repairCollisions(this);
paint(balls.gBuffer);
balls.canvas.repaint();
//THE SECOND CLASS
public class BouncingBalls extends JFrame{
public Graphics gBuffer;
public BufferedImage buffer;
private Obstacle o;
private List<CollideBall> balls=new ArrayList();
private static final int SPEED_MIN = 0;
private static final int SPEED_MAX = 15;
private static final int SPEED_INIT = 3;
private static final int INIT_X = 30;
private static final int INIT_Y = 30;
private JSlider slider;
private ChangeListener listener;
private MouseListener mlistener;
private int speedToSet = SPEED_INIT;
public JPanel canvas;
private JPanel p;
public BouncingBalls() {
super("fuck");
setSize(800, 600);
p = new JPanel();
Container contentPane = getContentPane();
final BouncingBalls xxxx=this;
o=new Obstacle(150,80,130,90);
buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
gBuffer=buffer.getGraphics();
//JPanel canvas start
final JPanel canvas = new JPanel() {
final int w=getSize().width-5;
final int h=getSize().height-5;
@Override
public void update(Graphics g)
paintComponent(g);
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
gBuffer.setColor(Color.ORANGE);
gBuffer.fillRect(0,0,getSize().width,getSize().height);
gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
//paint the obstacle rectangle
o.paint(gBuffer);
g.drawImage(buffer,0,0, null);
//gBuffer.dispose();
};//JPanel canvas end
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
addButton(p, "Start", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
balls.add(b);
b.start();
contentPane.add(canvas, "Center");
contentPane.add(p, "South");
public void addButton(Container c, String title, ActionListener a) {
JButton b = new JButton(title);
c.add(b);
b.addActionListener(a);
public boolean collide(CollideBall b1, CollideBall b2) {
double wx=b1.getCenterX()-b2.getCenterX();
double wy=b1.getCenterY()-b2.getCenterY();
//we calculate the distance between the centers two
//colliding balls (theorem of Pythagoras)
double distance=Math.sqrt(wx*wx+wy*wy);
if(distance<b1.diameter)
return true;
return false;
synchronized void repairCollisions(CollideBall a) {
for (CollideBall x:balls) if (x!=a && collide(x,a)) {
x.hit(a);
a.hit(x);
public static void main(String[] args) {
JFrame frame = new BouncingBalls();
frame.setVisible(true);
} And when i press start button:
Exception in thread "Thread-2" java.lang.NullPointerException
at fuck.CollideBall.run(CollideBall.java:153)
Exception in thread "Thread-3" java.lang.NullPointerException
at fuck.CollideBall.run(CollideBall.java:153)
Exception in thread "Thread-4" java.lang.NullPointerException
at fuck.CollideBall.run(CollideBall.java:153)
and line 153 is: balls.canvas.repaint(); in Method run() in First class.
Please help.public RepaintManager manager;
public BouncingBalls() {
manager = new RepaintManager();
manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
public void run() {
while(true) {
try {Thread.sleep(15);} catch (Exception e) { }
synchronized(balls)
move();
balls.repairCollisions(this);
paint(balls.gBuffer);
balls.manager.paintDirtyRegions(); //////// line 153
but when push start:
Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at fuck.CollideBall.run(CollideBall.java:153)
Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at fuck.CollideBall.run(CollideBall.java:153)
i'm newbie with Concurrency and i cant handle this exceptons.
Is this the right way to do repaint? -
Problem with JPanel and/or Thread
Hello all,
I have the following problem.
I have a JFrame containing to JPanels. The JPanels are placed
via BorderLayout.
JPanel #1 is for moving a little rectangle (setDoubleBufferd), it is
a self defined object extending JPanel.
The paint methon in JPanel #1 has been overwritten to do the drawings.
JPanel #2 contains 4 JButtons, but they have no effect at the
moment. It is an "original" JPanel.
The class extending JFrame implemented the interface Runnable and
is started in its own thread.
After starting the programm everthing looks fine.
But if I press a Button in the second JPanel this button is painted in
the top left corner of my frame. It changes if I press another button.
Any help would be appreciated.
Thanks.
RalfI have a JFrame containing to JPanels. The JPanels are
placed
via BorderLayout.The type of Layout does not seem to be relevant
>
JPanel #1 is for moving a little rectangle
(setDoubleBufferd), it is
a self defined object extending JPanel.
The paint methon in JPanel #1 has been overwritten to
do the drawings.
JPanel #2 contains 4 JButtons, but they have no effect
at the
moment. It is an "original" JPanel.
The class extending JFrame implemented the interface
Runnable and
is started in its own thread.
After starting the programm everthing looks fine.
But if I press a Button in the second JPanel this
button is painted in
the top left corner of my frame. It changes if I press
another button.
I noticed you solved this by painting the whole JFrame.
Yeh Form time to time I get this problem too......
Especially if the screen has gone blank - by going and having a cup of tea etc -
Text from one Panel would be drawn in another.. annoying
At first it was because I changed the state of some Swing Components
not from the Event Thread.
So make sure that your new Thread doesn't just blithely call repaint() or such like cos that leads to problems
but rather something like
SwingUtilities.invokeLater( new Runnable()
public void run()
MyComponent.repaint();
});However I still get this problem using JScrollPanes, and was able to fix it by using the slower backing store method for the JScrollPane
I could not see from my code how something on one JPanel can get drawn on another JPanel but it was happening.
Anyone who could totally enlighten me on this? -
How to give Common Background color for all JPanels in My Swing application
Hi All,
I am developing a swing application using The Swing Application Framework(SAF)(JSR 296). I this application i have multiple JPanel's embedded in a JTabbedPane. In this way i have three JTabbedPane embedded in a JFrame.
Now is there any way to set a common background color for the all the JPanel's available in the application??
I have tried using UIManager.put("Panel.background",new Color.PINK);. But it did not work.
Also let me know if SAF has some inbuilt method or way to do this.
Your inputs are valuable.
Thanks in Advance,
Nishanth.CIt is not the fault of NetBeans' GUI builder, JPanels are opaque by default, I mean whether you use Netbeans or not.Thank you!
I stand corrected (which is short for +"I jumped red-eyed on my feet and rushed to create an SSCCE to demonstrate that JPanels are... mmm... oh well, they are opaque by default... ;-[]"+)
NetBeans's definitely innocent then, and indeed using it would be an advantage (ctrl-click all JPanels in a form and edit the common opaque property to false) over manually coding
To handle this it would be better idea to make a subclass of JPanel and override isOpaque() to return false. Then use this 'Trasparent Panel' for all the panels where ever transparency is required.I beg to differ. From a design standpoint, I'd find it terrible (in the pejorative sense of the word) to design a subclass to inconsistently override a getter whereas the standard API already exposes the property (both get and set) for what it's meant: specify whether the panel is opaque.
Leveraging this subclass would mean changing all lines where a would-be-transparent JPanel is currently instantiated, and instantiate the subclass instead.
If you're editing all such lines anyway, you might as well change the explicit new JPanel() for a call to a factory method createTransparentJPanel(); this latter could, at the programmer's discretion, implement transparency whichever way makes the programmer's life easier (subclass if he pleases, although that makes me shudder, or simply call thePanel.setOpaque(false) before returning the panel). That way the "transparency" code is centralized in a single easy to maintain location.
I had to read the code for that latter's UI classes to find out the keys to use (+Panel.background+, Label.foreground, etc.), as I happened to not find this info in an authoritative document - I see that you seem to know thoses keys, may I ask you where you got them from?
One of best utilities I got from this forum, written by camickr makes getting these keys and their values very easy. You can get it from his blog [(->link)|http://tips4java.wordpress.com/2008/10/09/uimanager-defaults/]
Definitely. I bit a pair of knucles off when discovered it monthes after cumbersomely traversing the BasicL&F code...
Still, it is a matter-of-fact approach (and this time I don't mean that to sound pejorative), that works if you can test the result for a given JDK version and L&F, but doesn't guarantee that these keys are there to stand - an observation, but not a specification.
Thanks TBM for highlighting this blog entry, that's the best keys list device I have found so far, but the questions still holds as to what specifies the keys.
Edited by: jduprez on Feb 15, 2010 10:07 AM -
hai ashrivastava..
thank u for sending this one..now i got some more problems with that screen .. actually i am added one JPanel to JFrame with BorderLayout at south..the problem is when i am drawing diagram..the part of diagram bellow JPanel is now not visible...and one more problem is ,after adding 6 ro 7 buttons remaing buttons are not vissible..how to increase the size of that JPanel...to add that JPanel i used bellow code
JFrame f = new JFrame();
JPanel panel = new JPanel();
f.getContentPane().add(BorderLayout.SOUTH, panel);Hi
JFrame f = new JFrame();
JPanel panel = new JPanel();
// Add this line to ur code with ur requiredWidth and requiredHeight
panel.setPreferredSize(new Dimension(requiredWidth,requiredHeight));
f.getContentPane().add(BorderLayout.SOUTH, panel);
This should solve ur problem
Ashish -
If statement doesn't work in JPanel
Hi everybody.
I'd like somebody tell me the reason why the "if" statement doesn't work in a Jpanel but works in a Japplet. I'm including the fragments of code that are relevant to the question.
Thanks in advance.
public class Applet_INVEN extends JApplet {
jTabbedPane jTabbedPane1 = new JTabbedPane();
Panel_1 p_1 = new Panel_1();
JLabel jLabel1 = new JLabel();
JTextField jTextField1 = new JTextField();
JButton jButton1 = new JButton();
void jButton1_actionPerformed(ActionEvent e) {
if (jTextField1.getText() != "0") //------Executes when the condition is true
jLabel1.setText("bingo");
public class Panel_1 extends JPanel {//------INSIDE a JPANEL
JTextField jTextField1 = new JTextField();
JTextField jTextField2 = new JTextField();
JTextField jTextField3 = new JTextField();
JButton jButton1 = new JButton();
void jButton1_actionPerformed(ActionEvent e) {
jTextField2.setText(jTextField1.getText()); //----Ever executes, of course!
if(jTextField1.getText() != "0") //----Never executes, even when
jTextField3.setText("ojo"); //----the condition is true!You shouldn't use the != operator to test equality of Objects. Use Object.equals() instead.
if (jTextField1.getText() != "0")
should be
if ( ! jTextField1.getText().equals("0"))
or better:
if ( ! "0".equals(jTextField1.getText())) <-- avoids null pointer exception. -
Need help:JPanel not being displayed in the JFrame
Hello,
I have a class called ConstructRoom.java which extends JFrame and another class called DimensionsPanel.java which extends JPanel. In the ConstructRoom class I use the following theContainer.add(new DimensionsPanel());, so I can display my JPanel. Well I get the JFrame but no JPanel. When the this call is made the DimensionsPanel.java code is cycled through, Where has my JPanel gone to?
If I change the DimensionPanel.java extend JFrame and add the the JFrame code. Then I get the JFrame and the JPanel.
Whats going on here?
ThanksI made some of the changes with no luck. Here is some of the code:
---------from ConstructRoom.java--------
//Imports
public class ConstructRoom extends JFrame
//----Member objects and varibles
private static String theTitle; //Varible for title of frame
private JFrame theFrame; //Object for the JFrame
// ----------------------------------------------------------- ConstructRoom
public ConstructRoom(String theTitle)
super(theTitle); //JFrame super class
theFrame = new JFrame("My frame");
Container theContainer = theFrame.getContentPane(); //Frame container
theContainer.setLayout(new FlowLayout());
theContainer.add(new DimensionsPanel());
theFrame.pack();
theFrame.setBounds(10,10,400, 400);
theFrame.addWindowListener(new WindowHandler());
theFrame.setVisible(true);
}//end ConstructRoom(String theTitle)
// -------------------------------------------------------------------- main
public static void main(String args[])
ConstructRoom theRoom = new ConstructRoom(theTitle);
}//end main(String args[])
//----WindowHander
}//end class ConstructRoom extends JFrame
--------from DimensionsPanel.java
//Imports
public class DimensionsPanel extends JPanel
//----Member objects and varibles
private JPanel dimensionsPanel; //The main panel to hold all info
private Box panelBox; //Box for all boxes which is added to the JPanel
private Box furnListBox; //Box for all related items of the furnList
private Box dimensionsBox; //Box for all dimensions (x, y, z)
private Box xFieldBox; //Box for all related items of the xField
private Box yFieldBox; //Box for related items of the yField
private Box zFieldBox; //Box for related items of the zField
private Box buttonsBox; //Box for all buttons
private Box clearBox; //Box for related clear button items
private Box buildBox; //Box for related build button items
private JLabel furnListLabel; //Label for the furnList comboBox
private JLabel xFieldLabel; //Label for the xField
private JLabel yFieldLabel; //Label for yField
private JLabel zFieldLabel; //Label for zField
private JTextField xField; //Text field to enter the x dimension
private JTextField yField; //Text field to enter the y dimension
private JTextField zField; //Text field to enter the z dimension
private JComboBox furnList; //List of selectable furniture objects
private JButton clearButton; //Clear button
private JButton buildButton; //Build button
// --------------------------------------------------------- DimensionsPanel
public DimensionsPanel()
//----Setting up dimensions panel
dimensionsPanel = new JPanel();
dimensionsPanel.setLayout(new BorderLayout());
dimensionsPanel.setPreferredSize(new Dimension(150,150));
dimensionsPanel.setBorder(new TitledBorder(new EtchedBorder(),
"Select Furniture and Enter Dimensions"));
//----Initializing GUI components
furnListLabel = new JLabel("Select from list ");
furnList = new JComboBox();
xFieldLabel = new JLabel("Enter Width ");
xField = new JTextField();
yFieldLabel = new JLabel("Enter Height ");
yField = new JTextField();
zFieldLabel = new JLabel("Enter Depth ");
zField = new JTextField();
buildButton = new JButton("Build Object");
clearButton = new JButton("Clear Object");
//-----Setting up the combo box and adding items
furnList.addActionListener(new ComboProcessor());
furnList.addItem(" "); //Default item
furnList.addItem("Color Cube");
furnList.setMaximumRowCount(6); //Max number of items before scrolling
furnList.setSelectedItem(" "); //Set initial to default item
//--Add the furnList to its box for placement in the JPanel
furnListBox = Box.createHorizontalBox();
furnListBox.add(Box.createHorizontalStrut(5));
furnListBox.add(furnListLabel); //Adding the combo box label
furnListBox.add(furnList); //Adding the combo box
furnListBox.add(Box.createHorizontalStrut(5)); //Spacing
//-------------------------------- Start Dimensions Components
//----Setting up the xField
xField.setEnabled(false); //Disabled at start
xField.setFocusTraversalKeysEnabled(false); //Disabling the Tab Key
//----Adding the event listeners
xField.addActionListener(new XTextProcessor()); //Enter Key
xField.addMouseListener(new ClickProcessor()); //Mouse Click
//--Add the xField to its box for placement in the dimensionsBox
xFieldBox = Box.createHorizontalBox();
xFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
xFieldBox.add(Box.createGlue()); //Take up extra space
xFieldBox.add(xFieldLabel); //Adding the text field label
xFieldBox.add(xField); //Adding the text field
xFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
//----Setting up the yfield
yField.setEnabled(false); //Disabled at start
yField.setFocusTraversalKeysEnabled(false); //Disabling TAB KEY
//----Adding the event listeners
yField.addActionListener(new YTextProcessor()); //Enter Key
yField.addMouseListener(new ClickProcessor()); //Mouse Click
//--Add the yField to its box for placement in the dimensionsBox
yFieldBox = Box.createHorizontalBox();
yFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
yFieldBox.add(Box.createGlue()); //Take up extra space
yFieldBox.add(yFieldLabel); //Adding the text field label
yFieldBox.add(yField); //Adding the text field
yFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
//----Setting up the zfield
zField.setEnabled(false); //Disabled at start
zField.setFocusTraversalKeysEnabled(false); //Disabling TAB KEY
//----Adding the event listeners
zField.addActionListener(new ZTextProcessor()); //Enter Key
zField.addMouseListener(new ClickProcessor()); //Mouse Click
//--Add the zField to its box for placement in the dimensionsBox
zFieldBox = Box.createHorizontalBox();
zFieldBox.add(Box.createHorizontalStrut(10)); //Spacing
zFieldBox.add(Box.createGlue()); //Take up extra space
zFieldBox.add(zFieldLabel); //Adding the text field label
zFieldBox.add(zField); //Adding the text field
zFieldBox.add(Box.createHorizontalStrut(100)); //Spacing
//----Adding all dimension components to the dimensionsBox
dimensionsBox = Box.createVerticalBox();
dimensionsBox.add(xFieldBox); //Adding the xFieldBox
dimensionsBox.add(Box.createVerticalStrut(10)); //Spacing
dimensionsBox.add(yFieldBox); //Adding the yFieldBox
dimensionsBox.add(Box.createVerticalStrut(10)); //Spacing
dimensionsBox.add(zFieldBox); //Adding the zFieldBox
//-------------------------------- End Dimension Components
//----Setting up the clearButton
clearButton.setEnabled(false); //Disabled at start
//----Adding the event listener
clearButton.addActionListener(new ClearProcessor());
//--Add the clear button to its box for placement
clearBox = Box.createHorizontalBox();
clearBox.add(Box.createHorizontalStrut(5)); //Spacing
clearBox.add(clearButton); //Adding the clearButton
//----Setting up the buildButton
buildButton.setEnabled(false); //Disabled at start
//--Add the action listener here
buildBox = Box.createHorizontalBox();
buildBox.add(buildButton); //Adding the buildButton
buildBox.add(Box.createHorizontalStrut(5)); //Spacing
//----Adding both buttons the buttonsBox
buttonsBox = Box.createHorizontalBox();
buttonsBox.add(clearBox); //Adding the clearBox
buttonsBox.add(Box.createHorizontalStrut(10)); //Spacing
buttonsBox.add(buildBox); //Adding the buildBox
//----Create the JPanel (dimensionsPanel)
//--Creating the main box to be added to the JPanel
panelBox = Box.createVerticalBox();
panelBox.add(furnListBox); //Adding the furnListBox components
panelBox.add(Box.createVerticalStrut(10)); //Spacing
panelBox.add(dimensionsBox); //Adding the dimensionBox components
panelBox.add(Box.createVerticalStrut(10)); //Spacing
panelBox.add(buttonsBox); //Adding the buttonsBox components
panelBox.add(Box.createVerticalStrut(10)); //Spacing
dimensionsPanel.add(panelBox); //Adding all components to the JPanel
System.out.println("end dimensionpanel");
}//end DimensionsPanel()
//------ActionListeners
}//end class DimensionsPanel extends JPanel -
Displaying the content of JPanel
hello, I have a JPanel which contains a JScrollPane displaying data from a database. I have created a JButton which permit to hide and show the content
of jpanel (hide and show jscrollpane alternaly). but when I hide the content the first once I cant re-show it. the code of the JButton is :
// first click
jPanel3.add(jScrollPane1, null);
jPanel3.repaint();
// second click
jPanel3.removeAll();
this.repaint();
Best Regards.Instead of actually removing the component from the GUI and then trying to put it back, why don't you just make use of the setVisible() method?
-
Displaying the content of one JPanel in an other as a scaled image
Hi,
I'd like to display the content of one JPanel scaled in a second JPanel.
The first JPanel holds a graph that could be edited in this JPanel. But unfortunately the graph is usually to big to have a full overview over the whole graph and is embeded in a JScrollPanel. So the second JPanel should be some kind of an overview window that shows the whole graph scaled to fit to this window and some kind of outline around the current section displayed by the JScrollPanel. How could I do this?
Many thanks in advance.
Best,
Marc.Hi,
I'd like to display the content of one JPanel scaled
in a second JPanel.
The first JPanel holds a graph that could be edited
in this JPanel. But unfortunately the graph is
usually to big to have a full overview over the whole
graph and is embeded in a JScrollPanel. So the second
JPanel should be some kind of an overview window that
shows the whole graph scaled to fit to this window
and some kind of outline around the current section
displayed by the JScrollPanel. How could I do this?
Many thanks in advance.
Best,
Marc.if panel1 is the graph and panel2 is the overview, override the paintComponent method in panel2 with this
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.scale(...,...);
panel1.paint(g2);
}
Maybe you are looking for
-
10g Physical Standby to be used for Backup through RMAN
Dear All, I have 10g Database Primary and Standby Server which is operating in Maximum Performance Mode. I want to use Standby Database for performing Weekly Full and Daily Incremental Backups through RMAN. Kindly inform me is it possible, if yes how
-
Authentication via Web Service
I'm working on a custom Page Sentry function to tie HTML DB to our existing web Authentication scheme. I've got most of it sorted out, but the glue I'm missing is a call to verify the session details to our external system. Preferrably, I'd like to u
-
Flash Content error......
Hi I found the error popup windows "Flash content error : 9" is displayed when swf file is played in Flash Lite 2.0 on Symbian OS. What is this error popup mean?? And how can I solve this problem?? Please, help me.... Thank you.
-
I'm trying to design a dynamic query that looks like this: 20005-- Jan06 --- Feb06 --- Mar06 --- Apr06 ... Dec06 --- YTD My Problem, ich you give per e.g Dezember, all Months have to appear. Or you give may, your going to receive till may. In the yea
-
Where can I get missing drivers for cd/dvd on ibook
I got this apple lab top and the cd doesn't work, because the driver is missing. Also, I put in an airport card and can't access internet, I can't seem to configure it. It says it's on, but hasn't joined a network, my network is on the list, but w