Problem with JPanel in a JScrollPane
Hi all,
I am devloping an application where in i insert the JPanel's object in the JScrollPane object. Intitially the size of the JPanel's object is more than the size of the JScrollPane object.At this point fo time i can drag the nob of the scrollpane to the extent of the size of the JPanel's object. Now When i move the mouse behond the size of the JPanel i am increasing the size of the JPanel's object but i cant move the nob of the scrollpane object behond the original limit.
For example : when you open a notepad there will be scrollbar without the nob if you keep on pressing the enter key the size of the text area increases and we can see the scroll bar now. I what the similar functionality but
instead of TextArea i need the panel.
If any of you have solved this problem or know the solution please do inform. I need to solve this problem very urgently. Please do help me out.
Thanks in Advance.
regards
Ravi
Hi all,
I got the solution.we need to revalidate the panel object.
i.e JPanel.revalidate()
regards
Ravi Kumar
Similar Messages
-
Problem with Jpanel repaintingl
Hi!
I have a problem with Jpanel.
First , I add a Jscrollpane to the panel and I don't
see it.
Second, I have a paint method in the Jpanel and I do there some painting but when I exe the application I can see the panel painting only when I put the mouse cursor
on the place where the panel need to be.
It is very strange.
Help me.
Yair.Example code??
Can't tell what's wrong otherwise.
First , I add a Jscrollpane to the panel and I don't
see it.Have you added anything to this JScrollPane? Unless you set the scroll bar policies to always on you won't see anything if you haven't added anything to the scrollpane.
Also, if you're only adding this scrollPane to your JPanel initilise it with
JPanel whippet = new JPanel(new BorderLayout())
.. then when you add your scrollPanel to your JPanel do this to make sure its added slap in the in middle of it:
whippet.add(yourScrollPanel, BorderLayout.CENTER);
Bit more info please - duuuuuuuuuuuuuuuude (man, "Finding Nemo" was well funny didn't you think.. anyways, that's besides the point.... could just be my 8 year old mental age though.. who knows.)? -
Problem with JPanel inside JScrollPane
I want to make a simple graphic editor (like MS-Paint) with Java.
I create the frame using JFrame, and use many Swing component. But I found
some difficult when I tried to create the drawing area (the area where user
performs drawing). I use JPanel as drawing area and I put it in JScrollPane.
I use JScrollPane in case if user want to create a big drawing area.
What I want to do with drawing area is, to put it in JScrollPane with size smaller than JScrollPane but I can't get it because the size of drawing area (JPanel) is always be the same as JScrollPane size. In MS-Paint you can see that the canvas (drawing area) size is able to be resize. And the canvas default color is white, and the Scroll Box around it has darkgray color. How can I make it like that (MS-Paint)? Please help. Thanks...
IrfinI haven't actually tested this, but I think it should work...
Add a JPanel to the scrollpane setting it's background to grey (i think the dark grey in MSPaint is something easy like 128,128,128). Set the layout on that panel to null, then add a second panel to that panel, at freeze it's size (ie. setMaximumSize). Doing it this way will allow you to set like a (10,10) position or something like that, giving the second panel a position away from the edge of the scrollpane.
Seeing as you will be using mouse listeners anyways, you might even be able to allow for the second panel to be resized by checking the mouse position to see if the mouse is over the edge of the panel. I won't go into detail, that'll ruin the fun for you.
Good luck, hope this helps.
Grant. -
Problem with JPanel.updateUI()
Hello,
i have a problem with updateUI(), here's a simple example what's wrong. just compile and run the following piece of code and look what happens after 2 seconds: the left panel will be decrease its width after calling updateUI(), but why? is it a bug of updateUI() or is it my fault?
import java.awt.*;
import javax.swing.*;
public class Test extends JPanel
private JList m_list;
private DefaultListModel m_listModel;
private JPanel m_buttons;
public static GridBagConstraints creategbc (int x, int y, int w, int h, int wx, int wy, int f)
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
gbc.weightx = wx;
gbc.weighty = wy;
gbc.fill = f;
gbc.insets = new Insets(5, 5, 5, 5); // kleinen Rahmen ziehen
return gbc;
public Test ()
GridBagLayout gbl = new GridBagLayout();
setLayout(gbl);
GridBagConstraints gbc;
initButtons();
gbc = creategbc(0, 0, 1, 1, 20, 100, GridBagConstraints.NONE);
gbc.anchor = GridBagConstraints.NORTH;
gbl.setConstraints(m_buttons, gbc);
add(m_buttons);
initList();
JScrollPane sp = new JScrollPane(m_list);
gbc = creategbc(1, 0, 1, 1, 100, 100, GridBagConstraints.BOTH);
gbl.setConstraints(sp, gbc);
add(sp);
public void addItem (String item)
m_listModel.addElement(item);
public void initList ()
m_listModel = new DefaultListModel();
m_list = new JList(m_listModel);
public void initButtons ()
m_buttons = new JPanel();
m_buttons.setLayout(new GridLayout(4, 1, 0, 20));
m_buttons.add(new JButton("Neu"));
m_buttons.add(new JButton("Bearbeiten"));
m_buttons.add(new JButton("L�schen"));
m_buttons.add(new JButton("Abfrage"));
public static void main (String[] args)
JFrame f = new JFrame();
Test t = new Test();
f.setContentPane(t);
f.setSize(600, 450);
f.setVisible(true);
try
Thread.sleep(2000);
catch (Exception e)
t.addItem("Hallo");
t.updateUI();Hello,
i have a problem with updateUI(), here's a simple
example what's wrong. just compile and run the
following piece of code and look what happens after 2
seconds: the left panel will be decrease its width
after calling updateUI(), but why? is it a bug of
updateUI() or is it my fault?updateUI() its called when the L&F is changed, there is
rarely a case when you need to call updateUI().
Why do you call updateUI() if you remove the call to updateUI()
everything will work OK.
merry xmas -
Problem with a JList and JScrollpane
Hi,
Im having a problem with horizontal scrolling in that I have a simple JList inside a panel and a text box below where the user enters text. Now the text box has a width of 15, but the user can type as many characters as they want..Now the Jlist only displays 15 characters, but the horizontal scroller does not come up, instead just displays for example abcdefghijkl... (the three dots in the end)..
Isnt my scroller supposed to be automatically scrolling when there is more on the line then the screen displays?? I already have this so far..
scroller = new JScrollPane(dataList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);thanks!Try the following code:
package sample;
import java.awt.*;
import javax.swing.*;
public class MyDialog extends JDialog {
public static void main( String[] args) {
new MyDialog().setVisible(true);
JPanel contentPanel = new JPanel();
JScrollPane scrollPane = new JScrollPane();
JList list = new JList( new Object[] {"abcdefghijklmnopqrstuvwxyz", "123456789012345678901234567890"});
public MyDialog() {
contentPanel.setLayout(new BorderLayout());
getContentPane().add(contentPanel);
contentPanel.add(scrollPane, BorderLayout.CENTER);
scrollPane.getViewport().add(list, null);
setSize( 100,100);
setLocation( 100,100);
}Michael -
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 -
friends,
i have a jpanel with image as background and i am adding jlabels dynamically to the jpanel. i have to move the jlabel on the image so i added mouse listener to jlabel. now i want to add zooming functionality to the jpanel.
now if zoom out jpanel everything works well but jlabel mouse listener location is not changing so if i click on jlabel its not activating listener - i need to click outside of jlabel/jpanel (its original location when its 100% zoom) to activate the listener. how can i correct this ?
thanks in advance
i will add example after i cutdown (its part of big application)import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class PP3 extends JFrame {
private JButton btnStart;
private JButton btnStop;
private JLabel logoLabel;
private JSlider zoom;
private JPanel mainPanel;
private JPanel btnPanel;
private JScrollPane jspane;
private BackPanel3 secondPanel;
private boolean start = false;
public PP3() {
initComponents();
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
private void initComponents() {
logoLabel = new JLabel();
mainPanel = new JPanel();
btnPanel = new JPanel();
btnStart = new JButton();
btnStop = new JButton();
zoom = new JSlider(0,100,100);
setBackground(Color.white);
setLayout(new BorderLayout());
mainPanel.setBackground(Color.white);
mainPanel.setBorder(new EtchedBorder());
mainPanel.setPreferredSize(new Dimension(650, 600));
mainPanel.setLayout(new CardLayout());
jspane = new JScrollPane(getSecondPanel());
mainPanel.add(jspane,"Second Panel");
add(mainPanel, BorderLayout.CENTER);
btnPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2,2,2,2);
gbc.weighty = 1.0;
gbc.gridwidth = gbc.REMAINDER;
btnPanel.setBackground(Color.white);
btnPanel.setBorder(new EtchedBorder());
btnPanel.setPreferredSize(new Dimension(150, 600));
btnStart.setText("Start Labelling");
btnPanel.add(btnStart, gbc);
btnStart.setEnabled(true);
btnStart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
start = true;
btnStart.setEnabled(false);
btnStop.setEnabled(true);
if(secondPanel != null){
secondPanel.setStart(start);
Cursor moveCursor = new Cursor(Cursor.TEXT_CURSOR);
secondPanel.setCursor(moveCursor);
btnStop.setText("Done Labelling");
btnPanel.add(btnStop, gbc);
btnStop.setEnabled(false);
btnStop.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
start = false;
btnStart.setEnabled(true);
btnStop.setEnabled(false);
if(secondPanel != null){
secondPanel.setStart(start);
Cursor moveCursor = new Cursor(Cursor.DEFAULT_CURSOR);
secondPanel.setCursor(moveCursor);
final JLabel zoomLabel = new JLabel("Zoom");
zoomLabel.setBorder(BorderFactory.createEtchedBorder());
gbc.weighty = 0;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
btnPanel.add(zoomLabel, gbc);
btnPanel.add(zoom, gbc);
zoom.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
JSlider source = (JSlider)ce.getSource();
if(secondPanel != null) {
secondPanel.setZoomFactor((double)source.getValue());
zoomLabel.setText("Zoom = " + source.getValue()/100.0);
String id = "<html><nobr>show label</nobr><br><center>locations";
JCheckBox check = new JCheckBox(id, secondPanel.showLocations);
check.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
secondPanel.toggleShowLocations();
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.NONE;
btnPanel.add(check, gbc);
add(btnPanel, BorderLayout.EAST);
pack();
public JPanel getSecondPanel() {
if(secondPanel == null) {
secondPanel = new BackPanel3("images/cougar.jpg", 850, 1100);
secondPanel.setStart(false);
return secondPanel;
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PP3();
class BackPanel3 extends JPanel implements MouseListener,
MouseMotionListener{
String imgPath = null;
BufferedImage image;
private int width = 0;
private int height = 0;
private double zoomFactor = 1.0;
private boolean start = false;
private boolean same = false;
Cursor hourglassCursor = new Cursor(Cursor.MOVE_CURSOR);
// choose a declaration according to your java version
List<JLabel> labels; // declaration for j2se 1.5+
// List labels; // j2se 1.4-
JLabel lastSelected;
boolean showLocations;
JLabel selectedLabel;
boolean dragging;
Point offset;
int count = 0;
private static String SELECTED = "selected";
public BackPanel3(String path, int width, int height){
setLayout(null);
this.width = width;
this.height = height;
setPreferredSize(new Dimension(width,height));
addMouseListener(this);
addMouseMotionListener(this);
// chose an instantiation according to your java version
labels = new ArrayList<JLabel>(); // j2se 1.5+
// labels = new ArrayList(); // j2se 1.4-
lastSelected = new JLabel();
lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
showLocations = true;
dragging = false;
offset = new Point();
this.imgPath = path;
setImage();
public void setImage(){
try{
image = getImage(imgPath);
}catch(Exception e){
System.out.println(" (init) ERROR: " + e);
e.printStackTrace();
public void setStart(boolean flag){
start = flag;
public void setZoomFactor(double zoom){
zoomFactor = (zoom/100);
setPreferredSize(new Dimension((int)(850*zoomFactor), (int)(1100*zoomFactor)));
repaint();
revalidate();
public double getZoomFactor(){
return zoomFactor;
public void toggleShowLocations() {
showLocations = !showLocations;
repaint();
public void mouseClicked(MouseEvent e) {
if(start){
JLabel msgLabel = new JLabel("Test " + count++);
this.add(msgLabel);
Dimension d = msgLabel.getPreferredSize();
msgLabel.setBounds(e.getX(), e.getY(), d.width, d.height);
labels.add(msgLabel);
msgLabel.putClientProperty(SELECTED, Boolean.FALSE);
return;
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
for(int j = 0; j < labels.size(); j++) {
JLabel label = (JLabel)labels.get(j);
Rectangle bounds = label.getBounds();
AffineTransform at =
AffineTransform.getScaleInstance(zoomFactor, zoomFactor);
Shape xs = at.createTransformedShape(bounds);
if(xs.contains(p)) {
selectedLabel = label;
Rectangle r = xs.getBounds();
offset.x = p.x - r.x;
offset.y = p.y - r.y;
dragging = true;
break;
public void mouseReleased(MouseEvent e) {
dragging = false;
public void mouseDragged(MouseEvent me){
if(dragging) {
Rectangle bounds = selectedLabel.getBounds();
AffineTransform at =
AffineTransform.getScaleInstance(1.0/zoomFactor, 1.0/zoomFactor);
Point2D p = at.transform(me.getPoint(), null);
int x = (int)(p.getX() - offset.x);
int y = (int)(p.getY() - offset.y);
selectedLabel.setLocation(x, y);
repaint();
public void mouseMoved(MouseEvent me){
if(labels.size() == 0)
return;
Point p = me.getPoint();
boolean hovering = false;
boolean selectionChanged = false;
for(int j = 0; j < labels.size(); j++) {
final JLabel label = (JLabel)labels.get(j);
Rectangle r = label.getBounds();
AffineTransform at =
AffineTransform.getScaleInstance(zoomFactor, zoomFactor);
Shape scaledBounds = at.createTransformedShape(r);
if(scaledBounds.contains(p)) {
hovering = true;
if(!((Boolean)label.getClientProperty(SELECTED)).booleanValue()) {
label.putClientProperty("selected", Boolean.TRUE);
setCursor(hourglassCursor);
if(lastSelected != label) // for only one JLabel
lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
lastSelected = label;
selectionChanged = true;
break;
// reset lastSelected when there is no selection/hovering
if(!hovering &&
((Boolean)lastSelected.getClientProperty(SELECTED)).booleanValue()) {
lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
setCursor(Cursor.getDefaultCursor());
selectionChanged = true;
if(selectionChanged)
repaint();
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.scale(zoomFactor, zoomFactor);
g2.drawImage(image, 0, 0, this);
if(showLocations) {
// show bounds of the actual JLabel children
// components as they exist on this component
AffineTransform at = AffineTransform.getScaleInstance(1.0/zoomFactor,
1.0/zoomFactor);
g2.setPaint(Color.blue);
Component[] c = getComponents();
for(int j = 0; j < c.length; j++)
g2.draw(at.createTransformedShape(c[j].getBounds()));
// show selected label
g2.setPaint(Color.red);
for(int j = 0; j < labels.size(); j++) {
JLabel label = (JLabel)labels.get(j);
if(((Boolean)label.getClientProperty("selected")).booleanValue()) {
g2.draw(label.getBounds());
break;
protected BufferedImage getImage(String path){
try{
URL imgURL = BackPanel3.class.getResource(path);
if (imgURL == null &&
(path.indexOf(":\\") > 0 || path.indexOf(":/") > 0))
imgURL = new URL("file:///"+path);
return getImage(imgURL);
}catch(MalformedURLException mue){
System.out.println("error "+mue);
return null;
protected BufferedImage getImage(URL url){
try{
if (url != null) {
BufferedImage source = ImageIO.read(url);
double xScale = (double)width / source.getWidth();
double yScale = (double)height / source.getHeight();
double scale = Math.min(xScale, yScale);
int w = (int)(scale*source.getWidth());
int h = (int)(scale*source.getHeight());
BufferedImage scaled = new BufferedImage(w, h, source.getType());
Graphics2D g2 = scaled.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
// scales faster than getScaledInstance
AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
g2.drawRenderedImage(source, at);
g2.dispose();
return scaled;
}else{
return null;
}catch(IOException ioe){
System.out.println("read error "+ioe);
return null;
} -
Problem with JPanel and JDesktopPane
Hi,
I am having a problem with my app and I wonder if someone can see what I am doing wrong. I have a class that extends JFrame that holds a centered JPanel to draw on. There are also 3-4 other JInternalFrames that are in use.
From what I have read to use JDesktopPane to organize the JInternalFrames, all you do is add the JInternalFrames to the JDesktopPane and setContentPane to be the JdesktopPane:
Jpanel panel = new JPanel();
JDesktopPane dm = new JDesktopPane();
setContentPane(dm);
dm.add(panel, BorderLayout.CENTER);
dm.add(internalFrame1);
dm.add(internalFrame2);
dm.add(internalFrame3);But as soon as I add the panel to the JDesktopPane then my JPanel doesnt show up. As I had it before I was adding the panel to the content pane of the Jframe, and adding the JinternalFrames to the layeredPane like this:
getContentPane().add(panel, BorderLayout.CENTER);
lp = getLayeredPane();
lp.add(internalFrame1);
lp.add(internalFrame2);
lp.add(internalFrame3);and this worked but the JInternalFrames behaved badly, not getting focus or moving to the top frame when clicked, which I guess is what JDesktopPane is supposed to do. But how do I get my original JPanel in my JFrame to show up when added to the JDesktopPanel?
Am I missing something here?
Thanks,
PaulThanks for your response. I will try that when I get home, although I will be surprised if that works because I am already using setPreferredSize() . It seemed to me that once a Jframe's content pane gets assigned to a JDesktopPane, then the JPanel no longer has anywhere to draw itself, as according to the Sun documentation, you can only add a JInternalFrame to a JDesktopPane.
So I am thinking its not possible to have a JPanel as the content pane of a JFrame while having a JDesktopPane containing my JInternalFrames. Is this indeed the case?
Thanks,
Paul -
Weird problem with jpanel vs jframe
I'm using jmathplot.jar from JMathTools which lets me do 3d plotting. I used a JFrame to get some code to work and it worked fine. Here's the code that worked for a JFrame:
public class View extends JFrame
private Model myModel;
private Plot3DPanel myPanel;
// ... Components
public View(Model m)
myModel = m;
// ... Initialize components
myPanel = new Plot3DPanel("SOUTH");
myPanel.addGridPlot("Test",myModel.getXRange(),myModel.getYRange(),myModel.getZValues());
setSize(600, 600);
setContentPane(myPanel);
setVisible(true);
}Here's the class that starts everything:
public class TestApplet extends JApplet
public void init()
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try
SwingUtilities.invokeAndWait(new Runnable()
public void run()
createGUI();
catch (Exception e)
e.printStackTrace();
private void createGUI()
System.out.println("Creating GUI");
Model model = new Model();
View view = new View(model);
}And here's the Model:
public class Model
private double[] myXRange,myYRange;
private double[][] myZValues;
public Model()
createDataSet();
public double[] getXRange()
return myXRange;
public double[] getYRange()
return myYRange;
public double[][] getZValues()
return myZValues;
private void createDataSet()
myXRange = new double[10];
myYRange = new double[10];
myZValues = new double[10][10];
for(double i=0;i<10;i++)
for(double j=0;j<10;j++)
double x = i/10;
double y = j/10;
myXRange[(int) i] = x;
myYRange[(int) j] = y;
myZValues[(int) i][(int) j]= Math.cos(x*Math.PI)*Math.sin(y*Math.PI);
}However, as you can see, my main class is a JApplet because ideally I want View to be a JPanel that I add to the applet. All I did was change "extends JFrame" to "extends JApplet" and changed:
setSize(600, 600);
setContentPane(myPanel);
setVisible(true);to
this.add(myPanel);and added these two lines to createGUI():
view.setOpaque(true);
setContentPane(view);When I run it however, it appears really really small. It seems like its drawing the panel to the default size of the applet viewer and doesn't resize it when I resize the applet. I don't know if it's a problem with the library or if I'm doing something wrong in my applet.However, as you can see, my main class is a JApplet because ideally I want View to be a JPanel that I add to the applet. All I did was change "extends JFrame" to "extends JApplet" and (...)What do you mean? View extends JApplet? I thought View was meant to extend JPanel in the end...
When I run it however, it appears really really small. It seems like its drawing the panel to the default size of the applet viewer and doesn't resize it when I resize the applet.Or, the panel has its preferred size, and this latter is too small. Actually the panel has the size its container's layout manager awards it (taking or not the panel's preferred, minimum, and maximum sizes into account). See the tutorial on [layout managers|http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html] .
In particular, this line adds the myPanel to a parent panel (presumably, it is in class View which extends JPanel, whose default layout is FlowLayout):
this.add(myPanel);
I don't know if it's a problem with the library or if I'm doing something wrong in my applet.Likely not (presumably the library interfers only in how it computes the Plot3DPanel's preferred size). There's an easy way to tell: try to layout correctly a custom JPanel of yours, containing only e.g. a button with an icon. Once you understand the basics of layout management, revisit the example using ther 3rd-party library.
N.B.: there are a lot of "likely" and "presumably" in my reply: in order to avoid hardly-educated guesses especially on what is or isn't in your actual code, you'd better provide an SSCCE , which means reproducing the problem without the 3rd party library. -
Problem with JPanel and JScrollPane
Hey,
I have a class which extends JPanel. Inside this class I would like to have a JScrollPane.
However, it does not seem to work.
public class Summary extends JPanel
JScrollPane scrollPane;
JPanel p;
public Summary()
p = new JPanel()
public void paintComponent(Graphics g)
/// do painting here!!!!
setLayout(null);
setBorder(BorderFactory.createLineBorder(Color.green));
setBounds(0,0,240,290);
//p.setLayout(null);
p.setLayout(new FlowLayout());
p.setBorder(BorderFactory.createLineBorder(Color.black));
//p.setBounds(0,0,240,590);
p.setPreferredSize(new Dimension(240,500));
p.add(new JButton("test"));
scrollPane = new JScrollPane(p);
scrollPane.setLayout(null);
scrollPane.setBounds(0,0,240,290);
scrollPane.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(scrollPane);
}Any advice????
thanks in advanceAny advice????ditch this
setLayout(null); -
Hi,
I have a Jpanel with BorderLayout which has two components. First one is a JScrollpane which sits at CENTER and another is JEditorPane which sits at south. JScrollPane itself is over a JEditorPane ..... PROBLEM is I can't see the component sitting at SOUTH, any focus???Hi,
I haven't seen this before. Is it possible to get some sample code that illustrates the problem? Feel free to email me at [email protected] (please remove any attachment extension) and I'll take a look.
Moving discussion to the Problems & Bugs forum.
Thanks,
Chris -
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? -
Problem with JPanel, JMenuBar
Hi, I'm new here so I'm not even sure if I'm posting in the correct forum ^^
I usually don't have problems when building a JFrame and adding items into it but now I'm confused.
When the JFrame is "built", I get a NullPointerException from the Panel's paintComponent method when it's trying to draw an image (g.drawImage())
This is the whole JPanel class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PanneauDe extends JPanel
private static final String [] TAB_IMAGE = { "De1.GIF", "De2.GIF", "De3.GIF",
"De4.GIF", "De5.GIF", "De6.GIF" };
private static final int [] TAB_FREQUENCE = {0,0,0,0,0,0};
private static final int SIDE = 100;
private De unDe;
private ImageIcon imageDe;
private boolean aFirstTime;
private int aX, aY;
public PanneauDe()
unDe = new De();
aX = aY = 0;
aFirstTime = true;
addMouseListener(new EcouteurSouris());
public String getStats()
String statsMsg = "";
for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
statsMsg += "Face " + (iPos + 1) + " : " + TAB_FREQUENCE[iPos] + " fois\n\n";
return statsMsg;
public String getTotal()
int total = 0;
for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
total += TAB_FREQUENCE[iPos];
return "Le d� a �t� lanc� " + total + " fois";
public void throwDice()
unDe.throwAgain();
TAB_FREQUENCE[unDe.getFace() - 1] ++;
public void paintComponent (Graphics g)
super.paintComponent(g);
g.drawImage (imageDe.getImage(), aX, aY, null); // <---- THIS GENERATES THE NULLPOINTEREXCEPTION
class EcouteurSouris extends MouseAdapter
public void mouseClicked (MouseEvent pMouseEvent)
aX = pMouseEvent.getX();
aY = pMouseEvent.getY();
throwDice();
imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
repaint();
}When I click in the windows, a picture of a dice (different side, randomly generated by the method throwDice() ), when I click again the first image dissapear and another one appears... and I make statistics about the results.
I tried ...
public void paintComponent (Graphics g)
super.paintComponent(g);
//g.drawImage (imageDe.getImage(), aX, aY, null);
class EcouteurSouris extends MouseAdapter
public void mouseClicked (MouseEvent pMouseEvent)
aX = pMouseEvent.getX();
aY = pMouseEvent.getY();
throwDice();
imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
Graphics g = getGraphics();
g.drawImage (imageDe.getImage(), aX, aY, null);
g.dispose();
}Everything works correctly, no more NullPointerException, but the images don't dissapear when I click again. They just stay there.
I'm not completly familiar with the repaint/dispose/paintComponent but I really don't understand why i get this NullPointerException error :\
If you see some weird words in the code, it's because i'm canadian-frenchy! :)
Full program is hereThe real question is why are you trying to override the paintComponent() method. Just add the image to a JLabel and add the label to a panel.
However, the problem is that the paintComponent() method is invoked when the frame is shown and since you don't create the image until you do a mouseClick, the image in null. -
hello everyone!
i want to create a GUI consisting of a JTextField and a Jbutton which should be North aligned
and a JTextArea with a scrollbar south aligned. i created the following code but the button appears cut.
what's going wrong? could you help me?
Thanks!
Here is the code :
panel=new JPanel();
panel2=new JPanel();
enterField = new JTextField(20);
button=new JButton("Send");
enterField.setEnabled( false );
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
panel.add(enterField);
panel.add(button);
displayArea = new JTextArea(10,15);
displayArea.setEnabled( false );
scroller = new JScrollPane( displayArea );
panel2.add(displayArea);
panel2.add(scroller);
Container container = getContentPane();
container.add( panel, BorderLayout.NORTH );
container.add( panel2, BorderLayout.SOUTH );
setSize( 300, 150 );
setVisible( true );i changed the code as following but now the label, textfield and the button
all appear in the same line. But i want they appear the one under the other.
why does this happen?
panel=new JPanel();
panel2=new JPanel();
label=new JLabel("Choose a number from 1 to 10:");
enterField = new JTextField(8);
button=new JButton("Send");
enterField.setEnabled( false );
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
panel.add(label);
panel.add(enterField);
panel.add(button);
displayArea = new JTextArea(5,18);
displayArea.setEnabled( false );
scroller = new JScrollPane( displayArea );
panel2.add(scroller);
Container container = getContentPane();
container.add( panel, BorderLayout.NORTH );
container.add( panel2, BorderLayout.SOUTH );
//setSize(400,250);
pack( );
setVisible( true ); -
Problem with JPanel after rotation
Hi,
I am developing a graphics editor like mspaint. I have JPanel as my drawing canvas. now the problem is when I rotate the canvas, co-ordinates on the canvas are also getting rotate with it. for example if top-left corner is (0,0) initially then after rotating it 90 degree top-right corner becomes (0,0) and same for all the points on the canvas.
the code i m using for rotation is
contentPanel = new JPanel(){
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Rectangle rect=g2.getClipBounds();
if(rotation!=0){
double angle = rotation * Math.PI/2;
g2.rotate(angle,getWidth()/2,getHeight()/2);
rect=g2.getClipBounds();
setPreferredSize(new Dimension(rect.width,rect.height));
super.paintComponent(g);
revalidate();
};Whats your question?
If you rotate it, of course the points will rotate, they have to.
Maybe you are looking for
-
Dialog programming, data being washed out in TAB Control
Hi, i am working on dialog programming , in which i am using Table Control for user input (data is not coming from database table) . everything is going well till assignment of data to internal table but when control goes to PBO by any means li
-
Is There A Nav Bar Plugin?
Is there I can get a navagation bar from this website and put it on this one but get it all working? I have the nav bar on the website but it tries to locally link to the webite making it un-avilable... any help would be appriciated... I orignally to
-
Set formula to ignore blank cells
Hiya. Like Anim8me2 (good question about using formulas to assign letter grades to ranges of values), I am building a grade book for teaching. I really want to get away from my clunky and inelegant gradebook program and should be able to if I can sol
-
Global keyboard shortcuts (Exposé, Spotlight, etc.) not working
I've run into an odd problem with my computer--sometime around or after I upgraded to 10.4.8, my global keyboard shortcuts have just flat-out stopped working. I noticed this quickly because I use LaunchBar and it stopped activating when I hit its key
-
The javascript code is not working.
Hi , I tried to disable a text field by using the following code. I am able to disable the field, but the field is still allowing to enter data in disable mode also. The code I used is: var curr_state = thisItem.getProperty("state"); var correct