JPanel
I have a JFrame, in which im adding a JPanel,
frame.getContentPane().add(panel1);
Now what i want is that if i add another panel to the frame,
frame.getContentPane().add(panel2);
where panel1 and panel2 are to be placed at the same location, when panel2 is added, it should be visible above panel1
Not sure if I understood your problem, but maybe you should consider using http://java.sun.com/j2se/1.5/docs/api/java/awt/CardLayout.html
Similar Messages
-
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);
} -
How to enable a scrollbar in a JPanel
Hi
I am adding some components in a JPanel and I am adding the JPanel to a JScrollPane.The JScrollPane is finally added to the container.Now I could manage to get only the scrollbars added but it does not work!How should I use the scrollbars to view all the components that are added inside the JPanel.
Here is my source code:
tagPanel = new JPanel();
tagPanel.setLayout(new FlowLayout());
tagPanel.setPreferredSize(new Dimension(100,100));
tagPanel.setBackground(Color.white);
tagPanel.setAutoscrolls(true);
for(int i = 0; i<=20; i++)
tempButton = new JButton("Testing");
tagPanel.add(tempButton);
container.add(forbiddenscroll= new JScrollPane
(tagPanel),BorderLayout.WEST);
forbiddenscroll.setHorizontalScrollBarPolicy
(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
forbiddenscroll.setVerticalScrollBarPolicy
(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
Thank you for your reply!
Your help is very much appreciated.don't set prefered size of the tag panel.
run this code pasted below. it work fine.
regards,
Pratap
import java.awt.*;
import javax.swing.*;
public class Frame1 extends JFrame {
JScrollPane forbiddenscroll;
JPanel tagPanel;
JButton tempButton;
public Frame1() {
tagPanel = new JPanel();
tagPanel.setLayout(new FlowLayout());
tagPanel.setBackground(Color.white);
tagPanel.setAutoscrolls(true);
for(int i = 0; i<=20; i++)
tempButton = new JButton("Testing");
tagPanel.add(tempButton);
forbiddenscroll = new JScrollPane();
forbiddenscroll.getViewport().setView(tagPanel);
getContentPane().add(forbiddenscroll, BorderLayout.CENTER);
forbiddenscroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
forbiddenscroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
public static void main(String[] args) {
Frame1 f = new Frame1();
f.pack();
f.setLocation(200,200);
f.show();
} -
How to draw a 3Drect in a JPanel.
Hi, I'd like to draw a 3D rectangle in a panal to make some components looks grouped. e.g. if I have a name(JLabel: JTextField) and address(JLabel:JTextField) in a panel and want to draw a 3D rectangle around these two fields, how can I do that? Looks that the paint(Graphics g) doesn't work here.
The following is my test program, it has two files, an applet as program entrance and a Panel to draw on:
// TestApplet.java
import javax.swing.*;
public class TestApplet extends JApplet {
public void init() {
TopPanel tp = new TopPanel();
add(tp);
// TopPanel.java
import javax.swing.*;
public class TopPanel extends JPanel {
public TopPanel() {
JLabel lb = new JLabel("test");
add(lb);
Choice c = new Choice();
c.add("1");
c.add("2");
add(c);
public void paint(Graphics g) {
g.draw3DRect(5, 5, 40, 40, false);
super.paint(g);
}sorry for the messy code.
I've tried switching the two lines, but it doesn't
work. :(
Here is the repost of the code, I don't know why I
can't edit the original post....
// TestApplet.java
import javax.swing.*;
public class TestApplet extends JApplet {
public void init() {
TopPanel tp = new TopPanel();
add(tp);
// TopPanel.java
import javax.swing.*;
import java.awt.*;
public class TopPanel extends JPanel {
public TopPanel() {
JLabel lb = new JLabel("test");
add(lb);
Choice c = new Choice();
c.add("1");
c.add("2");
add(c);
public void paint(Graphics g) {
super.paint(g);
g.draw3DRect(5, 5, 40, 40, false);
1. You can only edit posts that have not been replied to.
2. Your code worked for me? (What is the problem).
3. Suggestions use a JComboBox instead of Choice. (It is not good to mix AWT and Swing.) Also you should be overiding paintComponentinstead of paint.
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.draw3DRect(5, 5, 40, 40, false);
} -
How to add a JScrollPane in a JPanel
I have a JPanel (layout = null, size = 200*400).
I would like to add a JScrollPane, that sizes 100*100 and that contains an other JPanel, at the location 0,200 in the first JPanel. I would like too that the JScrollBar is always visible.
How is it possible ?The scrollbars will appear automatically when the preferred size of the panel is greater than the size of the scroll pane. So you probably need to add:
panel.setPreferredSize(...);
Of course if you use LayoutManagers, instead of a null layout, then this is done automatically for you.
If you want the scroll bars to appear all the time then read the JScrollPane API. -
How to Fit a component in a JPanel
Hy, I am actually creating a Graphical Programming Language Appln and I am facing some problems.
My source code is found below. Here is my problem:
I have inserted some buttons have been inserted in the Main panel until both scroll bar appear,
what I want is that when I click on the button label "Fit", a new window opens,
where it shows the buttons which have been fitted in that window, without any scrollbar.How to do that?
Please send me the code for solving this problem. Its very very urgent.Here are my Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import javax.swing.tree.*;
import java.io.*;
public class MainDesktop extends JFrame implements ActionListener {
JSplitPane splitPane = new JSplitPane();
JPanel mainPane = new JPanel();
JScrollPane mainScrollPane = new JScrollPane();
Container contentPane = getContentPane();
public MainDesktop() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
//Adding the ToolBar to the main window
JToolBar toolBar = new JToolBar();
myToolBar(toolBar);
contentPane.add(toolBar, BorderLayout.NORTH);
//create a list of button and add them to a pane
JButton bgButton = new JButton("Begin");
JButton rdButton = new JButton("Read");
JButton wrButton = new JButton("Write");
JButton efButton = new JButton("If-Else");
JButton ifButton = new JButton("End-If");
JButton wlButton = new JButton("While-Loop");
JButton flButton = new JButton("For-Loop");
JButton elButton = new JButton("End-Loop");
JButton swButton = new JButton("Switch");
JButton arButton = new JButton("Arithmetic");
JButton enButton = new JButton("End");
bgButton.setActionCommand("Begin");
rdButton.setActionCommand("Read");
wrButton.setActionCommand("Write");
efButton.setActionCommand("If-Else");
ifButton.setActionCommand("End-If");
wlButton.setActionCommand("While-Loop");
flButton.setActionCommand("For-Loop");
elButton.setActionCommand("End-Loop");
swButton.setActionCommand("Switch");
arButton.setActionCommand("Arithmetic");
enButton.setActionCommand("End");
bgButton.addActionListener(this);
rdButton.addActionListener(this);
wrButton.addActionListener(this);
efButton.addActionListener(this);
ifButton.addActionListener(this);
wlButton.addActionListener(this);
flButton.addActionListener(this);
elButton.addActionListener(this);
swButton.addActionListener(this);
arButton.addActionListener(this);
enButton.addActionListener(this);
JPanel toolPane = new JPanel();
toolPane.setLayout(new GridLayout(15,0));
toolPane.add(bgButton);
toolPane.add(rdButton);
toolPane.add(wrButton);
toolPane.add(efButton);
toolPane.add(ifButton);
toolPane.add(wlButton);
toolPane.add(flButton);
toolPane.add(elButton);
toolPane.add(swButton);
toolPane.add(arButton);
toolPane.add(enButton);
//Create a pane for the drawing area and add scroll pane to it
mainPane.setLayout(new FlowLayout());
mainScrollPane = new JScrollPane(mainPane);
mainScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
mainScrollPane.setHorizontalScrollBarPolicy (JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
mainScrollPane.setLayout(new ScrollPaneLayout());
//Create a split pane with the two scroll panes in it
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,toolPane, mainScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(100);
splitPane.setPreferredSize(new Dimension(1000, 650));
getContentPane().add(splitPane);
protected void myToolBar(JToolBar toolBar) {
//Fit button
JButton fitButton = new JButton("Fit");
fitButton.setToolTipText("Fit Flowchart to drawing area");
fitButton.setActionCommand("Fit");
fitButton.addActionListener(this);
toolBar.add(fitButton);
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("Fit")) {
//fit flowchart to drawing area
if (cmd.equals("Delete")) {
//Delete a node from flowchart
//Action command for the list of button from the toolbox
if (cmd.equals("Begin")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("Read")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("Write")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("If-Else")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("End-If")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("While-Loop")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("For-Loop")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("End-Loop")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("Switch")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
if (cmd.equals("Arithmetic")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
//mainPane.repaint();
if (cmd.equals("End")) {
dragbutton drag = new dragbutton();
mainPane.add(drag);
//mainPane.repaint();
class dragbutton extends JButton implements DragGestureListener, DragSourceListener {
public dragbutton() {
super("Begin");
DragSource dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this,DnDConstants.ACTION_COPY_OR_MOVE,this);
public void dragGestureRecognized(DragGestureEvent e) {
e.startDrag(DragSource.DefaultCopyDrop,
new StringSelection(null),this);
public void dragDropEnd(DragSourceDropEvent e) {}
public void dragEnter(DragSourceDragEvent e) {}
public void dragExit(DragSourceEvent e) {}
public void dragOver(DragSourceDragEvent e) {}
public void dropActionChanged(DragSourceDragEvent e) {}
public static void main(String [] args) {
MainDesktop mainWindow = new MainDesktop();
mainWindow.setTitle("Graphical Programming Language");
mainWindow.setSize(700, 600);
mainWindow.setVisible(true);Instead of using:
frame.setSize(int, int);
use:
frame.pack(); -
How to replace a component in the JPanel?
Hi,
I want to replace a component in the JPanel. My panel has GridBagLayout.
Thanks in advance.because my application demands me to use GridBagLayout.No it doesn't, that a choice you made. You are never forced to use a specific layout manager. In fact most layout problems are solved by using combinations of layout managers. You two main choices are:
a) use a GridbagLayout for the main panel and then a CardLayout for the two components you want to sway, although it may look strange if the components are a different size as the preferred size of the panel will be the size of the largest component
b) Simulate a card layout using:
panel.remove(...)
panel.add(...);
panel.revalidate(...) -
How to generate a chart in JPanel
i want to implement (draw) a grpahical bar chart on JPanel , please help me
Search the forum. This question has been asked many time. Maybe a simple keyword like "chart" or "graph" will get you started.
-
How to draw a JPanel in an offscreen image
I am still working on painting a JPanel on an offline image
I found the following rules :
- JPanel.setBounds shall be called
- the JPanel does not redraw an offline image, on should explicitly override paint()
to paint the children components
- the Children components do not pain, except if setBounds is called for each of them
Still with these rules I do not master component placement on the screen. Something important is missing. Does somebody know what is the reason for using setBounds ?
sample code :
private static final int width=512;
private static final int height=512;
offScreenJPanel p;
FlowLayout l=new FlowLayout();
JButton b=new JButton("Click");
JLabel t=new JLabel("Hello");
p=new offScreenJPanel();
p.setLayout(l);
p.setPreferredSize(new Dimension(width,height));
p.setMinimumSize(new Dimension(width,height));
p.setMaximumSize(new Dimension(width,height));
p.setBounds(0,0,width,height);
b.setPreferredSize(new Dimension(40,20));
t.setPreferredSize(new Dimension(60,20));
p.add(t);
p.add(b);
image = new java.awt.image.BufferedImage(width, height,
java.awt.image.BufferedImage.
TYPE_INT_RGB);
Graphics2D g= image.createGraphics();
// later on
p.paint(g);
paint method of offScreenPanel :
public class offScreenJPanel extends JPanel {
public void paint(Graphics g) {
super.paint(g);
Component[] components = getComponents();
for (int i = 0; i < components.length; i++) {
JComponent comp=(JComponent) components;
comp.setBounds(0,0,512,512);
components[i].paint(g);Unfortunately using pack doesn't work, or I didn't use it the right way.
I made a test case, eliminated anything not related to the problem (Java3D, applet ...). In the
test case if you go to the line marked "// CHANGE HERE" and uncomment the jf.show(), you have
an image generated in c:\tmp under the name image1.png with the window contents okay.
If you replace show by pack you get a black image. It seems there still something.
simplified sample code :[b]
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.sun.j3d.utils.applet.*;
import com.sun.j3d.utils.image.*;
import com.sun.j3d.utils.universe.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class test {
private static final int width=512;
private static final int height=512;
public test() {
JPanel p;
BorderLayout lay=new BorderLayout();
java.awt.image.BufferedImage image;
// add a JPanel with a label and a button
p=new JPanel(lay);
p.setPreferredSize(new Dimension(width,height));
JLabel t=new JLabel("Hello");
t.setPreferredSize(new Dimension(60,20));
p.add(t,BorderLayout.NORTH);
p.setDebugGraphicsOptions(DebugGraphics.LOG_OPTION );
// show the panel for debug
JFrame jf=new JFrame();
jf.setSize(new Dimension(width,height));
jf.getContentPane().add(p);
[b]
// CHANGE HERE->
jf.pack();
//jf.show();
// create an off screen image
image = new java.awt.image.BufferedImage(width, height,
java.awt.image.BufferedImage.TYPE_INT_RGB);
// paint JPanel on off screen image
Graphics2D g= image.createGraphics();
g.setClip(jf.getBounds());
System.err.println("BEFORE PAINT");
jf.paint(g);
System.err.println("AFTER PAINT");
// write the offscreen image on disk for debug purposes
File outputFile = new File("c:\\tmp\\image1.png");
try {
ImageIO.write(image, "PNG", outputFile);
} catch (Exception e) {
System.err.println(e.getMessage());
g.dispose();
jf.dispose();
public static void main(String[] args) {
test t=new test();
}
Maybe you are looking for
-
Deleted coremidi.framework & CAN'T OPEN MUSIC PROGRAM. please help!
I use Ableton LIVE to make music. I don't know what "coremidi".framework is, but the coremidi.framework folder always bounces in my dock. I recently downloaded and installed my first plugin (Waves Tune) which wasn't working, so I suspected this Core
-
Why i can not open my itunes how to solve this problem
i have problem with my itunes version 10.3 but it said the file itunes library it could'nt be read it was created by new version of itunes where i can go to find the library of itunes or how to solve this problem..
-
Pages documents "too old to open?"
I have folders of important documents created using older versions of Pages that will not open in the new version. I do not have an older version of Pages on this (new) computer. Is there a known solution?
-
I am having trouble exporting my file as a pdf.
I have a document which I am creating in indesign, about 100 pages long, with images, etc. Each time I try to export it as a pdf it crashes, and then when I try opening the pdf the error message comes up saying that Adobe reader could not open this f
-
Is it successful and reliable to deploy the fax and modem over IP in production? Does it stable enough to replace the PSTN connection? Do delay and packet drops in the network affect so much for fax and modem traffic? How about to implement fax and m