ScrollPane problem
All,
i am trying to create my own TextArea, as i need to output lines of text with different colors on each line (a TextArea can only have one color for the text?).
i have created the following program but whenever i click on the scrollbar to scroll down all of the text disappears.
Where am i going wrong? please help
regards
package scrollbar;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ScrollBar extends Applet
public Canvas canvas = new Canvas();
public ScrollPane pane = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
public void init()
this.setLayout(null);
canvas.setBackground(Color.white);
pane.add(canvas);
pane.setSize(300, 200);
pane.setLocation(10,10);
this.add(pane);
public void paint(Graphics g)
System.out.println("paint");
Graphics gr = canvas.getGraphics();
int posX = 10;
int posY = 10;
for (int i = 0; i < 20; i++)
gr.drawString("TEST FONT ", posX, posY);
posY += 20;
this is because u draw strings over the ScrollPane and not in it, and every time you scroll it, it calls the repaint method and paint over your strings.
my suggestion is to put a label in the scrollpane and write your strings on the label or it could be easier to set html text in the label like this:l.setText("<html><body>....")good luck
mamtz
Similar Messages
-
ScrollPane Problem breaking my heart...
HI .I Want to read in a number from a textfield.This number will decide how many textfileds will appear on a panel. I want to then add this panel to a ScrollPane.I have this working but when the panel is in the scrollPane it doesnt scroll down the full length of the panel
heres my code structure
Create Scrollpane
Read integer
Create panel with textFields
Add Panel to Scrollpane
Add ScrollPane
Is this the wrong way.....
Any help really appreciatedThe client area of a ScrollPane is sized according to the components preferred size. The return value of the panels getPreferredSize is interesting. Does it have the value you expect?
public Dimension getPreferredSize()
Dimension dim;
dim=super.getPreferredSize();
System.out.println(�Preferre size:�+dim.width+�, �+dim.height);
Return dim;
}The other possible problem is the validation. When is the layout performed?
public void doLayout()
System.out.println(�doLayout() called�);
}Try to add the above two methods to your panel class.
Ragnvald. -
ScrollPane Problem (please help!!!!)
I've got a class PanneauImages (extends JPanel) and it contains (zone_photo) a canvas on which i draw images(several images ( a set of images) on one canvas, that's y i need a ScrollPane).
In the application, we have a button to change the set of images, like to go from set 1 to set 2 etc...
we may need the scroller to show for the first set for example, but not the second. so it's supposed to show for the 1st set, disapear for the 2nd and come back for set 3 for example.
I have a method repaint in the canvas class....
my problem is, that the scroller jsut doesn't move when i change the set of images. and the weird thing is that this happens only when I run the application on Windows. On LINUX i don't have any problems...
here's the full code of the two classes...
PS : the button that chages the set is contained in another class that contains the class PanneauImage...
first, Panneau Images...
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import dbtables.*;
* Classe : PanneauImages
* Description : Cette classe represente un panneau contenant l'ensemble des images
* elles meme contenues dans une zone
* Societe : Medias France
* @version 1.0
class PanneauImages extends JPanel
* La page resultat contenat cette page
ResultPanel parent;
* La zone contenant les images encadrees
Imag zone_photo;
* Dimensions
int width, height;
* La barre de defilement contenant les images
ScrollPane sp;
//===========================================================================================
* Constructeur par defaut.
* @param res Le parent
* @param chain La dexieme partie de l'adresse
* @return Sans objet.
public PanneauImages(ResultPanel res, int w, int h)
parent = res;
width = w;
height = h;
setLayout(new BorderLayout());
sp = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
zone_photo = new Imag(this, sp, width, height);
sp.add(zone_photo);
Adjustable vadjust = sp.getVAdjustable();
Adjustable hadjust = sp.getHAdjustable();
add(sp, "Center");
* redessiner les photos
* @param Sans objet.
* @return Sans
public void redessiner()
//zone_photo.changeHeight();
zone_photo.effacer();
zone_photo.repaint();
* Trouver la meilleure taille pour le composant
* @param Sans objet.
* @return La taille optimale
public Dimension getPreferredSize()
return new Dimension(width, height);
* Trouver la meilleure marge pour le composant
* @param Sans objet.
* @return La marge optimale
public Insets getInsets()
return new Insets(5,5,5,5);
and Imag
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import dbtables.*;
* Classe : Imag
* Description : Cette classe represente plusieurs image dans des cadres
* Societe : Medias France
* @version 1.0
class Imag extends Canvas
* Le scrollPane contenant cette classe
ScrollPane scroll;
* La classe contenant ces images
PanneauImages parent;
* Variables
int id,nb_images=0, indice=0, ancien_hauteur=0;
int width, height;
* Hauteur et largeur du cadre
int hauteur, largeur;
* tableau contenant les adresses des images
java.awt.Image[] img;
* les Coordonnees des images
int x,y, xx, yy;
* lee nombre d'images par ligne
int nbImLigne;
//===========================================================================================
* Constructeur par defaut.
* @param par Le parent
* @param s Le scroller
* @param w la largeur du conteneur d'origine
* @param h La hauteur du conteneur d'origine
* @return Sans objet.
public Imag(PanneauImages par,ScrollPane s, int w, int h)
parent = par;
width=w;
height = h;
indice=0;
scroll = s;
//le listener pour le zoom sur les images
addMouseListener(new MouseAdapter()
public void mouseClicked(MouseEvent evt)
//Coordonnee x du click souris
int x;
//Coordonnee y du click souris
int y;
//Le numero de ligne ou l'on a clique
int resy;
//Le numero de colonne ou l'on a clique
int resx;
//Le numero de l'image selectionnee
int num_image;
//recuperer les coordonnee du click
y = evt.getY();
x = evt.getX();
//trouver la ligne et la colonne
resy = y / 210;
resx = x / 182;
//verifier si le click est effectivement sur une image
int i1 = 10+210*resy;
int i2 = 172+210*resy;
if((i1 < y) && (i2 > y))
//rien faire
else
resy = -1;
int i3 = 10+182*resx;
int i4 = 172+182*resx;
if((i3 < x ) && (i4 > x ))
//rien faire
else
resx = -1;
//si click bon
if((resx > -1) && (resy > -1))
num_image = (resy *nbImLigne)+resx;
if (num_image < nb_images)
//creation et ouverture d'une fenetre image
Frame f = new Frame("Zoom");
ImageZoom imgzoom = new ImageZoom(f, img[num_image]);
* Dessiner les images
* @param r Le contexte graphique utilise pour le dessin.
* @return Sans objet.
public void paint(Graphics g)
//pollen courant
int nbre = parent.parent.numPollen;
//nombre d'images pour ce pollen
nb_images = ((ReqPropPollen)parent.parent.vectResult.elementAt(nbre)).images.size();
if (nb_images > 0)
img = new java.awt.Image[nb_images];
Photo p;
//recuperer les images a dessiner
for(int i = 0; i < nb_images; i++)
String s = ((dbtables.Image)((ReqPropPollen)parent.parent.vectResult.elementAt(nbre)).images.elementAt(i)).getChem_ima();
p = new Photo(this,s);
img[i] = p.img;
int j;
x=10;
y=10;
j=0;
xx=0;
yy=0;
//variables utilisees pour distribuer les images dans la fenetre
int xmax = parent.parent.parent.parent.getSize().width-70;
//nbre d'images max par ligne
nbImLigne = xmax/182;
//cas ou on ne peut afficher qu'une colone d'images
if (nbImLigne==0)
j = -1;
//pour toutes les images, les dessiner
for (int i=0; i<nb_images; i++)
largeur = img.getWidth(this);
hauteur = img[i].getHeight(this);
taille();
//tant qu'on peut dessiner une autre image sur la meme ligne...
if (j<nbImLigne)
g.drawRect(x-1,y-1,162,162); // trace un rectangle noir autour de la photo
g.drawImage(img[i],x+xx,y+yy,largeur, hauteur,this); // affiche la photo
x=x+182; //*(j+1);
j++;
else
j = 0;
x = 10;
y = y+210;
g.drawRect(x-1,y-1,162,162); // trace un rectangle noir autour de la photo
g.drawImage(img[i],x+xx,y+yy,largeur, hauteur,this); // affiche la photo
j++;
x=x+182;
width = 0; //permet de ne pas afficher une barre horizontale
int i1;
int i2;
if (nbImLigne==0)
i1 = nb_images;
i2 = nb_images - i1;
else
i1 = nb_images/nbImLigne;
i2 = nb_images - (i1*nbImLigne);
int i3;
if(i2 > 0)
i3 = i1+1;
else
i3 = i1;
height = 210*i3;
if (nbImLigne==0)
width = 182;
else
width = 182*nbImLigne;
//modifier la taille du Canvas
setBounds(getX(), getY(), width, height);
System.out.println("la largeur du canvas est de "+ getWidth());
System.out.println("la hauteur du canvas est de "+ getHeight());
else
System.out.println("pas d'images pour ce pollen");
* Calculer les variables pour le placement des images
* @param Sans objet.
* @return Sans objet.
public void taille()
int haut_tmp = hauteur*160/largeur;
if (haut_tmp >= 160)
largeur = largeur*160/hauteur;
hauteur=160;
xx = (160-largeur)/2;
yy = 0;
else
largeur = 160;
hauteur = haut_tmp;
yy = (160-hauteur)/2;
xx = 0;
* Mise a jour du Canvas sans effacer le fond a chaque fois
* @param p Le contexte graphique
* @return Sans objet.
public void update(Graphics g)
paint(g);
* Effacer le fond du Canvas
* @param p Le contexte graphique
* @return Sans objet.
public void effacer()
Graphics g = getGraphics();
g.clearRect(getX(), getY(), getWidth(), height);
g.dispose();
* Trouver la taille minimale pour le composant
* @param Sans objet.
* @return La taille minimale
public Dimension getMinimumSize()
return new Dimension(width, height);
* Trouver la meilleure taille pour le composant
* @param Sans objet.
* @return La taille optimale
public Dimension getPreferredSize()
return new Dimension(width, height);
* Trouver la meilleure marge pour le composant
* @param Sans objet.
* @return La marge
public Insets getInsets()
return new Insets(0,0,0,0);OMG! it's worse! now I have the scroller (both horizontal and vertical!)all the time!!! It's as if it doesn't even see the JComponent!
I tried changing the method paint to paintComponent but it doesn't change anything :o(
anyway, this is really weird, i don't understant why it's ok with LINUX and not with windows :o(
thanx for trying anyway :o) :o) :o) -
i have a scrollPane in a frame, and the scrollPane contains JPanels. The first JPanel appears and no scrollbar appears due to the JPanel fitting within the frame size..that's fine. Then upon a JButton click, a second JPanel appears in the first JPanel's place, this time the scrollbar appears because the JPanel size is larger then the frame size.
The problem is that upon JButton click back to the original JPanel the scrollbar stays and the first JPanel resizes to the size of second JPanel? Behaviour should be for the scrollbar to disappear and the original JPanel to use it's original size??
Anyone any ideas?You can try to work with the following methods:
setMaximumSize(Dimension d)
setPreferredSize(Dimension d)
setMinimumSize(Dimension d)
Perhaps it works when you set the first panels maximumsize.
Djamal -
ScrollPane problem - scrollbars not updated after child rescaling
Hi.
Here is a simple application using a ScrollPane to display a large circle. Initially everything looks fine but when you use zoom in and zoom out buttons ScrollPane doesn't update the scrollbars. Scrollbars are only updated after you try to scroll. Even worse - if you zoom out a couple of times, scrollbars dissapear. If you then zoom in again scrollbars will only reappear if you resize the stage main window.
Is there something else I should do in addition to rescaling the circle node?
Thanks for your help.
package test2;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.transform.Scale;
import javafx.stage.Stage;
public class App2 extends Application {
@Override
public void start(Stage stage) throws Exception {
final Scale scale = new Scale(1,1);
final Circle circle = new Circle(100,100,500, Color.BLUEVIOLET);
BorderPane border = new BorderPane();
ScrollPane scroll = new ScrollPane();
circle.getTransforms().add(scale);
scroll.setNode(circle);
Button zoomin = new Button("+");
Button zoomout = new Button("-");
zoomin.onActionProperty().set(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
scale.setX(scale.getX()*2);
scale.setY(scale.getY()*2);
zoomout.onActionProperty().set(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
scale.setX(scale.getX()/2);
scale.setY(scale.getY()/2);
HBox top = new HBox(5);
top.getChildren().addAll(zoomin, zoomout);
border.setTop(top);
border.setCenter(scroll);
Scene s = new Scene(border,500,500);
stage.setScene(s);
stage.setVisible(true);
public static void main(String[] args) {
Application.launch(args);
}Hi,
see this thread maybe you find something helpful.
javafx.scene.Group "auto-size" doesn't work in my case -
Design problem(split pane scrollpane Insets)
hi,
doing a exam simulator prgm
design is like,
Question (text area with scrollpane)
Answers (checkbox inside panel with scrollpane)
used split pane between qst and ans but big thick bar comes how to reduce size and it is not
moving.
used GridLayout for container and panel.
PROBLEM is how to leave space qst textarea appears from very left edge of screen how to leave some space
same prblm for checkbox they to appear extreme left on screen.Put those components in a JPanel overwriting the getInsets() method like this:
JPanel cPane=new JPanel(){
private final Insets _insets=new Insets(10,10,10,10);
public Insets getInsets(){
return _insets;
};...should do the trick, take a look at the Insets class if you need information on how defining it... -
Problem with ScrollPane and JFrame Size
Hi,
The code is workin but after change the size of frame it works CORRECTLY.Please help me why this frame is small an scrollpane doesn't show at the beginning.
Here is the code:
import java.awt.*;
public class canvasExp extends Canvas
private static final long serialVersionUID = 1L;
ImageLoader map=new ImageLoader();
Image img = map.GetImg();
int h, w; // the height and width of this canvas
public void update(Graphics g)
paint(g);
public void paint(Graphics g)
if(img != null)
h = getSize().height;
System.out.println("h:"+h);
w = getSize().width;
System.out.println("w:"+w);
g.drawRect(0,0, w-1, h-1); // Draw border
// System.out.println("Size= "+this.getSize());
g.drawImage(img, 0,0,this.getWidth(),this.getHeight(), this);
int width = img.getWidth(this);
//System.out.println("W: "+width);
int height = img.getHeight(this);
//System.out.println("H: "+height);
if(width != -1 && width != getWidth())
setSize(width, getHeight());
if(height != -1 && height != getHeight())
setSize(getWidth(), height);
}I create frame here...
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
public class frame extends JFrame implements MouseMotionListener,MouseListener
private static final long serialVersionUID = 1L;
private ScrollPane scrollPane;
private int dragStartX;
private int dragStartY;
private int lastX;
private int lastY;
int cordX;
int cordY;
canvasExp canvas;
public frame()
super("test");
canvas = new canvasExp();
canvas.addMouseListener(this);
canvas.addMouseMotionListener(this);
scrollPane = new ScrollPane();
scrollPane.setEnabled(true);
scrollPane.add(canvas);
add(scrollPane);
setSize(300,300);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public void mousePressed(MouseEvent e)
dragStartX = e.getX();
dragStartY = e.getY();
lastX = getX();
lastY = getY();
public void mouseReleased(MouseEvent mouseevent)
public void mouseClicked(MouseEvent e)
cordX = e.getX();
cordY = e.getY();
System.out.println((new StringBuilder()).append(cordX).append(",").append(cordY).toString());
public void mouseEntered(MouseEvent mouseevent)
public void mouseExited(MouseEvent mouseevent)
public void mouseMoved(MouseEvent mouseevent)
public void mouseDragged(MouseEvent e)
if(e.getX() != lastX || e.getY() != lastY)
Point p = scrollPane.getScrollPosition();
p.translate(dragStartX - e.getX(), dragStartY - e.getY());
scrollPane.setScrollPosition(p);
}...and call here
public class main {
public main(){}
public static void main (String args[])
frame f = new frame();
}There is something I couldn't see here.By the way ImageLoader is workin I get the image.
Thank you for your help,please answer me....I'm not going to even attempt to resolve the problem posted. There are other problems with your code that should take priority.
-- class names by convention start with a capital letter.
-- don't use the name of a common class from the standard API for your custom class, not even with a difference of case. It'll come back to bite you.
-- don't mix awt and Swing components in the same GUI. Change your class that extends Canvas to extend JPanel instead, and override paintComponent(...) instead of paint(...).
-- launch your GUI on the EDT by wrapping it in a SwingUtilities.invokeLater or EventQueue.invokeLater.
-- calling setSize(...) followed by pack() is meaningless. Use one or the other.
-- That's not the correct way to display a component in a scroll pane.
Ah, well, and the problem is that when you call pack(), it retrieves the preferredSize of the components in the JFrame, and you haven't set a preferredSize for the scroll pane.
Please, for your own good, take a break from whatever it is you're working on and go through The Java™ Tutorials: [Creating a GUI with JFC/Swing|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]
db -
Problem with drawing in a scrollpane using clipbounds
Hello
Setup is a JFrame containing a splitpane with on the left just some config buttons and on the right a scrollpane.
Inside the scrollpane I want to draw big waveforms.
This is represented by a long array of 1's and 0's for the Y coordinates.
On drawing in paintComponents method I allways reconstruct a GeneralPath, based on the Clipbouns returned by the Graphics variable.
I have to reconstruct the GeneralPath polygon because my data can be millions long. And therefor I have to limit the points that are drawn.
When I allways reconstruct this GeneralPath, upon scrolling the polygon is shown scrappy, as in the line connecting the points will only be half shown or almost not.
Resizing the window or just minimize maximize and it is shown ok.
I do not have this problem when the GeneralPath I construct is only once made upfront and never remade in the paintComponent method.
But as I need the clipbounds to know which part to construct I need to rebuild this polygon over and over again.
I have tried to draw it with Line2D.Double but I get almost the same effect, parts of the lines not being drawn ok.
Below is the code of the Panel inside the ScrollPane responsible for this drawing.
public class Usr_Test_L extends JPanel
final static Color bg = Color.black;
final static Color fg = Color.white;
final static Color wave = Color.red;
final static Color txt = Color.green;
final static Color grid = Color.lightGray;
private static final BasicStroke SOLID = new BasicStroke(1.0f);
private static final BasicStroke BOLD = new BasicStroke(3.0f);
private double maxX = 0.0;
private double maxY = 0.0;
private double gridWidth;
private double gridHeight;
private int panelWidth;
private int panelHeight;
boolean firstTime = true;
private double[] xPoints = null;
private double[] yPoints = null;
GeneralPath polygon;
boolean polyOk = false;
private double waveHeight = 0;
private boolean gridOn = true;
private Usr_Test_R scrollPane = null;
Usr_Test_L(Usr_Test_R scrollPane)
super(true);
this.scrollPane = scrollPane;
buildGui();
void buildGui()
setBackground(bg);
setForeground(fg);
//Let the user scroll by dragging to outside the window.
setAutoscrolls(true); //enable synthetic drag events
// addMouseMotionListener(this); //handle mouse drags
repaint();
private void generateWave(int cycles, double height)
waveHeight = height;
xPoints = new double[cycles];
yPoints = new double[cycles];
Random r = new Random();
for ( int i = 0; i < cycles; i++ )
xPoints[i] = i;
yPoints[i] = (int)( Math.pow(-1.0,i) ) * ( r.nextInt(2) );
// if ( ( i % 10 ) == 0 ) yPoints[i] = height;
// else yPoints[i] = height + gridHeight;
// System.err.println("P"+i+"("+xPoints[i]+","+yPoints[i]+")");
private void generateSineWave(int cycles, double height)
waveHeight = height;
xPoints = new double[cycles];
yPoints = new double[cycles];
double j, xval, yval;
j = 0;
int i = 0;
while (i < cycles)
xval = j;
yval = Math.sin(j) * 10.0 + 20;
xPoints[i] = xval;
yPoints[i] = yval;
i++;
j += 0.01;
public Dimension getPreferredSize() // <== used because of revalidate, parent scrollpane asks preferredsize ..., so we overruled the method
return new Dimension(panelWidth, panelHeight);
public void drawLine(int cycles, int height)
generateWave(cycles,(int)(gridHeight*height));
maxX = gridWidth * cycles;
maxY = gridHeight * cycles;
while ( maxX > panelWidth ) panelWidth *= 2;
while ( maxY > panelHeight ) panelHeight *= 2;
// polyOk = buildPolygon();
revalidate();
repaint();
public void drawSine(int cycles, int height)
generateSineWave(cycles,(int)(gridHeight*height));
maxX = gridWidth * cycles;
maxY = gridHeight * cycles;
while ( maxX > panelWidth ) panelWidth *= 2;
while ( maxY > panelHeight ) panelHeight *= 2;
// polyOk = buildPolygon();
revalidate();
repaint();
public void zoomIn()
gridWidth *= 2;
gridHeight *= 2;
repaint();
public void zoomOut()
gridWidth /= 2;
gridHeight /= 2;
repaint();
private void initPanel()
Dimension d = getSize();
panelWidth = d.width;
panelHeight = d.height;
maxX = panelWidth;
maxY = panelHeight;
gridWidth = panelWidth / 8;
gridHeight = panelHeight / 8;
scrollPane.getHorBar().setUnitIncrement((int)(gridWidth*3)); // times 2 otherwise no clipbounds are allways too small
scrollPane.getHorBar().setBlockIncrement((int)(gridWidth*3));
scrollPane.getVerBar().setUnitIncrement((int)(gridHeight*3));
scrollPane.getVerBar().setBlockIncrement((int)(gridHeight*3));
public void grid()
if ( gridOn ) gridOn = false;
else gridOn = true;
private void drawGrid(Graphics2D g2, Rectangle clip)
if ( ! gridOn ) return;
// draw grid
g2.setPaint(grid);
// new good grid
double startX = clip.getX() + ( gridWidth - ( clip.getX() % gridWidth ) );
double endX = clip.getX() + clip.getWidth();
double startY = clip.getY() + ( gridHeight - ( clip.getY() % gridHeight ) );
double endY = clip.getY() + clip.getHeight();
double y = startY;
while ( startX < endX )
while ( y < endY )
g2.draw(new Rectangle2D.Double( startX - 0.5, y - 0.5, 1.0, 1.0 ));
y += gridHeight;
y = startY;
startX += gridWidth;
private boolean buildPolygon(Rectangle clip)
if ( xPoints != null && yPoints != null )
polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,xPoints.length);
else
return false;
double x = xPoints[0] * gridWidth;
double y = waveHeight;
polygon.moveTo((float)xPoints[0], (float)yPoints[0]);
for ( int index = 0; index < xPoints.length; index++ )
x = xPoints[index] * gridWidth;
y = waveHeight + ( yPoints[index] * gridHeight );
if ( x > ( clip.getX() + clip.getWidth() ) ) break;
if ( y < clip.getY() || y > ( clip.getY() + clip.getHeight() ) ) continue;
if ( x < clip.getX() || x > ( clip.getX() + clip.getWidth() ) ) continue;
polygon.lineTo((float)x, (float)y);
return true;
private boolean drawLines(Graphics2D g2, Rectangle clip)
if ( xPoints == null || yPoints == null ) return false;
double x1 = xPoints[0] * gridWidth;
double y1 = waveHeight;
double x2, y2;
boolean cont = false;
for ( int index = 0; index < xPoints.length; index++ )
x2 = xPoints[index] * gridWidth;
y2 = waveHeight + ( yPoints[index] * gridHeight );
if ( x1 > ( clip.getX() + clip.getWidth() ) )
break;
if ( x2 > ( clip.getX() + clip.getWidth() ) )
break;
if ( y2 < clip.getY() || y2 > ( clip.getY() + clip.getHeight() ) )
cont = true;
if ( x2 < clip.getX() || x2 > ( clip.getX() + clip.getWidth() ) )
cont = true;
if ( ! cont ) g2.draw(new Line2D.Double(x1,y1,x2,y2));
x1 = x2;
y1 = y2;
cont = false;
return true;
public void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if ( firstTime )
initPanel();
firstTime = false;
// get clip bounds
Rectangle clip = new Rectangle();
clip = g2.getClipBounds(clip);
// draw grid
drawGrid(g2,clip);
// draw waveform
g2.setPaint(wave);
g2.setStroke(SOLID);
if ( buildPolygon(clip) ) g2.draw(polygon);
// if ( polyOk ) g2.draw(polygon);
// drawLines(g2,clip);
}I have added a standalone testcase for ease.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.util.*;
public class Scrolling {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(new DrawPanel()));
f.setSize(400,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
class DrawPanel extends JPanel {
private GeneralPath polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
private int[] coords;
public DrawPanel() {
setBackground(Color.white);
buildPolygon();
private void buildPolygon() {
coords = new int[2000];
Random r = new Random();
int height = 80;
int gridHeight = 10;
int gridWidth = 10;
int j = 0;
for (int i=0, dir=-1; i<1000; i++, dir=-dir) {
coords[j++] = i * gridWidth;
coords[j++] = height + dir*gridHeight*r.nextInt(2);
private void drawPolygonClipped(Rectangle clip)
polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
polygon.moveTo(0,80);
for ( int i = 0; i < 2000; i++ )
if ( coords[i] > ( clip.getX() + clip.getWidth() ) ) break;
if ( coords[i+1] < clip.getY() || coords[i+1] > ( clip.getY() + clip.getHeight() ) ) continue;
if ( coords[i] < clip.getX() || coords[i] > ( clip.getX() + clip.getWidth() ) ) continue;
polygon.lineTo(coords[i++],coords);
private void drawPolygon(Rectangle clip)
polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
polygon.moveTo(0,80);
for ( int i = 0; i < 2000; i++ )
polygon.lineTo(coords[i++],coords[i]);
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
Rectangle clip = new Rectangle();
g.getClipBounds(clip);
drawPolygonClipped(clip);
//drawPolygon(clip);
g2.draw(polygon);
public Dimension getPreferredSize() {
return new Dimension(1500,500); -
JTable with ScrollPane update problem
hay i have a table and scrollpane is used as a container, at runtime i create new object of table and assign it to the scrollpane, but its still showing the old table,
I also tried to
updateUI();
repaint();
but it still showing the same old table,
I also debug and saw that the new table has been created n successfuly displaying the values at command prompt.
Can any one know whats wrong in it.Dont be ferious budy, now this is a working example....
Problem is: I am changing the table object in jPanel2 but still jPanel2 is showing the same old table, I think there is a refresh kind of a problem
Be kool dude n tell where is the problem.
package tabletesting;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerAdapter;
public class EmbededTable extends JFrame {
public EmbededTable() {
try {
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
private void jbInit() throws Exception {
flag=1; // flag to alter between objects
getContentPane().setLayout(null);
jPanel1.setBorder(BorderFactory.createEtchedBorder());
jPanel1.setBounds(new Rectangle(28, 11, 320, 76));
jPanel1.setBackground(Color.pink);
jPanel1.setVisible(true);
// jPanel1 contain the buttons when press toggel the table in panel
this.setSize(new Dimension(640, 600));
this.addContainerListener(new EmbededTable_this_containerAdapter(this));
jPanel1.setLayout(null);
jButton1.setBounds(new Rectangle(57, 2, 71, 29));
jButton1.setText("jButton1");
jButton1.addActionListener(new EmbededTable_jButton1_actionAdapter(this));
jPanel2.setBorder(BorderFactory.createEtchedBorder());
jPanel2.setBounds(new Rectangle(22, 133, 578, 304));
jPanel2.addContainerListener(new EmbededTable_jPanel2_containerAdapter(this));
jPanel2.setLayout(borderLayout1);
testTable(); // to initially populate the jPanel2 with the tabel
jButton2.setBounds(new Rectangle(191, 20, 93, 25));
jButton2.setText("jButton2");
jButton2.addActionListener(new EmbededTable_jButton2_actionAdapter(this));
this.getContentPane().add(jPanel1);
jPanel1.add(jButton1, null);
jPanel1.add(jButton2);
this.getContentPane().validate();
this.setVisible(true);
this.show();
public void testTable()
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"Include Input",
"Include Output"};
Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new Boolean(false), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new Boolean(false), new Boolean(true)},
{"Kathy", "Walrath",
"Knitting", new Boolean(false), new Boolean(false)},
{"Sharon", "Zakhour",
"Speed reading", new Boolean(false), new Boolean(true)},
{"Philip", "Milne",
"Pool", new Boolean(false), new Boolean(false)},
if(flag==1)
TableDemo newContentPane = new TableDemo(columnNames,data,4,5);
newContentPane.setOpaque(true); //content panes must be opaque
jPanel2.add(newContentPane, BorderLayout.CENTER);
jPanel2.updateUI();
jPanel2.repaint();
jPanel2.revalidate();
this.getContentPane().add(jPanel2);
flag=0;
else if(flag==0)
Object[][] daa = {
{"A", "T",
"B", new Boolean(false), new Boolean(false)},
{"C", "T",
"Rowing", new Boolean(false), new Boolean(true)},
{"D", "T",
"Knitting", new Boolean(false), new Boolean(false)},
{"E", "T",
"Speed reading", new Boolean(false), new Boolean(true)},
{"F", "T",
"Pool", new Boolean(false), new Boolean(false)},
TableDemo newContentPane = new TableDemo(columnNames,daa,4,5);
newContentPane.setOpaque(true); //content panes must be opaque
this.getContentPane().add(jPanel2);
this.jPanel2.add(newContentPane,BorderLayout.CENTER);
this.jPanel2.updateUI();
jPanel2.repaint();
jPanel2.revalidate();
this.getContentPane().add(jPanel2);
flag=1;
public static void main(String[] args) {
EmbededTable embededtable = new EmbededTable();
JPanel jPanel1 = new JPanel();
static int flag;
JButton jButton1 = new JButton();
JPanel jPanel2 = new JPanel();
JPanel jPanel3 = new JPanel();
BorderLayout borderLayout1 = new BorderLayout();
JButton jButton2 = new JButton();
public void CreateGUI()
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"Include Input",
"Include Output"};
Object[][] data = {
{"A", "Campione",
"B", new Boolean(false), new Boolean(false)},
{"C", "Huml",
"Rowing", new Boolean(false), new Boolean(true)},
{"D", "Walrath",
"Knitting", new Boolean(false), new Boolean(false)},
{"E", "Zakhour",
"Speed reading", new Boolean(false), new Boolean(true)},
{"F", "Milne",
"Pool", new Boolean(false), new Boolean(false)},
//Create and set up the content pane.
TableDemo newContentPane = new TableDemo(columnNames,data,4,5);
newContentPane.setOpaque(true); //content panes must be opaque
jPanel3.setBorder(BorderFactory.createEtchedBorder());
jPanel3.setBounds(new Rectangle(22, 133, 578, 304));
jPanel3.setLayout(borderLayout1);
// this.getContentPane().remove(jPanel2);
this.getContentPane().add(jPanel3);
this.jPanel3.add(newContentPane,BorderLayout.CENTER);
this.jPanel3.updateUI();
this.validate();
public void jButton1_actionPerformed(ActionEvent e) {
CreateGUI();
public void jButton2_actionPerformed(ActionEvent e) {
testTable();
public void this_componentAdded(ContainerEvent e) {
public void jPanel2_componentRemoved(ContainerEvent e) {
System.out.println(" component removed");
public void jPanel2_componentAdded(ContainerEvent e) {
System.out.println(" component added");
class EmbededTable_jPanel2_containerAdapter extends ContainerAdapter {
private EmbededTable adaptee;
EmbededTable_jPanel2_containerAdapter(EmbededTable adaptee) {
this.adaptee = adaptee;
public void componentRemoved(ContainerEvent e) {
adaptee.jPanel2_componentRemoved(e);
public void componentAdded(ContainerEvent e) {
adaptee.jPanel2_componentAdded(e);
class EmbededTable_this_containerAdapter extends ContainerAdapter {
private EmbededTable adaptee;
EmbededTable_this_containerAdapter(EmbededTable adaptee) {
this.adaptee = adaptee;
public void componentAdded(ContainerEvent e) {
adaptee.this_componentAdded(e);
class EmbededTable_jButton2_actionAdapter implements ActionListener {
private EmbededTable adaptee;
EmbededTable_jButton2_actionAdapter(EmbededTable adaptee) {
this.adaptee = adaptee;
public void actionPerformed(ActionEvent e) {
adaptee.jButton2_actionPerformed(e);
class EmbededTable_jButton1_actionAdapter implements ActionListener {
private EmbededTable adaptee;
EmbededTable_jButton1_actionAdapter(EmbededTable adaptee) {
this.adaptee = adaptee;
public void actionPerformed(ActionEvent e) {
adaptee.jButton1_actionPerformed(e);
TabelDemo class
public class TableDemo extends JPanel {
private boolean DEBUG = false;
public TableDemo(String[] c, Object[][] d,int col,int row) {
super(new GridLayout(1, 0));
JTable table = new JTable(new MyTableModel(c,d,4,5));
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
Object obj=table.getValueAt(0,1);
table.updateUI();
JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().setView(table);
Object ob= table.getValueAt(0,0);
System.out.println(" ob " + ob.toString());
scrollPane.updateUI();
scrollPane.getViewport().revalidate();
scrollPane.getViewport().updateUI();
add(scrollPane);
this.updateUI();
this.revalidate();
super.repaint();
super.validate();
Tabel class
public class MyTableModel extends AbstractTableModel {
boolean DEBUG= false;
public String[] columnNames ;
public String[] str; // to verify only one output variable
Boolean fal= new Boolean(false);
public Object[][] data;
MyTableModel()
MyTableModel(String[] col, Object[][] dat, int lenRow, int lenCol)
data=dat;
columnNames=col;
str= new String[col.length];
funcopy(str,lenRow);
void funcopy(String[] str, int lenRow)
for(int i=0;i<lenRow;i++)
str=fal.toString();
for(int i=0;i<str.length;i++)
System.out.println("values are " + str[i]);
public int getColumnCount() {
return columnNames.length;
public int getRowCount() {
return data.length;
public String getColumnName(int col) {
return columnNames[col];
public Object getValueAt(int row, int col) {
return data[row][col];
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
System.out.println("row " + row + "col " + col + value.toString());
Object obj= getValueAt(row,col);
if(col==3) // column 3 is the output column.
if(value.toString().equals("true"))
int savepointer=row;
int flag=-1;
for(int i=0;i<str.length;i++)
if(str[i].toString().equalsIgnoreCase("true"))
flag=1;
if(flag!=1)
System.out.println("inside flag ==1");
data[row][col]=value;
str[row]=value.toString();
fireTableCellUpdated(row, col);
if(value.toString().equals("false"))
data[row][col]=value;
str[row]=value.toString();
fireTableCellUpdated(row, col);
}// id col ends...
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
System.out.println();
System.out.println("--------------------------"); -
ScrollPane + Dynamic text problem.
Hi,
I use the ScrollPane component to display a movieclip which contains some text. Until now I have entered just a few paragraphs, with the text field set to "Static text"...but as I have wrote some more I noticed that the text field displays only half of my text. So I have switched to "Dynamic text", which solves the display issue and I get 100% of my text but now I have it always on the scene displayed, even if it is only available in the library...strange!
Could somone help me out please??
Regards,
vedtamOk, I try to make my self clear.
I have to display a really long text on this website. By default when I am typing anything the Text tool is set to "Static text" in that little drop down in the Text Properties window. So I have moved on whit this, but after more then 50-60 paragraph typed in I get only 30 displayed. Than I went to that little drop down and selected "Dynamic text" to see if this helps, and when I have tested the movie again the text was displayed with all its 60 paragraph, but it was overlapping all my other content without pressing its button (without calling it).
The movieclip which contains the text, sits in the library, and the ScrollPane component (which loads it externally) is in the scene on the 1st frame. Again, as I test the movie I get the text showing up in the background, so as I click any menu item it is overlapping any other content.
What I would like to achieve is to have the text displayed without an issue (not only a half of it). But this task is failed by the "Static text" option and setting it to "dynamic text" solves the first problem while rises a second (the sudden appearance of the text on the scene without calling it).
I hope this second explanation helps,
Vedtam -
Hi All
Let me explain the problem to u guys..
I have a dialog whose contentPane is set to BorderLayout.A scrollPane is added to this dialog.Next a Panel is added to this ScrollPane and the panel is having a gridbaglayout.Some components are added to this Panel is rows and columns dynamically,everytime new components need to be added the old components are removed using removeAll.The scrollPane is having VERTICAL_SCROLLBAR_AS_NEEDED and HORIZONTAL_SCROLLBAR_NEVER (The component is given a fixed prefferedSize,MaximumSize and Minimum size).The problem is I am not getting to view all the components widthwise,vertically its OK since I have a scrollBar.I want all the compnents in the row to be displayed within the viewport area.
Is it bcoz of fixed preferredSize,maximumsize and minimum size of componets that i am not getting to view them fully?Please give me a solution as to how i can solve the problem
regards
OliverI would suspect the gridbag layout. If you add a horizontal scrollbar (just to find out what's going on), can you see all the components? Maybe you can post some code for us to look at. . .
-
Hi,
I'm sure there's a pretty simple solution for this. I've got
a scrollpane and some graphical content in the scroll pane. I want
to print the graphical content in the scrollpane. This content
resides on a single movieclip. The problem is that when I print
either just the scrollpane or just the content movieclip I only get
what is currently visible on the screen in the scollpane as output.
The rest of the movie clip being masked by the scrollpane itself
doesn't print. Below is code very similar to what I'm doing. Any
help would be appreciated!
Thanks!
var myPrint = new PrintJob();
myResult = myPrint.start();
if (myResult) {
myResult = myPrint.addPage("myMovie", {xMin:
0,xMax:800,yMin:0,yMax:800}), {printAsBitmap:true},1);
myResult = myPrint.addPage("myMovie", {xMin:
800,xMax:1600,yMin:0,yMax:800}), {printAsBitmap:true},2);
myResult = myPrint.adPage(1,null,{printAsBitmap:true},3);
myPrint.sent();
delete.myPrint;As you are using Box Layout for your panel.
so you need to set box property like where in the panel it will appear like left,right south,north etc.
You may know that we can have multiple boxes in a panel.
After setting the box level on the panel,set the label's position on the box,
add like panel.ad(BoxLayout.SOUTH,label1)
By this you can place labels as desirable positions.
also you can have a look on the panel and labels view in swing
Visit : http://java.sun.com/docs/books/tutorial/uiswing/components/panel.html -
Flicker Problems with a dynamic Canvas and scrollpane
Hello all,
I'm having some trouble with flickering in a dynamically sizing canvas. Basically I have a new component similar to a text area implemented as a canvas. I put this canvas into a scrollpane and it is updated when a new message comes in. problem occurs both when a new msg comes in and when the scrollbar is used. I get heavy flickering in the component area and no where else. I've tried double buffering, I've looked through some of the old topic threads here and tried a few suggestions but it still occurs. I traced the paint/update calls with printlns into the console and found that only the paint gets called and not the update. I'm thinking that the changing height of the canvas is automatically calling the paint method directly. Any and all help (that works) will be rewarded with duke dollars. I really need help on this one. Below is a cut away of the code:
CANVAS COMPONENT
public class IconBox extends Canvas {
//other methods to handle text processing
public void append(String text)
//places text into a vector and calls repaint to add it to
//the canvas and updates the height of the canvas
public void update (Graphics g)
paint(g);
public void paint(Graphics g)
// I basically refresh the canvas with new text updates
// here with g,drawtexts and add a few images with
// drawimage
APPLET
public class ConfDraw extends Applet implements ComponentListener
newTextarea lC;
ScrollPane appletScroller
public void init()
lC = new IconBox(427);
lC.addComponentListener(this);
appletScroller = new ScrollPane(1);
appletScroller.add(lC,0);
appletScroller.setSize( 445, 380 );
public void componentResized(ComponentEvent e) {
appletScroller.doLayout();
public void componentHidden(ComponentEvent e) {
public void componentMoved(ComponentEvent e) {
public void componentShown(ComponentEvent e) {
// other methods that send text to IC
public void update(Graphics g)
//tried with and without this over ride at this level
paint(g);
}Create offscreen image & graphics
eg.
Image offscreenImg = createImage(w, this.size().height);
Graphics offscreenG = offscreenImg.getGraphics();paint all ur contents on off screen grpahics.
eg.
offscreenG.drawString("Hello", 10, 10);finally paint the off-screen image to the Graphics
g.drawImage(offscreenImg,0,0,this);This will avoid flickering as whole of the image is replaced at once. Also override update. -
Problem adding a table to scrollpane
Hi:
I have created a JTable that I want to be in a scrollpane. When I tried to add this JTable to a scrollpane I get a null pointer error at execution time. But when I add this table directly to the frame I get no error at execution time.
Here is my code:
import java.awt.*;
import java.awt.event .*;
import javax.swing.*;
import java.util.*;
import javax.swing.event.*;
import java.io.*;
import javax.swing.table.*;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import java.net.*;
import java.util.regex.*;
// METHODS
// =======
// private String returnSelectedString( int col ))
public class DialogFrame extends JFrame
{ //===================
//MEMBER VARIABLES
//===================
public JLabel topClassifiedLabel, bottomClassifiedLabel,printerCountLabel,defaultPrinterLabel ;
public JPanel panelForLabel,topClassificationPanel , bottomClassificationPanel, SecBotPanel, ClassificationPanel,Classification_botPanel,firstTopPanel, titlePanel,titlePanel2,displayPanel,labelPanel,buttonPanel;
public DefaultListModel listModel;
public final String screenTitle = "Printer Configuration "
+ " CSS - 105";
public JLabel localDisplay = new JLabel("Local: Printer directly connected to this computer");
public JLabel remoteDisplay = new JLabel("Remote: Printer connected to another computer");
public JLabel networkDisplay = new JLabel("Network: Printer connected to the LAN");
public char hotKeys[] = { 'A', 'D', 'Q','T','R','I','Q','H' };
public JPanel ConnectTypePanel = null, printCountPanel;
public JScrollPane tabScrollPane;
public JLabel l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12,TitleLabel;
public JButton addPrinterButton,setDefaultButton,restartPrintSystemButton, deletePrinterButton, displayQueueButton,
ToggleBannerButton, RestartPrintSystemButton, InstallOpenPrintButton, QuitButton, continueButton,CancelButton,HelpButton;
public Vector columnNames;
public String line2 = "";
public addPrinterDialog aPDialog;
public printQueueDialog dQDialog;
public String nextElement,name,Type,Interface,Description,Status,Queue,BannerPage;
public JRadioButton networkButton, localButton, remoteButton;
public JLabel nameLabel, descriptionLabel, modelLabel,ClassificationLabel,ClassificationLabel_bot,setL,defaultL;
public JTextField nameTextField, descriptionTextField, modelTextField;
private int printerCount = 0;
static DefaultTableModel model;
public JTable table;
//=======================//
//**Constructor
//=========================//
public DialogFrame()
createTable();
public void createTable()
defaultPrinterLabel = new JLabel();
printerCountLabel = new JLabel();
//COLUMN FOR TABLE
columnNames = new Vector();
columnNames.add("Name");
columnNames.add("Type");
columnNames.add("Interface");
columnNames.add("Description");
columnNames.add("Status");
columnNames.add("Queue");
columnNames.add("BannerPage");
Vector tableRow = new Vector();
//tableRow = executeScript("perl garb.pl");
// tableRow = executeScript("perl c:\\textx.pl");
model = new DefaultTableModel( tableRow, columnNames ){
public boolean isCellEditable(int row,int col) {
return false;
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
table = new JTable(model);
JTableHeader header = table.getTableHeader();
TableColumnModel colmod = table.getColumnModel();
for (int i=0; i < table.getColumnCount(); i++)
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setHorizontalAlignment(SwingConstants.CENTER);
colmod.getColumn(i).setCellRenderer(renderer);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setShowGrid( false );
table.getTableHeader().setReorderingAllowed( false );
table.setIntercellSpacing(new Dimension(0,0) );
table.addMouseListener( new MouseAdapter () {
public void mouseClicked( MouseEvent e) {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) !=0)
printSelectCell(table);
this.setSize(900,900);
//========================================//
// Technique for centering a frame on the screen
//===========================================//
Dimension frameSize = this.getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation((screenSize.width - frameSize.width)/2,
(screenSize.height - frameSize.height)/2);
setResizable(false);
// CREATE A FEW PANELS
firstTopPanel = new JPanel();
BoxLayout box = new BoxLayout(firstTopPanel, BoxLayout.Y_AXIS);
firstTopPanel.setLayout(box);
topClassificationPanel = new JPanel();
topClassificationPanel.setBackground(new Color(45,145,71));
bottomClassificationPanel = new JPanel();
bottomClassificationPanel.setBackground(new Color(45,145,71));
SecBotPanel = new JPanel();
SecBotPanel.setLayout(new BorderLayout());
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,8));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 0));
buttonPanel.setBackground(new Color(170,187,119));
panelForLabel = new JPanel();
// panelForLabel.setBackground( Color.white );
//Border etchedBorder = BorderFactory.createEtchedBorder();
printerCountLabel.setHorizontalAlignment(SwingConstants.LEFT);
printerCountLabel.setPreferredSize(new Dimension(700, 20));
//printerCountLabel.setBorder(etchedBorder);
printerCountLabel.setForeground(Color.black);
defaultPrinterLabel.setHorizontalAlignment(SwingConstants.RIGHT);
defaultPrinterLabel.setText("Default Printer: " + name);
defaultPrinterLabel.setForeground(Color.black);
panelForLabel.add(printerCountLabel);
panelForLabel.add(defaultPrinterLabel);
titlePanel = new JPanel( );
titlePanel.setBackground( Color.white );
ConnectTypePanel = new JPanel();
ConnectTypePanel.setBackground(new Color(219,223,224));
ConnectTypePanel.setLayout( new GridLayout(3,1) );
//CREATE A FEW LABELS
topClassifiedLabel = new JLabel("UNCLASSIFIED", SwingConstants.CENTER );
topClassifiedLabel.setForeground(Color.white);
bottomClassifiedLabel = new JLabel("UNCLASSIFIED", SwingConstants.CENTER );
bottomClassifiedLabel.setForeground(Color.white);
TitleLabel = new JLabel( screenTitle, SwingConstants.CENTER );
//ADD LABELS TO PANELS
topClassificationPanel.add( topClassifiedLabel );
bottomClassificationPanel.add( bottomClassifiedLabel );
titlePanel.add( TitleLabel, BorderLayout.CENTER );
ConnectTypePanel.add(localDisplay );
ConnectTypePanel.add(remoteDisplay );
ConnectTypePanel.add(networkDisplay );
//Create the scrollpane and add the table to it.
tabScrollPane = new JScrollPane(table);
JPanel ps = new JPanel();
ps.add(tabScrollPane);
getContentPane().setLayout(
new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ) );
getContentPane().add(firstTopPanel);
getContentPane().add(panelForLabel);
getContentPane().add(header);
getContentPane().add(ps);//contain table
getContentPane().add(SecBotPanel);
WindowListener w = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
DialogFrame.this.dispose();
System.exit(0);
this.addWindowListener(w);
//==================================//
// AddPrinterButton
//==================================//
addPrinterButton = new JButton();
addPrinterButton.setLayout(new GridLayout(2, 1));
l1 = new JLabel("Add", JLabel.CENTER);
l1.setForeground(Color.black);
l2 = new JLabel("Printer", JLabel.CENTER);
l2.setForeground(Color.black);
addPrinterButton.add(l1);
addPrinterButton.add(l2);
addPrinterButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
//(aPDialog == null) // first time
aPDialog = new addPrinterDialog(DialogFrame.this);
aPDialog.setLocationRelativeTo(null);
aPDialog.pack();
aPDialog.show(); // pop up dialog
//======================================
// DeletePrinterButton
//=====================================
deletePrinterButton = new JButton();
deletePrinterButton.setLayout(new GridLayout(2, 1));
l1 = new JLabel("Delete", JLabel.CENTER);
l1.setForeground(Color.black);
l2 = new JLabel("Printer", JLabel.CENTER);
l2.setForeground(Color.black);
deletePrinterButton.add(l1);
deletePrinterButton.add(l2);
deletePrinterButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
int sr = table.getSelectedRow();
if (sr == -1)
JOptionPane.showMessageDialog(null, "You have not selected a printer for this operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
else
name = returnSelectedString(0);
int ans = JOptionPane.showConfirmDialog(null,"Are you sure you want to delete printer " + name + "?","Delete",JOptionPane.YES_NO_OPTION);
switch(ans) {
case JOptionPane.NO_OPTION:
return;
case JOptionPane.YES_OPTION:
// String machineName = returnSelectedString(0);
int rowNumber = table.getSelectedRow();
model.removeRow(rowNumber);
//TiCutil.exe("/usr/lib/lpadmin -x " + machineName);
decreasePrinterCount();
JOptionPane.showMessageDialog(null, "Printer " + name + " have been successfully deleted","SUCCEED",JOptionPane.INFORMATION_MESSAGE);
return;
//==============================//
//DisplayQueuePrinter //
//================================//
displayQueueButton = new JButton();
displayQueueButton.setLayout(new GridLayout(2, 1));
l5 = new JLabel("Display", JLabel.CENTER);
l5.setForeground(Color.black);
l6 = new JLabel("Queue", JLabel.CENTER);
l6.setForeground(Color.black);
displayQueueButton.add(l5);
displayQueueButton.add(l6);
displayQueueButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
Vector tab = new Vector();
int sr = table.getSelectedRow();
if (sr == -1)
JOptionPane.showMessageDialog(null, "You have not selected a printer for this" +
"operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
else
name = returnSelectedString(0);
//PASS TABLE HERE
/*tab = executeScript("lpstat -o " + name + " | sed \'s/ on$//\'");
System.out.println("lpstat -o " + name + " | sed \'s/ on$//\'");
dQDialog = new printQueueDialog(DialogFrame.this, name, tab);
dQDialog.setLocationRelativeTo(null);
dQDialog.pack();
dQDialog.show(); // pop up dialog */
//===================================
// SetDefaultButton
//================================//
setDefaultButton = new JButton();
setDefaultButton.setLayout(new GridLayout(2, 1));
setL = new JLabel("Set", JLabel.CENTER);
setL.setForeground(Color.black);
defaultL = new JLabel("Default", JLabel.CENTER);
defaultL.setForeground(Color.black);
setDefaultButton.add(setL);
setDefaultButton.add(defaultL);
setDefaultButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
int sr = table.getSelectedRow();
if (sr == -1)
JOptionPane.showMessageDialog(null, "You have not selected a printer for this operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
else
name = returnSelectedString(0);
JOptionPane.showMessageDialog(null, "printer " + name + " is now the default.","Succeed",JOptionPane.INFORMATION_MESSAGE);
defaultPrinterLabel.setText("Default Printer: " + name);
//==============================//
// ToggleBannerButton
//==============================//
ToggleBannerButton = new JButton();
ToggleBannerButton.setLayout(new GridLayout(2, 1));
l7 = new JLabel("Toggle", JLabel.CENTER);
l7.setForeground(Color.black);
l8 = new JLabel("Banner", JLabel.CENTER);
l8.setForeground(Color.black);
ToggleBannerButton.add(l7);
ToggleBannerButton.add(l8);
ToggleBannerButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
int sr = table.getSelectedRow();
System.out.println("sr :" + sr);
if (sr == -1)
JOptionPane.showMessageDialog(null, "You have not selected a printer for this operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
else
String banner = returnSelectedString(6);
name = returnSelectedString(0);
String machineName = returnSelectedString(0);
Type = returnSelectedString(1);
if ( !(Type.equals("Remote")) )
if( banner.equals("Yes") )
JOptionPane.showMessageDialog(null,"Banner page will NOT be printed for printer "+ name ,"Succeed",JOptionPane.INFORMATION_MESSAGE);
//TiCutil.exe("sed -e 's/^BANNER=\"yes\"/BANNER=\"\"/' /etc/lp/interfaces/" + machineName + " > /tmp/delete.txt" );
//TiCutil.exe("mv /tmp/delete.txt /etc/lp/interfaces/" + machineName);
table.setValueAt("No",sr,6);
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.fireTableCellUpdated(sr,6);
table.requestFocus();
else
JOptionPane.showMessageDialog(null,"Banner page WILL be printed for printer "+ name ,"Succeed",JOptionPane.INFORMATION_MESSAGE);
//TiCutil.exe("sed -e 's/^BANNER=\"\"/BANNER=\"yes\"/' /etc/lp/interfaces/" + machineName + " > /tmp/delete.txt");
//TiCutil.exe("mv /tmp/delete.txt /etc/lp/interfaces/" + machineName);
table.setValueAt("Yes",sr,6);
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.fireTableCellUpdated(sr,6);
table.requestFocus();
else
JOptionPane.showMessageDialog(null,"Operation failed system respond \n" + "was:\n" + "cannot toggle the banner page for a\n" + "REMOTE printer." ,"OPFAIL",JOptionPane.INFORMATION_MESSAGE);
//==================================//
// RestartPrintSystemButton
//==================================//
restartPrintSystemButton = new JButton();
restartPrintSystemButton.setLayout(new GridLayout(2, 1));
l3 = new JLabel("Restart Print", JLabel.CENTER);
l3.setForeground(Color.black);
l4 = new JLabel("System", JLabel.CENTER);
l4.setForeground(Color.black);
restartPrintSystemButton.add(l3);
restartPrintSystemButton.add(l4);
restartPrintSystemButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
//==============================
// InstallOpenPrint
//================================
InstallOpenPrintButton = new JButton();
InstallOpenPrintButton.setLayout(new GridLayout(2, 1));
l11 = new JLabel("Install Open", JLabel.CENTER);
l11.setForeground(Color.black);
l12 = new JLabel("Print", JLabel.CENTER);
l12.setForeground(Color.black);
InstallOpenPrintButton.add(l11);
InstallOpenPrintButton.add(l12);
InstallOpenPrintButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
int ans = JOptionPane.showConfirmDialog(null,"Are you sure you want to install OPENPrint?","Delete",JOptionPane.YES_NO_OPTION);
switch(ans) {
case JOptionPane.NO_OPTION:
return;
case JOptionPane.YES_OPTION:
int cd,opinstall,banner_var,pwd;
opinstall = runIt("open_print.ksh");
banner_var = runIt("banner_var.ksh");
System.out.println("opinstall: " + opinstall );
System.out.println("banner_var: " + banner_var);
if ( opinstall == 0 && banner_var == 0)
JOptionPane.showMessageDialog(null, "OPENprint successfully added"
,"SUCCEED",JOptionPane.INFORMATION_MESSAGE);
return;
//==========================
//QuitButton
//============================
QuitButton = new JButton("Quit");
QuitButton.addActionListener (new ActionListener ()
{ public void actionPerformed (ActionEvent e){
System.exit (0); }
HelpButton = new JButton("Help");
//ADD BUTTONS TO PANEL
buttonPanel.add( addPrinterButton );
buttonPanel.add( deletePrinterButton );
buttonPanel.add( displayQueueButton );
buttonPanel.add( setDefaultButton);
buttonPanel.add( ToggleBannerButton );
buttonPanel.add( restartPrintSystemButton );
buttonPanel.add( InstallOpenPrintButton );
buttonPanel.add( QuitButton );
//buttonPanel.add( HelpButton );
//END OF BUTTONS CREATION
//ADD PANEL ON TO PANEL
SecBotPanel.add(ConnectTypePanel, BorderLayout.CENTER);
SecBotPanel.add(bottomClassificationPanel, BorderLayout.SOUTH);
firstTopPanel.add(topClassificationPanel);
firstTopPanel.add(titlePanel);
firstTopPanel.add(buttonPanel);
//===========================================================
// METHODS
//==========================================================
public int runIt(String targetCode)
int result = -1;
try{
Runtime rt = Runtime.getRuntime();
Process p = rt.exec( targetCode );
// Thread.sleep(20000);
p.waitFor();
result = p.exitValue();
catch( IOException ioe )
ioe.printStackTrace();
catch( InterruptedException ie )
ie.printStackTrace();
return result;
//====================================================
public void increasePrinterCount()
printerCount++;
printerCountLabel.setText("Printer: " + printerCount);
//===========================================================
public void decreasePrinterCount()
printerCount--;
printerCountLabel.setText("Printer: " + printerCount);
private String returnSelectedString( int col )
int row = table.getSelectedRow();
String word;
//javax.swing.table.TableModel model = table.getModel();
word =(String)model.getValueAt(row, col);
return word; //return string
//==============================================================================
private Vector executeScript(String str)
Vector tableOfVectors = new Vector();
try{
String line;
Process ls_proc = Runtime.getRuntime().exec(str);
//get its output (your input) stream
BufferedReader in = new BufferedReader( new InputStreamReader( ls_proc.getInputStream() ));
//readLine reads in one line of text
int k = 1, i = 0;
//LOOK FOR THE "|"
Pattern p = Pattern.compile(" ");
while (( line = in.readLine()) != null)
Vector data = new Vector();
Matcher m = p.matcher(line);
if(m.find() == true)//find " "
line = line.replaceAll(" {2,}?", "|");
//creates a new vector for each new line read in
StringTokenizer t = new StringTokenizer(line,"|");
while ( t.hasMoreTokens() )
try
nextElement = t.nextToken().trim();
//add a string to a vector
data.add(nextElement.trim());
catch(java.util.NoSuchElementException nsx)
System.out.println(nsx);
tableOfVectors.add(data);
//COUNT THE NUMBER OF PRINTER
printerCount = k;
printerCountLabel.setText("Printer: " + printerCount);
k++;
}//END OF WHILE
in.close();
}//END OF TRY
catch (IOException e1) {
System.err.println(e1);
System.exit(1);
return tableOfVectors;
//==========================================================================================================
private String getDefaultPrinter(String str)
String groupStr = null;
try{
String lin;
Process ls_proc = Runtime.getRuntime().exec(str);
BufferedReader in = new BufferedReader( new InputStreamReader( ls_proc.getInputStream() ));
Pattern p2 = Pattern.compile("system default destination: (\\S+)");
while (( lin = in.readLine()) != null)
Matcher m2 = p2.matcher(lin);
m2.reset(lin);
if (m2.find() == true )
groupStr = m2.group(1);
in.close();
catch (IOException e1) {
System.err.println(e1);
System.exit(1);
return groupStr;
//================================================================================
public synchronized void clearTable()
int numrows = model.getRowCount();
for ( int i = numrows -1 ; i >= 0 ; i--)
model.removeRow(i);
//=======================================================================================================
private void printSelectCell(JTable table )
int numCols = table.getColumnCount();
int row = table.getSelectedRow();
System.out.println(row);
javax.swing.table.TableModel model = table.getModel();
for(int j=0;j < numCols; j++)
System.out.println(" " + model.getValueAt(row,j));
System.out.println();
System.out.println("-----------------------------------------------");
//CREATE ADD PRINTER DIALOG
class addPrinterDialog extends JDialog
public addPrinterDialog(JFrame owner)
super(owner, "ap1", true);
final ButtonGroup rbg = new ButtonGroup();
JPaneOk I have the table on the page I created a css with a background image called .search How to I link that to the table so It shows the image
I am only used to doing certain css items Never didi this before
THXS STeve -
Problem of JSplitPane with ScrollPane
Does JSplitPane work with ScrollPane?i am writing 2 ScrollPanes in a JSplitPane,but i can not move the bound.Thanks!
It might be a little too late but I will put my 2 cents anyway...
There is a scenario where mixing ScrollPane and JSplitPane is needed (unless you create your own AWTSplitPane): when you need to contain a heavyweight component (AWT) with a ScrollPane, you cannot use JScrollPane, that's for sure.
The JSplitPane does not work because the minimumSize of the ScrollPane is set to its size and therefore JSplitPane won't reduce the component under its minimum size. The solution is to extend ScrollPane and override getMinimumSize method to whatever minimum size you decide.
Maybe you are looking for
-
Problems in selecting an image and scaling it.Image is selected using JFile
Hello All, I need to select a file using JFilechooser and scale it down and display it on the frame. This never happens.I dont know why.Please help me with this. Thanks. Regards. NP package loadpic; * <p>Title: </p> * <p>Description: </p> * <p>Copyri
-
Report - Status of a specific advertisement showing 900 resources when only deployed to 100
we have a strange problem where we run the "Status of a specific advertisment" is showing some bogus data. We deployed to a collection containing 100 PCs and the report for that collection ID shows: Accepted = 300 Rejected = 5 No Status = 600 I found
-
Database - information lost after saving and closing.
I have a very simple database. Two text fields and a date field. There are 146 records. Each text field occasionally contains a lot of characters (isn't 255 the max.?) If a create another record, put in a date and some text in each text field, then s
-
Hello, The codes below works fine from a stand alone ABAP program. TYPES: BEGIN OF v_level_text, level type /BI0/HPROD_HIER-tlevel, text type /BI0/TPROD_HIER-txtlg, END OF v_level_text. DATA: i_level_text type tabl
-
How to add ineligible tracks to my iPhone?
So I have some spoken word tracks that I would like to add to my iphone but they are ineligible for iCloud for either the 64 kbs encode rate or the the file size being 30 + MB. I really would prefer not to have to re-encode the files. With Itunes M