JPanel location
hi,
I"m working on the program that's similar to paint,
and I would like to place my contentPane to be at the specific location (for the drawing area).
Is there anyway, rather than BoxLayout, FlowLayout, or GridLayout to set the location of the JPanel?
like, I would like to place it in x- and y-coordinates of (50,120) and the size of 500 X 320.
Help would be really appreciated it. thank you!
altjs89 wrote:
would this be the right way to do it?No. This would be correct if you want to use absolute positioning and sizing of components added to this JPanel. It will have no effect on the relative or absolute location and size of the drawingArea JPanel itself. To affect that, you must set the layout manager of the component that holds this JPanel to null. But what exactly are you trying to achieve here? Please give a more detailed and specific description, because I'll bet that null layout is not the solution you need. Also, on rereading your initial post, what do you mean about contentPane? The contentPane of the JFrame or JApplet? That would mean you want to change the location of the application on the screen? Or are you talking about the location of a JPanel within an application (which I had assumed in my prior answer)?
Similar Messages
-
Hi,
I'm having a lot of difficulty setting the size and position of JPanels.
I have an application with 2 panels, one above the other, and I need one to be a certain size (i.e. button height).
Can anybody help? It keeps keeping the 1/2 ratio.
Thanks in advance,
HughCheck out this section from the Swing tutorial on "Using Layout Managers":
http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html -
I'm attempting to write Monopoly and I'm having some inheritance problems. Every space on the board is first and foremost of type BoardSpace however some of them are of type Property which extends BoardSpace and some are of type Chance/Community which also extend BoardSpace etc. Depending on what type of space it is something different happens. Right now heres how a couple of classes look. I'm having a problem where if I land on a space that doesn't define its own action method, it defaults to the BoardSpace action method as it should yet it goes into that if statement even when it clearly shouldn't be. Like if I land in jail, it will still go into that if statement, and it will print Jail (3 times). Is this something funky with inheritance?
BoardSpace:
public class BoardSpace extends JPanel
Location loc;
String name;
public BoardSpace(String s, Location l)
loc = l;
name = s;
public void action(Player p)
if(name.equals("Go"));//If name is "go" how can it also be "jail" ?
System.out.println(name);
System.out.println(this.name);
System.out.println(p.spot.name);
p.money+=200;
}Property:
import javax.swing.*;
public class Property extends BoardSpace
Player owner = null;
public Property(String s, Location l)
super(s,l);
public void action(Player p)
if(owner!=null && owner!=p)
JOptionPane.showMessageDialog(this,"You landed on "+this.name+".\n This property is owned by Player" +owner.number+".\n You owe $5");
else
JOptionPane.showInputDialog("Buy?");
}duckbill wrote:
Hint: you can launch JOptionPane dialogs without a single panel, frame etc...
#You can also launch dialogs with panels, frames, etc... but without subclassing Property from JPanel
Edited by: DrLaszloJamf on Oct 3, 2007 12:42 PM -
Hi
I have just started lerning Java in my school, but they are only doing Applets and whith no LayoutManagers. But I want to learn more. My teacher isn't very good at this so I'm asking you. If you can tell me what is wrong with this code.
The program dosen't do anything yet so thats not the problem. I'm having problem with the SpringLayout.
Here is the code.
import javax.swing.*;
import java.awt.*;
import java.awt.Container;
import java.awt.event.*;
public class SpringDemo1 implements ActionListener{
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
Container contentPane;
public void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Sl�ttar T�lur");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = frame.getContentPane();
prentaVidmot();
//takki.addActionListener(this);
//S�na gluggan
frame.pack();
frame.setVisible(true);
public static void prentaVidmot(){
//Set up the content pane.
//SpringLayout layout = new SpringLayout();
JPanel kassi = new JPanel();
SpringLayout layout = new SpringLayout();
kassi.setLayout(layout);
kassi.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
//Create and add the components.
JLabel label = new JLabel("Tala: ");
JTextField tala = new JTextField(15);
JLabel labelNidurstodur = new JLabel("Ni�urst��ur: ");
TextArea textabox = new TextArea(5,21);
JButton takki = new JButton("Reikna");
kassi.add(label);
kassi.add(tala);
kassi.add(labelNidurstodur);
kassi.add(textabox);
kassi.add(takki);
//Stilla sta�setningu label
kassi.putConstraint(SpringLayout.WEST, label, 5,SpringLayout.WEST, kassi);
kassi.putConstraint(SpringLayout.NORTH, label,5,SpringLayout.NORTH, kassi);
//Stilla sta�setningu tala
kassi.putConstraint(SpringLayout.WEST, tala,50,SpringLayout.EAST, label);
kassi.putConstraint(SpringLayout.NORTH, tala,5,SpringLayout.NORTH, kassi);
//Stilla sta�setningu labelNidurstodur
kassi.putConstraint(SpringLayout.WEST, labelNidurstodur, 0, SpringLayout.WEST, label);
kassi.putConstraint(SpringLayout.NORTH, labelNidurstodur, 10, SpringLayout.SOUTH, label);
//Stilla sta�setningu textabox
kassi.putConstraint(SpringLayout.WEST, textabox, 0, SpringLayout.WEST, tala);
kassi.putConstraint(SpringLayout.NORTH, textabox, 5, SpringLayout.SOUTH, tala);
//Stilla sta�setningu takka
kassi.putConstraint(SpringLayout.EAST, takki,0,SpringLayout.EAST, textabox);
kassi.putConstraint(SpringLayout.NORTH, takki,10,SpringLayout.SOUTH, textabox);
//Stilla st�r� glugga
public void actionPerformed(ActionEvent event){
double teljari = (Double.parseDouble(tala.getText()));
System.out.println("Foo");
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}And here is the error:
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:66: cannot resolve symbol
symbol : method putConstraint (java.lang.String,javax.swing.JLabel,int,java.lang.String,javax.swing.JPanel)
location: class javax.swing.JPanel
kassi.putConstraint(SpringLayout.WEST, label, 5,SpringLayout.WEST, kassi);
^
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:67: cannot resolve symbol
symbol : method putConstraint (java.lang.String,javax.swing.JLabel,int,java.lang.String,javax.swing.JPanel)
location: class javax.swing.JPanel
kassi.putConstraint(SpringLayout.NORTH, label,5,SpringLayout.NORTH, kassi);
^
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:70: cannot resolve symbol
symbol : method putConstraint (java.lang.String,javax.swing.JTextField,int,java.lang.String,javax.swing.JLabel)
location: class javax.swing.JPanel
kassi.putConstraint(SpringLayout.WEST, tala,50,SpringLayout.EAST, label);
^
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:71: cannot resolve symbol
symbol : method putConstraint (java.lang.String,javax.swing.JTextField,int,java.lang.String,javax.swing.JPanel)
location: class javax.swing.JPanel
kassi.putConstraint(SpringLayout.NORTH, tala,5,SpringLayout.NORTH, kassi);
^
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:74: cannot resolve symbol
symbol : method putConstraint (java.lang.String,javax.swing.JLabel,int,java.lang.String,javax.swing.JLabel)
location: class javax.swing.JPanel
kassi.putConstraint(SpringLayout.WEST, labelNidurstodur, 0, SpringLayout.WEST, label);
^
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:75: cannot resolve symbol
symbol : method putConstraint (java.lang.String,javax.swing.JLabel,int,java.lang.String,javax.swing.JLabel)
location: class javax.swing.JPanel
kassi.putConstraint(SpringLayout.NORTH, labelNidurstodur, 10, SpringLayout.SOUTH, label);
^
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:78: cannot resolve symbol
symbol : method putConstraint (java.lang.String,java.awt.TextArea,int,java.lang.String,javax.swing.JTextField)
location: class javax.swing.JPanel
kassi.putConstraint(SpringLayout.WEST, textabox, 0, SpringLayout.WEST, tala);
^
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:79: cannot resolve symbol
symbol : method putConstraint (java.lang.String,java.awt.TextArea,int,java.lang.String,javax.swing.JTextField)
location: class javax.swing.JPanel
kassi.putConstraint(SpringLayout.NORTH, textabox, 5, SpringLayout.SOUTH, tala);
^
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:82: cannot resolve symbol
symbol : method putConstraint (java.lang.String,javax.swing.JButton,int,java.lang.String,java.awt.TextArea)
location: class javax.swing.JPanel
kassi.putConstraint(SpringLayout.EAST, takki,0,SpringLayout.EAST, textabox);
^
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:83: cannot resolve symbol
symbol : method putConstraint (java.lang.String,javax.swing.JButton,int,java.lang.String,java.awt.TextArea)
location: class javax.swing.JPanel
kassi.putConstraint(SpringLayout.NORTH, takki,10,SpringLayout.SOUTH, textabox);
^
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:90: cannot resolve symbol
symbol : variable tala
location: class SpringDemo1
double teljari = (Double.parseDouble(tala.getText()));
^
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:101: non-static method createAndShowGUI() cannot be referenced from a static context
createAndShowGUI();
^
12 errors
Tool completed with exit code 1If you are just learning Java, you should not start with GUI programming. You'll need all the basics to really understand what you are doing.
For example you seem to have problems reading and understanding error messages. That's understandable, because at first they may seem intimidating.
Let's look at the first error:
N:\T�l103\Forritun\javasafn\forrit_04_01\SpringDemo1.java:66: cannot resolve symbol
symbol : method putConstraint (java.lang.String,javax.swing.JLabel,int,java.lang.String,javax.swing.JPanel)
location: class javax.swing.JPanel
kassi.putConstraint(SpringLayout.WEST, label, 5,SpringLayout.WEST, kassi);
^The first line tells you where the problem occurs (the file and the line nummer) and what the general error is ("cannot resolve symbol" means that some class/method/variable/... can't be found).
The second line tells you which symbol it can't find (a method named putConstraint taking the list of parameters specified).
The third line tells you where it tried to find the symbol (the class JPanel).
The fourth line shows you the line of code that didn't compile.
You should now analyze and fix each error one, one after the other. -
How to make a simple form layout without ad RAD tool
I'm trying to make a simple form, but I'm not finding the right layout manager to make the components goes in Y axis. The BoxLayout could solve my problem, if it does not fill all the panel with the components.
My SCCEE:
public class TestSimpleForm extends JPanel {
JLabel nameLbl = new JLabel("Name:");
JTextField nameField = new JTextField();
JButton okBtn = new JButton("OK");
JButton cancelBtn = new JButton("Cancel");
public TestSimpleForm() {
add(nameLbl);
add(nameField);
add(okBtn);
add(cancelBtn);
public static void main(String[] args) {
JPanel panel = new TestSimpleForm();
// if i make it a boxlayout panel, the text field size goes huge
// panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JFrame f = new JFrame();
f.setContentPane(panel);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 600);
f.setLocationRelativeTo(null);
f.setVisible(true);
}wellington7 wrote:
..My SCCEE:While I don't know what an SCCEE is, I am very familiar with the SSCCE, and..
public class TestSimpleForm extends JPanel {
.....this code is surely not an SSCCE.
Running tool: Java Compile
/media/disk/projects/numbered/all/TestSimpleForm.java:1: cannot find symbol
symbol: class JPanel
public class TestSimpleForm extends JPanel {
^
/media/disk/projects/numbered/all/TestSimpleForm.java:3: cannot find symbol
symbol : class JLabel
location: class TestSimpleForm
JLabel nameLbl = new JLabel("Name:");
^
/media/disk/projects/numbered/all/TestSimpleForm.java:4: cannot find symbol
symbol : class JTextField
location: class TestSimpleForm
JTextField nameField = new JTextField();
^
/media/disk/projects/numbered/all/TestSimpleForm.java:6: cannot find symbol
symbol : class JButton
location: class TestSimpleForm
JButton okBtn = new JButton("OK");
^
/media/disk/projects/numbered/all/TestSimpleForm.java:7: cannot find symbol
symbol : class JButton
location: class TestSimpleForm
JButton cancelBtn = new JButton("Cancel");
^
/media/disk/projects/numbered/all/TestSimpleForm.java:3: cannot find symbol
symbol : class JLabel
location: class TestSimpleForm
JLabel nameLbl = new JLabel("Name:");
^
/media/disk/projects/numbered/all/TestSimpleForm.java:4: cannot find symbol
symbol : class JTextField
location: class TestSimpleForm
JTextField nameField = new JTextField();
^
/media/disk/projects/numbered/all/TestSimpleForm.java:6: cannot find symbol
symbol : class JButton
location: class TestSimpleForm
JButton okBtn = new JButton("OK");
^
/media/disk/projects/numbered/all/TestSimpleForm.java:7: cannot find symbol
symbol : class JButton
location: class TestSimpleForm
JButton cancelBtn = new JButton("Cancel");
^
/media/disk/projects/numbered/all/TestSimpleForm.java:17: cannot find symbol
symbol : class JPanel
location: class TestSimpleForm
JPanel panel = new TestSimpleForm();
^
/media/disk/projects/numbered/all/TestSimpleForm.java:22: cannot find symbol
symbol : class JFrame
location: class TestSimpleForm
JFrame f = new JFrame();
^
/media/disk/projects/numbered/all/TestSimpleForm.java:22: cannot find symbol
symbol : class JFrame
location: class TestSimpleForm
JFrame f = new JFrame();
^
/media/disk/projects/numbered/all/TestSimpleForm.java:24: cannot find symbol
symbol : variable JFrame
location: class TestSimpleForm
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
^
13 errors
Exited: 256 -
Help with placing the JComponents at a particular location in JPanel
Hello All,
I think it is simple in placing JLabel with an icon or just just text at a particular location in the JPanel. But it is notworking. I know it is very simple but i think i am missing something. Here is code please help with this code.
Thanks
Smithaimport java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import javax.swing.*;
public class DocumentGraphicalRepresentation {
public void buildDocumentation() {
JFrame frame = new JFrame("Graphical Representation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(0, 0, 475, 265);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 475, 265);
panel.setBackground(Color.lightGray);
//panel.setLayout(new BorderLayout());
JLabel label0 = new JLabel(new ImageIcon("c:/arrow.gif"));
label0.setLocation(61, 68);
label0.setOpaque(false);
panel.add(label0);
JLabel label1 = new JLabel(new ImageIcon("c:/bulb.gif"));
label1.setLocation(338, 139);
label1.setOpaque(false);
panel.add(label1);
frame.getContentPane().add(panel);
frame.setVisible(true);
public static void main(String args[]) {
DocumentGraphicalRepresentation document = new DocumentGraphicalRepresentation();
document.buildDocumentation();
}When adding components to a null layout you must set both a location and size for them to show up.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import javax.swing.*;
public class DGR {
public void buildDocumentation() {
JFrame frame = new JFrame("Graphical Representation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(0, 0, 475, 265);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 475, 265);
panel.setBackground(Color.lightGray);
//panel.setLayout(new BorderLayout());
JLabel label0 = new JLabel(new ImageIcon(//"c:/arrow.gif"));
"images/geek/geek-----.gif"));
Dimension d = label0.getPreferredSize();
label0.setSize(d);
label0.setLocation(61, 68);
// label0.setOpaque(false);
panel.add(label0);
JLabel label1 = new JLabel(new ImageIcon(//"c:/bulb.gif"));
"images/hawk.jpg"));
d = label1.getPreferredSize();
label1.setBounds(338,139,d.width,d.height);
// label1.setLocation(338, 139);
System.out.println("label1.isOpaque = " + label1.isOpaque());
// label1.setOpaque(false);
panel.add(label1);
frame.getContentPane().add(new JScrollPane(panel));
frame.setVisible(true);
public static void main(String args[]) {
new DGR().buildDocumentation();
} -
How locate a JPanel in a JPanel (SOS !!!)
I add the class affectation (see below) in a JPanel but I can't succeed in locating it in this JPanel..
I have tried to use setLayout(null) and to use setLocate and setBounds but it doesn't work..
Thanks
public class Affectation extends JPanel{
public Affectation(int deb, int fin,Color couleur){
this.setBackground(couleur);
this.setBorder(BorderFactory.createLineBorder(Color.black));
//this.setBounds(new Rectangle(deb,10,fin-deb,20));
this.setLocation(deb, 7);
this.setPreferredSize (new Dimension(fin-deb,20));
this.setMinimumSize (new Dimension(fin-deb,20));
this.setMaximumSize (new Dimension(fin-deb,20));
}You have to locate Affectation in the container you add it to.
JPanel otherPanel = new JPanel(new NullLayout());
Affectation myAffectation = new Affection( deb, fin, coleur);
otherPanel.add(myAffectation);
myAffectation.setLocation(deb, 7);
other something like that.
Cheers
DB -
Locate a JPanel in an other JPanel (HELP !!!)
I add the class affectation (see below) in a JPanel but I can't succeed in locating it in this JPanel..
I have tried to use setLocate and setBounds but it doesn't work
public class Affectation extends JPanel{
public Affectation(int deb, int fin,Color couleur){
this.setBackground(couleur);
this.setBorder(BorderFactory.createLineBorder(Color.black));
//this.setBounds(new Rectangle(deb,10,fin-deb,20));
this.setLocation(deb, 7);
this.setPreferredSize (new Dimension(fin-deb,20));
this.setMinimumSize (new Dimension(fin-deb,20));
this.setMaximumSize (new Dimension(fin-deb,20));
}Here's an example that uses absolute positioning to get a drag effect:import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
public Test () {
Dimension sizeA = new Dimension (300, 300);
Dimension sizeB = new Dimension (300, 300);
DragPanel dragPanelA = new DragPanel (sizeA, new Rectangle (100, 100, 100, 100), Color.YELLOW);
DragPanel dragPanelB = new DragPanel (sizeB, new Rectangle (100, 100, 100, 100), Color.GREEN);
WrapPanel wrapPanelA = new WrapPanel (sizeA, dragPanelA, Color.GREEN);
WrapPanel wrapPanelB = new WrapPanel (sizeB, dragPanelB, Color.YELLOW);
getContentPane ().setLayout (new GridLayout (1, 2));
getContentPane ().add (wrapPanelA);
getContentPane ().add (wrapPanelB);
setDefaultCloseOperation (DISPOSE_ON_CLOSE);
setResizable (false);
setTitle ("Drag those panels!");
pack ();
setLocationRelativeTo (null);
show ();
private class WrapPanel extends JPanel {
private Dimension size;
public WrapPanel (Dimension size, Component component, Color background) {
this.size = size;
setLayout (null);
add (component);
setBackground (background);
public Dimension getPreferredSize () {
return size;
private class DragPanel extends JPanel {
private Dimension outerSize;
private Rectangle bounds;
public DragPanel (Dimension outerSize, Rectangle bounds, Color background) {
this.outerSize = outerSize;
this.bounds = bounds;
setBounds (bounds);
setBackground (background);
DragListener dragListener = new DragListener ();
addMouseListener (dragListener);
addMouseMotionListener (dragListener);
private class DragListener implements MouseListener, MouseMotionListener {
private Point previousPoint;
public DragListener () {
previousPoint = null;
public void mousePressed (MouseEvent event) {
previousPoint = event.getPoint ();
public void mouseReleased (MouseEvent event) {
previousPoint = null;
public void mouseDragged (MouseEvent event) {
Point point = event.getPoint ();
int dx = point.x - previousPoint.x;
int dy = point.y - previousPoint.y;
bounds.x = getBetween (bounds.x + dx, 0, outerSize.width - bounds.width);
bounds.y = getBetween (bounds.y + dy, 0, outerSize.height - bounds.height);
setBounds (bounds);
private int getBetween (int value, int lower, int upper) {
return (value < lower) ? lower : (value > upper) ? upper : value;
public void mouseClicked (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
public void mouseMoved (MouseEvent event) {}
public static void main (String[] parameters) {
new Test ();
}Alternatively, you could create a super wrap panel (or something similar) to place the wrap panels in.
Kind regards,
Levi -
Set Location of JPanel in another JPanel
Hello, i want to set the location of a JPanel in another JPanel.
This is my code:
* To change this template, choose Tools | Templates
* and open the template in the editor.
package nemo;
* @author Administrator
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class BackgroundImage extends JFrame
JScrollPane scrollPane;
ImageIcon icon;
ImageIcon iconDrinken;
Image image;
public BackgroundImage() {
icon = new ImageIcon("startpage.JPG");
iconDrinken = new ImageIcon("drankje.JPG");
JPanel panel = new JPanel() {
protected void paintComponent(Graphics g) {
// Dispaly image at at full size
g.drawImage(icon.getImage(), 0, 0, null);
super.paintComponent(g);
JPanel panelDrinks = new JPanel() {
protected void paintComponent(Graphics g) {
g.drawImage(iconDrinken.getImage(), 0, 0, null);
super.paintComponent(g);
panelDrinks.setOpaque( false );
panelDrinks.setPreferredSize( new Dimension(200, 215) );
panel.setOpaque( false );
panel.setPreferredSize( new Dimension(400, 400) );
scrollPane = new JScrollPane( panel );
getContentPane().add( scrollPane );
panel.add(panelDrinks);
public static void main(String [] args)
BackgroundImage frame = new BackgroundImage();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}When i execute this i get this:
[http://img208.imageshack.us/img208/738/nowml5.jpg]
And i want the image in the first white box from the left.
But how to do it???
I've tried .setLocation and .setBounds
Edited by: Sven.nl on Apr 17, 2008 2:42 AM
Edited by: Sven.nl on Apr 17, 2008 2:43 AMI already found it. Thanks anyway.
JPanel panelDrinks = new JPanel() {
protected void paintComponent(Graphics g) {
g.drawImage(iconDrinken.getImage(), 100, 200, 200, 215, null);
super.paintComponent(g);
panelDrinks.setOpaque( false );
panelDrinks.setPreferredSize( new Dimension(800, 600) );
panelDrinks.setLocation(300, 300);
Edited by: Sven.nl on Apr 17, 2008 3:05 AM -
Location of node of JTree in JPanel?
Hello
does anyone know how I can retrieve the location (x and y) of a node of a JTree, which is in a JPanel?Assuming your JPanel is the direct parent of your JTree and assuming you're asking for the location relative to the JPanel origin, this should do it.
Rectangle r = tree.getRowBounds(tree.getRowForPath(yourNodePath));
Point p = tree.getLocation();
r.x += p.x;
r.y += p.y;Simple enough to find in the API ;o) -
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 -
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 put a JPanel in a JTable
I have been having problems with using a JPanel in each cell in a column of a JTable. I have a class "myPanel" which extends JPanel and has an overridden paint() function. In each row I want the "myPanel" to be displayed in the cell.
I've read all the documentation(that I could find online), and have searched for a while, but have not found the right way to do this.
I currently have defined myPanel like this:
class myPanel extends JPanel implements TableCellRenderer{
public Component getTableCellRendererComponent( ... ) {
repaint();
public void paint(Graphics g) { ... }
So, In my paint function I am not sure which cell(in the table) needs to be painted, but in the getTableCellRendererComponent, I know the cell to be rendered but I can't actually paint anything(I dont have a Graphics object to paint on).
SO either I get my graphics painted into every cell in the column identically, or I don't see anything in the cells. How do I paint differently in different cells.
Should I be using the object passed into getTableCellRendererComponent directly?
And I don't think there is a default renderer for a panel which would display the panel.
Any hints would be wonderful, as I can't get this to work.You should use your myPanel with the params row and column as if the panel in that row and that column is the one to paint and return it from the method getCellRendererComponent, like in this code.
public Component getTableCellRendererComponent(...){
//....set the properties of your panel/CellRenderer as needed
//for displaiing the cell located in the row and column you get as //parameters,
//even adding or removing buttons or other stuffs from your panel
return this;
// you return the CEllRenderer itself !!! The table will do the painting work !!
That's it !!!
Do not use paint or repaint, you don't need it !!!
Bye Massimo -
How to display a JPanel of JButtons on ImagePanel?
Hi
From the Swing Hacks examples, I can display a JButton on an ImagePanel no problem. But when I put this JButton in JPanel, then add the JPanel to the ImagePanel, the JPanel with the JButton is not displayed.
Can someone please explain why this is?
Here is the ImagePanel code:
import java.awt.*;
import javax.swing.*;
public class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null),img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
public void paintComponent(Graphics g) {
g.drawImage(img,0,0,null);
}And here is the code to add a JButton to a JPanel, then add the JPanel to the ImagePanel:
import javax.swing.*;
import java.awt.event.*;
public class ImageTest {
public static void main(String[] args) {
ImagePanel panel = new ImagePanel(new ImageIcon("images/background.png").getImage());
JPanel buttonPanel = new JPanel()
JButton button = new JButton("Button");
buttonPanel.add(button);
JFrame frame = new JFrame("Hack #XX: Image Components");
frame.getContentPane().add(button); // WORKS!
//frame.getContentPane().add(buttonPanel); // NO BUTTON IS DISPLAYED???
frame.pack();
frame.setVisible(true);
}ThankssetLayout(null);When you use a null layout then you are responsible for setting the size and location of any component added to the panel. The default location is (0,0) so thats ok, but the default size of the button panel is also (0,0) which is why nothing get painted.
Don't use a null layout. Let the layout manager layout any component added to it.
Also, I would override the getPreferredSize() method of your ImagePanel to return the size of the image, instead of setting the preferred size in the constructor. -
How to refresh a JPanel/JTextArea
My main problem is that I don't know how to correctly refresh a JTextArea in an Applet. I have an Applet with 2 internal frames. Each frame is comprised of a JPanel.
The first internal frame calls the second one as shown below:
// Set an internal frame for Confirmation and import the Confirm class into it//
Container CF = nextFrame.getContentPane();
//<Jpanel>
confirmation = new Confirmation( );
CF.add ( confirmation, BorderLayout.CENTER );
mFrameRef.jDesktopPane1.add(nextFrame,JLayeredPane.MODAL_LAYER);
currentFrame.setVisible(false); // Hide this Frame
nextFrame.setVisible(true); // Show Next Frame/Screen of Program
confirmation (Jpanel) has a JTextArea in it. When it's called the first time it displays the correct information (based on choices from the first frame). If a user presses the back button (to return to first frame) and changes something, it doesn't refresh in the JTextArea when they call the confirmation(Jpanel) again. I used System.out.println (called right after jtextareas code), and it shows the info has indeed changed...I guess I don't know how to correctly refresh a JTextArea in an Applet. Here is the relevent code for the 2nd Internal Frame (confirmation jpanel):
// Gather Info to display to user for confirmation //
final JTextArea log = new JTextArea(10,35);
log.setMargin(new Insets(5,5,5,5));
log.setEditable(false);
log.append("Name: " storeInfoRef.getFirstName() " "
+storeInfoRef.getLastName() );
log.append("\nTest Project: " +storeInfoRef.getTestProject() );
JScrollPane logScrollPane = new JScrollPane(log);Here is the relevant code that I am having the problem with...
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class Confirmation extends JPanel {
// Variables declaration
private StoreInfo storeInfoRef; // Reference to StoreInfo
private MFrame mFrameRef; // Reference to MFrame
private Progress_Monitor pmd; // Ref. to Progress Monitor
private JLabel ConfirmMessage; // Header Message
private JButton PrevButton; // Navigation Button btwn frames
private JInternalFrame prevFrame, currentFrame; // Ref.to Frames
// End of variables declaration
public Confirmation(MFrame mFrame, StoreInfo storeInfo) {
mFrameRef = mFrame; // Reference to MFrame
storeInfoRef = storeInfo; // Reference to Store Info
prevFrame = mFrameRef.FileChooserFrame; // Ref. to Previous Frame
currentFrame = mFrameRef.ConfirmationFrame; // Ref. to this Frame
initComponents();
// GUI for this class //
private void initComponents() {
ConfirmMessage = new JLabel();
PrevButton = new JButton();
UploadButton = new JButton();
setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraints1;
ConfirmMessage.setText("Please confirm that the information "
+"entered is correct");
add(ConfirmMessage, gridBagConstraints1);
// Gather Info to display to user for confirmation //
final JTextArea log = new JTextArea(10,35);
log.setMargin(new Insets(5,5,5,5));
log.setEditable(false);
log.append("Name: " storeInfoRef.getFirstName() " "
+storeInfoRef.getLastName() );
log.append("\nTest Project: " +storeInfoRef.getTestProject() );
log.append("\nTest Director: " +storeInfoRef.getTestDirector() );
log.append("\nTest Location: " +storeInfoRef.getTestLocation() );
log.append("\nDate: " +storeInfoRef.getDate() );
String fileOutput = "";
Vector temp = new Vector( storeInfoRef.getFiles() );
for ( int v=0; v < temp.size(); v++ )
fileOutput += "\n " +temp.elementAt(v); // Get File Names
log.append("\nFile: " +fileOutput );
// log.repaint();
// log.validate();
// log.revalidate();
JScrollPane logScrollPane = new JScrollPane(log);
System.out.println("Name: " storeInfoRef.getFirstName() " " +storeInfoRef.getLastName() );
System.out.println("Test Project: " +storeInfoRef.getTestProject() );
System.out.println("Test Director: " +storeInfoRef.getTestDirector() );
System.out.println("Test Location: " +storeInfoRef.getTestLocation() );
System.out.println("Date: " +storeInfoRef.getDate() );
System.out.println("File: " +fileOutput );
// End of Gather Info //
add(logScrollPane, gridBagConstraints1);
PrevButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
PrevButtonMouseClicked(evt);
PrevButton.setText("Back");
JPanel Buttons = new JPanel();
Buttons.add(PrevButton);
add(Buttons, gridBagConstraints1);
// If User Presses 'Prev' Button //
private void PrevButtonMouseClicked(java.awt.event.MouseEvent evt) {
try
currentFrame.setVisible(false); // Hide this Frame
prevFrame.setVisible(true); // Show Next Frame/Screen of Program
catch ( Throwable e ) // If A Miscellaneous Error
System.err.println( e.getMessage() );
e.printStackTrace( System.err );
}// End of Confirmation class
Maybe you are looking for
-
How do I create a new Sharepoint site at Home to connect with our own Website?
How do I connect our website with our home computer. I am not linked with a company server site - just what has been created with the website, so how do I connect to a server or that server; know the server details and how can I link my Sharepoint wi
-
Net Price Issue while creating PO w.r.t PR
Dear All, While creating PO w.r.t PR, there is error given by the system as Net Price is not adopted. Net Price remains as zero. All the others details are automatically adopted. Is there customization required so that Net Price is adopted from PR wh
-
I have stopped using IE because it doesn't work, however my iTunes will not connect to the internet now because it is tied to the proxy setting in IE and now I am using FireFox, so, how do I get iTunes to see FireFox as my web browser.
-
Lead Questionnaire not displayed in WebUI
Hi Experts, I have created a questionnaire in Lead settings and assigned to the transaction type. I have left out the determination criteria blank. When I run the lead transaction in Sapgui the questionnaire is displayed under the evaluation tab.The
-
Imac boots up in verbose mode after been left overnight!
Hello I have recently bought a used Imac 2010 model and have upgraded to Mountain Lion all was fine for a few days. Know if I leave my computer overnight and reboot it comes on in text mode which I have to exit to get to the GUI. Also when shutting d