Swing/JScrollPane

My problem is that I have this class that extends JApplet and has 3 JPanel and an instance from another class that extends JPanel (I will call it class2) inside it.
My problem is that I'm inserting class2 inside a JScrollPane than I insert JScrollPane inside my JApplet, but whenever I move my JScrollPane which should just move the content from class2 (lines, numbers, ...), but I'm getting a messed screen like if the computer was mixing the old content (before using JScrollPane) with the new content (after moving)...something like the JScrollPane listener isnt refreshing the screen when I use it.
If anyone know a fix for this, please contact me and if you want to check the code, email me ([email protected]).

I'm posting all the code below...could anyone please help me out with this, there is a very weird behaviour when I move the JScrollPane
* C�digo de Huffman - Applet
* Arildo Fran�a Oliva Filho - 99/32810
* Leonardo Lobo Pulcineli - 99/20064
* Marcos Garrison Dytz - 99/20102
* Octavio do Vale Rocha - 99/20129
package huffman;
// Bibliotecas que fazem parte da implementa��o do applet
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
import java.text.DecimalFormat;
* Objetos que far�o parte da GUI do programa, onde se tem a ocorrencia de
* tres botoes para o controle do fluxo do programa, uma caixa para a entrada
* das probabilidades, um classe instanciada para controlar as mensagens ao
* usu�rio e outra que far� a apresenta��o de todo conte�do
* Declara��o de todas as vari�veis utilizadas para armazenar as probabilidades
* onde o maior n�mero de vari�ives que podem ser implementadas � 200
public class Huff extends JApplet implements ActionListener, ComponentListener {
JButton reset_button, step_button, end_button;
// JButton file_button, fix_button;
JTextField input_string;
cent Cent = new cent();
ErrorCanvas stdout = new ErrorCanvas();
DecimalFormat f = new DecimalFormat("0.000"); // Define um formato para os valores
DecimalFormat f2 = new DecimalFormat("0.00");
JScrollPane scroll = new JScrollPane(Cent);
boolean inAnApplet = true; // Testa a validade do applet
protected int numProbabilidade; // Numero total de probabilidades
protected int numProbabilidadeTemp; // Numero total de probabilidades
protected int[] marcador; // Marca a pr�xima probabilidade
protected double[][] probabilidade;
protected String[][] simbolo; // Guarda os c�digos bin�rios
protected int passo; // Controle quanto ao fim das probs.
protected boolean proximo = true; // Idem acima
protected double entropia = 0.0; // Entropia;
// protected boolean estArquivo = true; // Estado de um arquivo
protected boolean inic = true;
* Construtor para a classe Huff (inicializa todo o GUI)
public Huff() {
getContentPane().setLayout(new BorderLayout());
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
getContentPane().add("Center", scroll);
Font def = new Font("Dialog", 0, 12);
Cent.setFont(def);
JPanel p = new JPanel(new GridLayout(2, 0));
JPanel q = new JPanel(new GridLayout(2, 0));
JPanel r = new JPanel(new FlowLayout());
r.add(reset_button = new JButton("Reiniciar"));
r.add(step_button = new JButton("Proximo"));
r.add(end_button = new JButton("Concluir"));
// r.add(file_button = new JButton("Arquivo");
// r.add(file_button = new JButton("Corrigir arquivo");
p.add(r);
p.add(input_string = new JTextField());
* O visualizador gr�fico (JPanel q) que � utilizado por ErrorCanvas para
* emitir algumas mensagens para o usu�rio
q.add(p);
q.add(stdout);
getContentPane().add("South", q);
reset_button.addActionListener(this);
step_button.addActionListener(this);
end_button.addActionListener(this);
input_string.addActionListener(this);
scroll.addComponentListener(this);
* M�todo utilizado para inicializar o �ndice dos arrays utilizados e zerar
* o valor de todas as probabilidades utilizadas
public void init() {
marcador = new int[200];
probabilidade = new double[200][400];
simbolo = new String[200][250];
for(int i = 0; i < 200; i++)
for(int j = 0; j < 400; j++) {
probabilidade[i][j]=0.0;
JOptionPane.showMessageDialog(null, " ", "Bem vindo",
JOptionPane.INFORMATION_MESSAGE);
if(inic)
iniciarProbabilidade(probabilidade[0]);
this.reset();
* Conta o n�mero de probabilidades que foram inseridos no TextField, assim
* como testa a validade destes valores. � bem similar ao funcionamento de
* parseProbabilidade
void contarProbabilidade() {
StringTokenizer st = new StringTokenizer(input_string.getText());
double teste = 0.0;
if(input_string.getText().length() > 0 && input_string.getText() != null) {
while (st.hasMoreTokens()) {
try {
teste = Double.valueOf(st.nextToken()).doubleValue();
if(teste < 0) {
JOptionPane.showMessageDialog(null,"Probabilidade negativa.", "Erro",
JOptionPane.ERROR_MESSAGE);
input_string.setText("");
numProbabilidade = 0;
break;
if(teste > 1.0) {
JOptionPane.showMessageDialog(null,"Probabilidade maior que 1.", "Erro",
JOptionPane.ERROR_MESSAGE);
input_string.setText("");
numProbabilidade = 0;
break;
if(teste == 0.0) {
JOptionPane.showMessageDialog(null,"Probabilidade igual a 0.", "Erro",
JOptionPane.ERROR_MESSAGE);
input_string.setText("");
numProbabilidade = 0;
break;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null,"Numero incorreto.", "Erro",
JOptionPane.ERROR_MESSAGE);
input_string.setText("");
numProbabilidade = 0;
break;
numProbabilidade++;
if(numProbabilidade > 200 && st.hasMoreTokens()) {
JOptionPane.showMessageDialog(null,"S�o permitidos at� 200 probabilidades",
"Erro", JOptionPane.ERROR_MESSAGE);
input_string.setText("");
numProbabilidade = 0;
break;
} else
JOptionPane.showMessageDialog(null,"Insira algum valor.",
"Erro", JOptionPane.ERROR_MESSAGE);
* Todos os m�todos abaixos far�o algum ajuste necess�rio quando ocorrer uma
* mudan�a no ScrollPane
public void componentResized(ComponentEvent e)
scroll.getSize();
public void componentMoved(ComponentEvent e)
public void componentShown(ComponentEvent e)
public void componentHidden(ComponentEvent e)
* Listener utilizado por Java para fazer todo o controle dos Eventos que
* ocorram no aplicativo, ou seja, o pressionar dos tr�s bot�es, assim como
* a utiliza��o da tecla Enter dentro do TextField. Para cada uma destas
* a��es se encontrar� um c�digo diferente para seu processamento correto
public void actionPerformed(ActionEvent evt) {
if(evt.getSource() == reset_button) {               // Bot�o de Reiniciar
end_button.setEnabled(true);
step_button.setEnabled(true);
numProbabilidade = 0;
contarProbabilidade();
if(input_string.getText().length() > 0) {
if(parseProbabilidade(input_string.getText()))
this.reset();
stdout.println("Applet reinicializado");
this.reset();
* O bot�o de Proximo pode ser visto abaixo e ele quem far� todo o controle
* gr�fico, assim como matem�tico em rela��o aos pr�ximos valores a serem
* impressos na tela utilizando diversos m�todo diferentes
} else if(evt.getSource() == step_button) {
if(proximo) {
if(calcProbabilidade(passo)) {
proximo = false;
marcador[passo] = -1;
passo--;
} else {
int tmp = 0;
for(; tmp < 400; tmp++)
if(probabilidade[passo-1][tmp] == 0.0)
break;
Cent.printNextStep(passo, probabilidade[passo], marcador[passo]);
stdout.println("As duas probabilidades inferiores da coluna " + passo
+" foram somadas: " +
f.format(probabilidade[passo-1][tmp-1]) + " + " +
f.format(probabilidade[passo-1][tmp-2]) + " = " +
f.format(probabilidade[passo][marcador[passo]]), false);
stdout.println(1, "A soma � mostrada em negrito na coluna 2.",false);
passo++;
if(!proximo) {
if(passo < 0) {
Cent.setReverseStep(-1,-1,-1);
end_button.setEnabled(false);
step_button.setEnabled(false);
for(int k = 0; k < 200; k++) // C�lculo da entropia
if (probabilidade[0][k] != 0)
entropia += probabilidade[0][k]*(-Math.log(probabilidade[0][k])) *
Math.log(10) / Math.log(2) * Math.log(Math.exp(1/(Math.log(10))));
Double ent = new Double(entropia);
entropia = 0;
String cod = new String("Codigo correspondente:\n\n");
for(int m = 0; m < 200; m++)
if (simbolo[0][m].length() > 0)
cod += simbolo[0][m] + "\n";
JOptionPane.showMessageDialog(null, cod, "Codigo", JOptionPane.INFORMATION_MESSAGE);
stdout.println("Num. Prob.: " + numProbabilidade +
" Entropia: " + ent);
} else {
designaSimbolo(passo);
Cent.printReverseStep(passo,simbolo[passo]);
passo--;
* O bot�o de Concluir e ele simplesmente executar� o mesmo c�digo do bot�o
* Proximo, por�m at� o fim da execu��o do programa *
} else if(evt.getSource() == end_button) {
end_button.setEnabled(false);
step_button.setEnabled(false);
entropia = 0;
for(int k = 0; k < 400; k++) {
if(proximo) {
if(calcProbabilidade(passo)) {
proximo = false;
marcador[passo] = -1;
passo--;
} else {
int tmp = 0;
for(; tmp < 400; tmp++)
if(probabilidade[passo-1][tmp] == 0.0)
break;
Cent.printNextStep(passo, probabilidade[passo], marcador[passo]);
passo++;
if(!proximo) {
if(passo < 0) {
Cent.setReverseStep(-1,-1,-1);
} else {
designaSimbolo(passo);
Cent.printReverseStep(passo,simbolo[passo]);
passo--;
} // C�lculo da entropia abaixo
if (probabilidade[0][k] != 0)
entropia += probabilidade[0][k]*(-Math.log(probabilidade[0][k])) *
Math.log(10) / Math.log(2) * Math.log(Math.exp(1/(Math.log(10))));
Double ent = new Double(entropia);
entropia = 0;
stdout.println("Entropia " + f.format(ent));
String cod = new String("Codigo correspondente:\n\n");
for(int m = 0; m < 200; m++)
if (simbolo[0][m].length() > 0)
cod += simbolo[0][m] + "\n";
JOptionPane.showMessageDialog(null, cod, "Codigo", JOptionPane.INFORMATION_MESSAGE);
stdout.println("Num. Prob.: " + numProbabilidade +
" Entropia: " + ent);
* O c�digo abaixo far� todo o papel de abrir um arquivo com probabilidades,
* assim como salvar um arquivo com as probabilidades
/* } else if(evt.getSource() == file_button) {
if(estArquivo) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY):
fileChooser.showSaveDialog(this);
File fileName = fileChooser.getSelectedFile();
if (fileName == null || fileName.getName().equals(""))
JOptionPane.showMessageDialog(null, "Arquivo inv�lido.", "Erro",
JOptionPane.ERROR_MESSAGE);
else {
try {
ObjectInputStream input = new ObjectInputStream(new FileInputStream(fileName));
String arq = (String) input.readObject();
input_string.setText(arq);
if(input_string.getText().length() > 0) {
if(parseProbabilidade(input_string.getText())) {
estArquuivo = false;
end_button.setEnabled(true);
step_button.setEnabled(true);
numProbabilidade = 0;
contarProbabilidade();
this.reset();
stdout.println("Applet reinicializado");
this.reset();
} catch (EOFException e) {
JOptionPane.showMessageDialog(null, "Erro de EOF.", "Erro",
JOptionPane.ERROR_MESSAGE);
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, "Erro: Class Not Found.", "Erro",
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Erro ao abrir arquivo.", "Erro",
JOptionPane.ERROR_MESSAGE);
try {
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Erro ao fechar arquivo.", "Erro",
JOptionPane.ERROR_MESSAGE);
} else {
if (passos < 0) {
try {
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("c:\codigo.txt"));
for(int o = 0; o < 200; o++) {
while(simbolo[0][o].length() != 0) {
output.writeObject(simbolo[0][o])
output.writeObject(" ");
output.flush();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Erro ao salvar no arquivo.", "Erro",
JOptionPane.ERROR_MESSAGE);
try {
output.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Erro ao fechar arquivo.", "Erro",
JOptionPane.ERROR_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Finalize o processo.", "Erro",
JOptionPane.ERROR_MESSAGE);
/* } else if(evt.getSource() == fix_button) {
try {
input.close();
estArquivo = true;
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Erro abrindo arquivo.", "Erro",
JOptionPane.ERROR_MESSAGE);
* A a��o que ocorre quando se pressiona o bot�o Enter dentro do TextField
* pode ser vista abaixo e � bem similar ao pressionar do bot�o Reiniciar
} else if(evt.getSource() == input_string) {        // Utiliza��o da TextBox
end_button.setEnabled(true);
step_button.setEnabled(true);
numProbabilidade = 0;
contarProbabilidade();
if(input_string.getText().length() > 0) {
if(parseProbabilidade(input_string.getText()))
this.reset();
stdout.println("Applet reinicializado");
this.reset();
} else {                                            // Problema!
stdout.println("Evento desconhecido ");
* M�todo utilizado quando o bot�o Reiniciar � pressionado, ele reinicia os
* valores para todas vari�veis e coloca na primeira coluna os primeiros
* valores utilizados na �ltima experimenta��o
void reset() {
int i = 0, j = 0;
Cent.clearScreen(probabilidade[0]);
proximo = true;
passo = 1;
for(i = 0; i < 200; i++)
marcador[i] = -1;
for(i = 0; i < 200; i++)
for(j = 0; j < 250; j++)
simbolo[i][j] = "";
* Testa quanto a viabilidade das probabilidades inseridas no TextBox estarem
* de acordo com os criterios adotados e � bem simples de ser compreendida
boolean parseProbabilidade(String s) {
int linha = 0, i = 0;
double soma = 0.0;
double[] d = new double[200];
StringTokenizer st = new StringTokenizer(s); // Conta o n�mero de itens
// dentro de input_string
for(i = 0; i < 200; i++)
d[i] = 0.0;
i = 0;
while (st.hasMoreTokens()) {                  // Testa se h� mais Tokens
try {
d[i] = Double.valueOf(st.nextToken()).doubleValue();
if(d[i] < 0) {
return(false);
if(d[i] > 1.0) {
return(false);
if(d[i] == 0.0) {
return(false);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Os n�meros n�o estao em sua forma correta",
"Erro", JOptionPane.ERROR_MESSAGE);
return(false);
i++;
bubblesort(d);
for(i = 0; i < 200; i++) {                  // Testa quanto a viabilidade da
soma += d; // das vari�veis
if((soma <= 0.999999) || (soma >= 1.000001)) {
JOptionPane.showMessageDialog(null, "A soma das probabilidadades n�o e igual a 1." +
"\nA soma das probabilidade foi " + soma, "Erro", JOptionPane.ERROR_MESSAGE);
return(false);
for(i = 0; i < 200; i++)
probabilidade[0][i] = d[i];
stdout.println("Entrada de probabilidades correta. Pressione " + '\"' +
"Proximo" + '\"' + " para continuar.");
return(true);
* Este m�todo ser� utilizado como sentinela pra a inicializa��o das
* probabilidades
void iniciarProbabilidade(double[] p) {
inic = false;
iniciarProbabilidade(p, p.length-1);
* Executa a inicializa��o para alguns valores das probabilidades a partir
* do objeto Rand()
void iniciarProbabilidade(double[] p, int n) {
Random rand = new Random();
double soma = 0.0, s = 0.0;
int i = 0;
String input = " ";
stdout.println(null); // Limpa o texto abaixo
for(; i < 20; i++) {
p[i] = rand.nextDouble() + 0.1; // Gera os n�meros iniciais
soma += p[i]; // onde se deseja valores pr�ximos
for(i = 0; i < 20; i++) {
p[i] /= soma; // Escalonamento
p[i] = Math.floor(p[i]*100) / 100.0; // Truncamento
s += p[i];
for(i = 0; i < 20; i++) // Utilizado para equilibrar as
if(p[i] < 0.001) {                      //  probabilidades
p[i] += 0.01;
s -= 0.01;
if (s < 1.000) {                          // Utilizado para inteirar a soma
double resto = 1.0 - s;
p[0] += resto;
bubblesort(p);
for(int k = 0; k < 20; k++) // Constroi string a ser exibida
input += f2.format(p[k]) + " "; // dentro de string_input
String input2 = input.replace(',','.');
input_string.setText(input2);
contarProbabilidade();
* Faz um sort bem comum de todos as probabilidades inseridas
void bubblesort(double[] d) {
for(int i = 0; i < (d.length - 1); i++)
for(int j = 0; j < (d.length - 1); j++)
if(d[j] < d[j+1]) {
double t = d[j];
d[j] = d[j+1];
d[j+1] = t;
* Calcula o valor da probabilidade resultante a partir da soma das duas
* probabilidades anteriores e seu c�digo � representando somente por loops
* que setam estes valores
boolean calcProbabilidade(int passo) {
int n = 0, i = 0;
double soma = 0.0;
if(passo >= 0) {
for(; i < 400; i++)
if(probabilidade[passo-1][i] == 0.0)
break;
n = i;
soma = probabilidade[passo-1][n-1] + probabilidade[passo-1][n-2];
for(i = 0; i < 200; i++)
if(probabilidade[passo-1][i] >= soma) {
probabilidade[passo][i] = probabilidade[passo-1][i];
} else
break;
marcador[passo] = i;
probabilidade[passo][i] = soma;
for(; i < 200; i++)
probabilidade[passo][i+1] = probabilidade[passo-1][i];
probabilidade[passo][n-1] = 0.0;
probabilidade[passo][n] = 0.0;
if(n == 2)
return(true);
else
return(false);
return(true);
* Designa todos os s�mbolos ou c�digos para as probabilidades inseridas
* a partir do controle feito pelos m�todos "actionPerformed" e
* "calcProbabilidade"
void designaSimbolo(int passo) {
int i = 0, m = marcador[passo+1];
String str = "";
if(m == -1) {
simbolo[passo][0] = "0";
simbolo[passo][1] = "1";
stdout.println("Os primeiros valores (0 e 1) foram designados na coluna" +
" da extrema direita.", false);
} else {
for(; i < 400; i++)
if(probabilidade[passo+1][i] != 0.0) {
if(m == i) {
str = simbolo[passo+1][i];
} else if(m < i) {
simbolo[passo][i-1] = simbolo[passo+1][i];
} else if(m > i) {
simbolo[passo][i] = simbolo[passo+1][i];
} else
System.out.println("Problema!!!");
} else
break;
Cent.setReverseStep(passo,i,m);
stdout.println("O c�digo correspondente a probabilidade marcada (" +
f.format(probabilidade[passo+1][m]) +
") foi usado como base para se designar os valores.", false);
stdout.println(1,"O c�digo das duas probabilidade inferiores (" +
f.format(probabilidade[passo][i-1]) + ")(" +
f.format(probabilidade[passo][i]) + ")" +
" foram modificados. Os outros c�digos permanecem" +
" os mesmos.", false);
simbolo[passo][i-1] = str + "0";
simbolo[passo][i] = str + "1";
* Inicializa todo o aplicativo caso seja feito stand-alone
/* public static void main(String args[]) {
JFrame f = new JFrame("C�digo de Huffman");
Huff codigo = new Huff();
codigo.inAnApplet = false;
codigo.init();
f.getContentPane().add("Center", codigo);
f.setSize(800,600);
f.show();
codigo.start();
* A classe abaixo � utilizada para o controle de todas as mensagens exibidas
* ao usu�rio do applet a partir do JPanel stdout, assim como comunica��o
* via interface MS-DOS
class ErrorCanvas extends Canvas {
private String output, output2;
public void paint(Graphics g) {
if(output == null) {
g.drawString("C�digo de Huffman", 350, 20);
g.drawString("Arildo Fran�a Oliva Filho - 99/32810", 20, 40);
g.drawString("Leonardo Lobo Pulcineli - 99/20064", 20, 60);
g.drawString("Marcos Garrison Dytz - 99/20102", 550, 40);
g.drawString("Octavio do Vale Rocha - 99/20129", 550, 60);
} else {
g.drawString(output,20,20);
void println(String s)
println(0,s);
void println(String s,boolean echo)
println(0,s,echo);
void println(int linha,String s)
println(linha,s,true);
void println(int linha,String s,boolean echo)
if(linha == 0)
output = s;
output2 = "";
} else
output2 = s;
this.repaint();
if(s != null && echo)
System.out.println(s);
* A classe abaixo � utilizada na cria��o de toda a interface gr�fica utilizada
* pelo programa como as diversas setas que ligam as probabilidades, a cria��o
* das colunas e controle em rela��o as cores dos c�digos.
* Grande parte do c�digo deste classe deve ser creditado a Paul Williams.
class cent extends JPanel {
private int reverse_step = -1;
private int rs_y, rs_m;
private String[][] buffer; // O conjunto de vari�veis abaixo controlam
private int[] xoffsets; // todo o posicionamento dos diferentes
private int[] yoffsets; // objetos na tela
private int[] lines;
private int yoffset,yhalfoffset,linexoffset,
ybelowoffset,xrightoffset;
protected boolean isinit = false;
protected boolean repainting = false;
Font boldfont = null, deffont;
DecimalFormat f = new DecimalFormat("0.00");
* Executa a inicializa��o de todas vari�veis e arrays, assim como dos objetos
* que ser�o manipulados pela interface gr�fica caso eles n�o tenham ocorrido
void init() {
if(!isinit) {
xoffsets = new int[200];
for(int k =0; k < xoffsets.length; k++)
xoffsets[k] = 40 + k * 60;
yoffset = 16;
yoffsets = new int[400];
int i;
for(i = 0; i < yoffsets.length; i++)
yoffsets[i] = 30 * (i+1) + 60;
buffer = new String[200][400];
int j;
for(i = 0; i < 200; i++)
for(j = 0; j < 400; j++)
buffer[i][j] = "";
lines = new int[400];
for(i = 0; i < lines.length; i++)
lines[i] = -1;
linexoffset = 45; // offset of left of line from left of text
xrightoffset = 5; // offset between forward and reverse(red) text
ybelowoffset = 12; // offset between forward and reverse(red) text
yhalfoffset = 5; // offset for lines (half a character)
deffont = new Font("Dialog", 0, 12);
boldfont = new Font("Dialog", Font.BOLD, 12);
if(deffont == null || boldfont == null) {
boldfont = null;
System.out.println("N�o foi poss�vel indicar o valor para as fontes.");
isinit = true;
repainting = false;
* Construtor para essa classe e define que se a classe n�o tive sido inicia-
* lizada, ent�o ser� por este construtor
public cent()
if(!isinit)
this.init();
* Limpa todo o conte�do exibido no JPanel Cent
void clearScreen(double[] p) {
int i,j;
for(i = 0; i < 200; i++)
for(j = 0; j < 400; j++)
buffer[i][j] = "";
for(i = 0;i < lines.length; i++)
lines[i] = -1;
for(i = 0; i < 200; i++) {
if(p[i] == 0.0)
buffer[0][i*2] = "";
else
buffer[0][i*2] = f.format(p[i]);
repaint();

Similar Messages

  • Swing (JScrollPane - scroll bar) help

    Hello all..
    I am new user in Swing. Currently I am developing a program using JSCrollPane. I have to draw a kind of chart in it. Therefore as a drawing media, I used the JPanel, in which I put it inside my JScrollPane. Then.. since my graphic is long.. then I set the
    setHorizontalScrollBarPolicy value to ALWAYS. Then I put my JPanel using the following commands :
    this.jScrollPane1.setViewportView(this.jPanel2);
    this.jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    Fyi, my JPanel size is set to be wider than the jScrollPane3 size. Nevertheless.. during the run time the horizontal scroll bar is not shown. I am completely loss on how to solve this. Does anyone has any clue or solution for this problem. Thank you very much in advance.
    Kariyage.

    Fyi, my JPanel size is set to be wider than the jScrollPane3 sizeYou should use panel.setPreferredSize(...) not panel.setSize(...);

  • Swing jscrollpane border opacity

    Hi guys,
    quick question, how do you set the border of a jscrollpane to be opaque(invisable)?
    In this program we have:
    a textarea in a scrollpane, both are set to be opaque, as well as the veiwport for the scrollpane. The problem is we have about a 2 pixel thick border around it that we want to get rid of, so our question is how? Thanks!

    scrollPane.setBorder(null);  (?)

  • Java Swing application problem in Windows vista

    When we execute the Swing application in windows vista environment.
    The look and feel of the swing components are displayed improperly.
    Do we need to put any specific look and feel for windows vista environment or any specific hardware configuration is required to setup windows vista environment.
    Please give some inputs to solve the problem.
    We have tried with the following sample code to run in windows vista.
    * Vista.java
    * Created on December 5, 2006, 5:39 PM
    public class Vista extends javax.swing.JFrame {
    /** Creates new form Vista */
    public Vista() {
    initComponents();
    pack();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
    jButton1 = new javax.swing.JButton();
    jToggleButton1 = new javax.swing.JToggleButton();
    jPanel1 = new javax.swing.JPanel();
    jCheckBox1 = new javax.swing.JCheckBox();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jTextField1 = new javax.swing.JTextField();
    getContentPane().setLayout(null);
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jButton1.setText("Button 1");
    getContentPane().add(jButton1);
    jButton1.setBounds(20, 20, 170, 30);
    jToggleButton1.setText("Togle btn");
    getContentPane().add(jToggleButton1);
    jToggleButton1.setBounds(100, 80, 90, 20);
    jPanel1.setLayout(null);
    jCheckBox1.setText("jCheckBox1");
    jCheckBox1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    jCheckBox1.setMargin(new java.awt.Insets(0, 0, 0, 0));
    jPanel1.add(jCheckBox1);
    jCheckBox1.setBounds(10, 40, 130, 13);
    getContentPane().add(jPanel1);
    jPanel1.setBounds(10, 150, 200, 130);
    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);
    getContentPane().add(jScrollPane1);
    jScrollPane1.setBounds(210, 150, 164, 94);
    jTextField1.setText("jTextField1");
    getContentPane().add(jTextField1);
    jTextField1.setBounds(240, 30, 140, 30);
    pack();
    }// </editor-fold>//GEN-END:initComponents
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Vista().setVisible(true);
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration//GEN-END:variables
    }

    When we execute the Swing application in windows
    vista environment.
    The look and feel of the swing components are
    displayed improperly.Improperly means what? You must be aware that Vista's native L&F certainly isn't supported yet.

  • JTable, JScrollPane, and JinternalFrame problems.

    I have this internal frame in my application that has a scrollpane and table in it. Some how it won't let me selelct anything in the table. Also it scrolls really weird. There's a lot of chopping going on. Here's my code for the internal frame:
    public class BCDEObjectWindow extends javax.swing.JInternalFrame{
        private Vector bcdeObjects = new Vector();
        private DefaultTableModel tModel;
        public BCDEObjectWindow(JavaDrawApp p) {
            initComponents();
            this.setMaximizable(false);
            this.setClosable(false);
            this.setIconifiable(true);
            this.setDoubleBuffered(true);
            objectTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
            listScrollPane.setColumnHeaderView(new ObjectWindowHeader());
            pack();
            this.setVisible(true);
            parent = p;
            getAllBCDEFigures();
            setPopupMenu();
            tModel = (DefaultTableModel) objectTable.getModel();
            objectTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        public void getAllBCDEFigures() {
            bcdeObjects.removeAllElements();
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
        public void addBCDEFigure(BCDEFigure b) {
            bcdeObjects.add(b);
            tModel.addRow(new Object[]{b.BCDEName, "incomplete"});
        public void changeLabelName(BCDEFigure b) {
            if (bcdeObjects.contains(b)) {
                int index = bcdeObjects.indexOf(b);
                tModel.removeRow(index);
                tModel.insertRow(index, new Object[]{b.BCDEName, "incomplete"});
        public void removeBCDEFigure(BCDEFigure b) {
            int index = 0;
            if (bcdeObjects.contains(b)) {
                index = bcdeObjects.indexOf(b);
                bcdeObjects.remove(b);
                tModel.removeRow(index);
        public void removeAllBCDEFigures(){
            int i;
            for (i = 0; i < bcdeObjects.size(); i++) {
                tModel.removeRow(0);
            bcdeObjects.removeAllElements();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            listScrollPane = new javax.swing.JScrollPane();
            objectTable = new javax.swing.JTable();
            getContentPane().setLayout(new java.awt.FlowLayout());
            setBackground(new java.awt.Color(255, 255, 255));
            setIconifiable(true);
            setTitle("BCDE Objects");
            listScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            listScrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            listScrollPane.setPreferredSize(new java.awt.Dimension(250, 150));
            objectTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                new String [] {
                    "Name", "Status"
                boolean[] canEdit = new boolean [] {
                    true, false
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
            objectTable.setColumnSelectionAllowed(true);
            listScrollPane.setViewportView(objectTable);
            jPanel1.add(listScrollPane);
            getContentPane().add(jPanel1);
            pack();
        }// </editor-fold>
        // Variables declaration - do not modify
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane listScrollPane;
        private javax.swing.JTable objectTable;
        // End of variables declaration
    }and this is how i create the object in my JFrame:
    bcdeOW = new BCDEObjectWindow(this);
            bcdeOW.setLocation(400, 0);
            if (getDesktop() instanceof JDesktopPane) {
                ((JDesktopPane)getDesktop()).setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
                ((JDesktopPane)getDesktop()).add(bcdeOW, JLayeredPane.PALETTE_LAYER);
            } else
                getDesktop().add(bcdeOW);Any help would be great. Thanks a lot.

    Rajb1 wrote:
    to get the table name to appear
    create a scollpane and put the table in the scrollpane and then add the the scollpane to the component:
    //declare
    scrollpane x;
    //body code
    scrollpane x - new scrollpane();
    table y = new table();
    getContentPane().add(x(y));What language is this in, the lambda calculus -- add(x(y))!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  • Trying to scroll a JComponent with JScrollPane but can't do it. :(

    Hi, what im trying to do seems to be simple but I gave up after trying the whole day and I beg you guys help.
    I created a JComponent that is my map ( the map consists only in squared cells ). but the map might be too big for the screen, so I want to be able to scroll it. If the map is smaller than the screen,
    everything works perfect, i just add the map to the frame container and it shows perfect. But if I add the map to the ScrollPane and them add the ScrollPane to the container, it doesnt work.
    below is the code for both classes Map and the MainWindow. Thanks in advance
    package main;
    import java.awt.Color;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowStateListener;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JViewport;
    public class MainWindow implements WindowStateListener {
         private JFrame frame;
         private static MainWindow instance = null;
         private MenuBar menu;
         public Map map = new Map();
         public JScrollPane Scroller =
              new JScrollPane( map,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS );
         public JViewport viewport = new JViewport();
         private MainWindow(int width, int height) {
              frame = new JFrame("Editor de Cen�rios v1.0");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(width,height);
              frame.setVisible(true);
              menu = MenuBar.createMenuBar();
              JFrame.setDefaultLookAndFeelDecorated(false);
              frame.setJMenuBar(menu.create());
              frame.setBackground(Color.WHITE);
              frame.getContentPane().setBackground(Color.WHITE);
                                    // HERE IS THE PROBLEM, THIS DOESNT WORKS   <---------------------------------------------------------------------------------------
              frame.getContentPane().add(Scroller);
              frame.addWindowStateListener(this);
    public static MainWindow createMainWindow(int width, int height)
         if(instance == null)
              instance = new MainWindow(width,height);
              return instance;               
         else
              return instance;
    public static MainWindow returnMainWindow()
         return instance;
    public static void main(String[] args) {
         MainWindow mWindow = createMainWindow(800,600);
    public JFrame getFrame() {
         return frame;
    public Map getMap(){
         return map;
    @Override
    public void windowStateChanged(WindowEvent arg0) {
         map.repaint();
    package main;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import javax.swing.JComponent;
    import javax.swing.Scrollable;
    public class Map extends JComponent  implements Scrollable{
         private Cell [] mapCells;
         private String mapPixels;
         private String mapAltura;
         private String mapLargura;
         public void createMap(String pixels , String altura, String largura)
              mapPixels = pixels;
              mapAltura = altura;
              mapLargura = largura;
              int cells = Integer.parseInt(altura) * Integer.parseInt(largura);
              mapCells = new Cell[cells];
              //MainWindow.returnMainWindow().getFrame().getContentPane().add(this);
              Graphics2D grafico = (Graphics2D)getGraphics();
              for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                   mapCells[i] = new Cell( horiz, vert,Integer.parseInt(mapPixels));
                   MainWindow.returnMainWindow().getFrame().getContentPane().add(mapCells);
                   grafico.draw(mapCells[i].r);
                   horiz = horiz + Integer.parseInt(mapPixels);
                   if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                        horiz = 0;
                        vert = vert + Integer.parseInt(mapPixels);
              repaint();
         @Override
         protected void paintComponent(Graphics g) {
              super.paintComponent(g);
              System.out.println("entrou");
              Graphics2D g2d = (Graphics2D)g;
              if(mapCells !=null)
                   for(int i=0, horiz = 0 , vert = 0; i < mapCells.length; i++)
                        g2d.draw(mapCells[i].r);
                        horiz = horiz + Integer.parseInt(mapPixels);
                        if(horiz == Integer.parseInt(mapLargura)*Integer.parseInt(mapPixels))
                             horiz = 0;
                             vert = vert + Integer.parseInt(mapPixels);
         @Override
         public Dimension getPreferredScrollableViewportSize() {
              return super.getPreferredSize();
         @Override
         public int getScrollableBlockIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;
         @Override
         public boolean getScrollableTracksViewportHeight() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public boolean getScrollableTracksViewportWidth() {
              // TODO Auto-generated method stub
              return false;
         @Override
         public int getScrollableUnitIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              // TODO Auto-generated method stub
              return 5;

    Im so sorry Darryl here are the other 3 classes
    package main;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.filechooser.FileNameExtensionFilter;
    public class MenuActions {
         public void newMap(){
              final JTextField pixels = new JTextField(10);
              final JTextField hCells = new JTextField(10);
              final JTextField wCells = new JTextField(10);
              JButton btnOk = new JButton("OK");
              final JFrame frame = new JFrame("Escolher dimens�es do mapa");
              frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
              btnOk.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
              String txtPixels = pixels.getText();
              String hTxtCells = hCells.getText();
              String wTxtCells = wCells.getText();
              frame.dispose();
              MainWindow.returnMainWindow().map.createMap(txtPixels,hTxtCells,wTxtCells);         
              frame.getContentPane().add(new JLabel("N�mero de pixels em cada c�lula:"));
              frame.getContentPane().add(pixels);
              frame.getContentPane().add(new JLabel("Altura do mapa (em c�lulas):"));
              frame.getContentPane().add(hCells);
              frame.getContentPane().add(new JLabel("Largura do mapa (em c�lulas):"));
              frame.getContentPane().add(wCells);
              frame.getContentPane().add(btnOk);
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setSize(300, 165);
              frame.setResizable(false);
             frame.setVisible(true);
         public Map openMap (){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showOpenDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: manipular o mapa aberto
              return new Map();          
         public void save(){
         public void saveAs(){
              //Abre somente arquivos XML
              JFileChooser fc = new JFileChooser();
              FileNameExtensionFilter filter = new FileNameExtensionFilter("XML file", "xml" );
              fc.addChoosableFileFilter(filter);
              fc.showSaveDialog(MainWindow.returnMainWindow().getFrame());
              //TO DO: Salvar o mapa aberto
         public void exit(){
              System.exit(0);          
         public void copy(){
         public void paste(){
    package main;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.KeyStroke;
    public class MenuBar implements ActionListener{
         private JMenuBar menuBar;
         private final Color color = new Color(250,255,245);
         private String []menuNames = {"Arquivo","Editar"};
         private JMenu []menus = new JMenu[menuNames.length];
         private String []arquivoMenuItemNames = {"Novo","Abrir", "Salvar","Salvar Como...","Sair" };
         private KeyStroke []arquivoMenuItemHotkeys = {KeyStroke.getKeyStroke(KeyEvent.VK_N,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_A,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.CTRL_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_S,ActionEvent.SHIFT_MASK),
                                                                  KeyStroke.getKeyStroke(KeyEvent.VK_F4,ActionEvent.ALT_MASK)};
         private JMenuItem []arquivoMenuItens = new JMenuItem[arquivoMenuItemNames.length];
         private String []editarMenuItemNames = {"Copiar","Colar"};
         private KeyStroke []editarMenuItemHotKeys = {KeyStroke.getKeyStroke(KeyEvent.VK_C,ActionEvent.CTRL_MASK),
                                                                 KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK)};
         private JMenuItem[]editarMenuItens = new JMenuItem[editarMenuItemNames.length];
         private static MenuBar instance = null;
         public JMenuItem lastAction;
         private MenuBar()
         public static MenuBar createMenuBar()
              if(instance == null)
                   instance = new MenuBar();
                   return instance;                    
              else
                   return instance;
         public JMenuBar create()
              //cria a barra de menu
              menuBar = new JMenuBar();
              //adiciona items a barra de menu
              for(int i=0; i < menuNames.length ; i++)
                   menus[i] = new JMenu(menuNames);
                   menuBar.add(menus[i]);
              //seta a hotkey da barra como F10
              menus[0].setMnemonic(KeyEvent.VK_F10);
              //adiciona items ao menu arquivo
              for(int i=0; i < arquivoMenuItemNames.length ; i++)
                   arquivoMenuItens[i] = new JMenuItem(arquivoMenuItemNames[i]);
                   arquivoMenuItens[i].setAccelerator(arquivoMenuItemHotkeys[i]);
                   menus[0].add(arquivoMenuItens[i]);
                   arquivoMenuItens[i].setBackground(color);
                   arquivoMenuItens[i].addActionListener(this);
              //adiciona items ao menu editar
              for(int i=0; i < editarMenuItemNames.length ; i++)
                   editarMenuItens[i] = new JMenuItem(editarMenuItemNames[i]);
                   editarMenuItens[i].setAccelerator(editarMenuItemHotKeys[i]);
                   menus[1].add(editarMenuItens[i]);
                   editarMenuItens[i].setBackground(color);
                   editarMenuItens[i].addActionListener(this);
              menuBar.setBackground(color);
              return menuBar;                    
         @Override
         public void actionPerformed(ActionEvent e) {
              lastAction = (JMenuItem) e.getSource();
              MenuActions action = new MenuActions();
              if(lastAction.getText().equals("Novo"))
                   action.newMap();
              else if(lastAction.getText().equals("Abrir"))
                   action.openMap();
              else if(lastAction.getText().equals("Salvar"))
                   action.save();               
              else if(lastAction.getText().equals("Salvar Como..."))
                   action.saveAs();               
              else if(lastAction.getText().equals("Sair"))
                   action.exit();               
              else if(lastAction.getText().equals("Copiar"))
                   action.copy();               
              else if(lastAction.getText().equals("Colar"))
                   action.paste();               
    package main;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JComponent;
    public class Cell extends JComponent{
         public float presSub = 0;
         public double errPressInfer = 0.02;
         public double errPressSup = 0.02;
         public float profundidade = 1;
         public Rectangle2D r ;
         public Cell(double x, double y, double pixel)
              r = new Rectangle2D.Double(x,y,pixel,pixel);          
    Edited by: xnunes on May 3, 2008 6:26 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JAWS does not always read  Swing menus

    I have come across a problem that involves JAWS 4.51 and Java menus in Internet Explorer.
    I have a Java application that has a JMenuBar. The menu bar contains several JMenus that in turn contain several JMenuItems.
    When navigating through a menu, JAWS reads every JMenuItem. However, once a disabled JMenuItem is reached, JAWS no longer reads the JMenuItems below the disabled one in the open JMenu.
    The problem occurs only in Internet Explorer on "plain" menu items that follow a disabled menu item. The problem does not affect "complex" menu items, such as those that open sub menus.
    I can only reproduce this problem in Internet Explorer 6. Netscape Communicator 7, Web Start clients and a command line launch do not suffer from this problem. Also, JAWS 4.02 is fine as well; only 4.51 has this problem.
    Attached at the end is a sample application that recreates the issue. You'll notice in the sample application that JAWS will not read "A check box menu item" and "Another one" while it will read "A submenu."
    Does anyone have a solution to this? Thanks a lot!
    Sample application:
    ======================================================
    Note: The code below is a modification of the Sun menu tutorial found at http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
    middle.gif can be downloaded from http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/images/middle.gif
    MenuLookDemoApplet.java:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JCheckBoxMenuItem;
    import javax.swing.JRadioButtonMenuItem;
    import javax.swing.ButtonGroup;
    import javax.swing.JMenuBar;
    import javax.swing.KeyStroke;
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JApplet;
    /* MenuLookDemoApplet.java is a 1.4 application that requires images/middle.gif. */
    * This class exists solely to show you what menus look like.
    * It has no menu-related event handling.
    public class MenuLookDemoApplet extends JApplet {
        JTextArea output;
        JScrollPane scrollPane;
        public JMenuBar createMenuBar() {
            JMenuBar menuBar;
            JMenu menu, submenu;
            JMenuItem menuItem;
            JRadioButtonMenuItem rbMenuItem;
            JCheckBoxMenuItem cbMenuItem;
            //Create the menu bar.
            menuBar = new JMenuBar();
            //Build the first menu.
            menu = new JMenu("A Menu");
            menu.setMnemonic(KeyEvent.VK_A);
            menu.getAccessibleContext().setAccessibleDescription(
                    "The only menu in this program that has menu items");
            menuBar.add(menu);
            //a group of JMenuItems
            menuItem = new JMenuItem("A text-only menu item",
                                     KeyEvent.VK_T);
            //menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_1, ActionEvent.ALT_MASK));
            menuItem.getAccessibleContext().setAccessibleDescription(
                    "This doesn't really do anything");
            menu.add(menuItem);
            ImageIcon icon = createImageIcon("images/middle.gif");
            menuItem = new JMenuItem("Both text and icon", icon);
            menuItem.setMnemonic(KeyEvent.VK_B);
            menu.add(menuItem);
            menuItem = new JMenuItem(icon);
            menuItem.setMnemonic(KeyEvent.VK_D);
            menu.add(menuItem);
            //a group of radio button menu items
            menu.addSeparator();
            ButtonGroup group = new ButtonGroup();
            rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
            rbMenuItem.setSelected(true);
            rbMenuItem.setMnemonic(KeyEvent.VK_R);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            rbMenuItem = new JRadioButtonMenuItem("Another one");
            rbMenuItem.setMnemonic(KeyEvent.VK_O);
            group.add(rbMenuItem);
            menu.add(rbMenuItem);
            rbMenuItem.setEnabled(false);   //@dpb
            //a group of check box menu items
            menu.addSeparator();
            cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
            cbMenuItem.setMnemonic(KeyEvent.VK_C);
            menu.add(cbMenuItem);
            cbMenuItem = new JCheckBoxMenuItem("Another one");
            cbMenuItem.setMnemonic(KeyEvent.VK_H);
            menu.add(cbMenuItem);
            //a submenu
            menu.addSeparator();
            submenu = new JMenu("A submenu");
            submenu.setMnemonic(KeyEvent.VK_S);
            menuItem = new JMenuItem("An item in the submenu");
            menuItem.setAccelerator(KeyStroke.getKeyStroke(
                    KeyEvent.VK_2, ActionEvent.ALT_MASK));
            submenu.add(menuItem);
            menuItem = new JMenuItem("Another item");
            submenu.add(menuItem);
            menu.add(submenu);
            //Build second menu in the menu bar.
            menu = new JMenu("Another Menu");
            menu.setMnemonic(KeyEvent.VK_N);
            menu.getAccessibleContext().setAccessibleDescription(
                    "This menu does nothing");
            menuBar.add(menu);
            return menuBar;
        public Container createContentPane() {
            //Create the content-pane-to-be.
            JPanel contentPane = new JPanel(new BorderLayout());
            contentPane.setOpaque(true);
            //Create a scrolled text area.
            output = new JTextArea(5, 30);
            output.setEditable(false);
            scrollPane = new JScrollPane(output);
            //Add the text area to the content pane.
            contentPane.add(scrollPane, BorderLayout.CENTER);
            return contentPane;
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path) {
            java.net.URL imgURL = MenuLookDemo.class.getResource(path);
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
                return null;
        public void init() {
            MenuLookDemoApplet demo = new MenuLookDemoApplet();
            setJMenuBar(demo.createMenuBar());
            setContentPane(demo.createContentPane());
    applet.html:
    <html>
    <head>
        <title>Menu Test Page </title>
    </head>
    <body>
    Here's the applet:
    <applet code="MenuLookDemoApplet.class" width="300" height="300">
    </applet>
    </body>
    </html>

    Unfortunately the menu items are fully accessible (or so our internal accessibility tool claims). It doesn't seem to be a problem on that level, but I was hoping that perhaps something else was interfeering.
    As for the JTable reading the previous cell, I've notice that it reads the last non-empty cell (regardless of whether it was the previous cell or not) when clicking or moving with the arrow keys to an empty cell. It works fine when clicking or moving to non-empty cells.
    I don't have any empty cells in the actual application so I did not try to fix it. My suspicions are that either an event is not being fired or the selection position is not being updated on the empty cells.

  • Swings-JFrame

    IN my program ,JFrame,JButton1 named VIEW ALL ,JComboBox ,JButton2 by clicking this calender will be displayed select the date ,that selected date will come into JComboBox,JButton3 named BY DATE.
    when click on VIEW ALL button data from the database(oracle 10g) will be retrieved into JTable, that table will be displayed in same JFrame.
    If we click on BY DATE button data will be displayed by that date only in the same JFrame.
    view is like this:
    VIEW ALL JCOmboBox JButton2 BY DATE
    display of JTable resultsin the same frame
    i have written the code for JTable like this;
    package crm;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    import java.lang.*;
    * @author rajeshwari
    public class Callbacks extends javax.swing.JFrame {
    JTable table;
         JTableHeader header;
         Vector data = new Vector();
         String colnames[];
    public Callbacks() {
    getConnection();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    // private void initComponents() {
    // jPanel1 = new javax.swing.JPanel();
    // jPanel2 = new javax.swing.JPanel();
    // jButton1 = new javax.swing.JButton();
    // jButton2 = new javax.swing.JButton();
    // jButton3 = new javax.swing.JButton();
    // jButton4 = new javax.swing.JButton();
    // jButton5 = new javax.swing.JButton();
    // jButton6 = new javax.swing.JButton();
    // jButton7 = new javax.swing.JButton();
    // jLabel1 = new javax.swing.JLabel();
    // jTextField1 = new javax.swing.JTextField();
    // jLabel2 = new javax.swing.JLabel();
    // jTextField2 = new javax.swing.JTextField();
    // jLabel3 = new javax.swing.JLabel();
    // jScrollPane1 = new javax.swing.JScrollPane();
    // jTextArea1 = new javax.swing.JTextArea();
    // jLabel4 = new javax.swing.JLabel();
    // jTextField3 = new javax.swing.JTextField();
    // jLabel5 = new javax.swing.JLabel();
    // jTextField4 = new javax.swing.JTextField();
    // jLabel6 = new javax.swing.JLabel();
    // jTextField5 = new javax.swing.JTextField();
    // jLabel7 = new javax.swing.JLabel();
    // jTextField6 = new javax.swing.JTextField();
    // jLabel8 = new javax.swing.JLabel();
    // jTextField7 = new javax.swing.JTextField();
    // jLabel9 = new javax.swing.JLabel();
    // jTextField8 = new javax.swing.JTextField();
    // jLabel10 = new javax.swing.JLabel();
    // jTextField9 = new javax.swing.JTextField();
    // jLabel11 = new javax.swing.JLabel();
    // jTextField10 = new javax.swing.JTextField();
    // jButton8 = new javax.swing.JButton();
    // jButton9 = new javax.swing.JButton();
    // jPanel3 = new javax.swing.JPanel();
    // jLabel12 = new javax.swing.JLabel();
    // jTextField11 = new javax.swing.JTextField();
    // jLabel13 = new javax.swing.JLabel();
    // jTextField12 = new javax.swing.JTextField();
    // jLabel14 = new javax.swing.JLabel();
    // jTextField13 = new javax.swing.JTextField();
    // jLabel15 = new javax.swing.JLabel();
    // jTextField14 = new javax.swing.JTextField();
    // jScrollPane2 = new javax.swing.JScrollPane();
    // jTextPane1 = new javax.swing.JTextPane();
    // jButton10 = new javax.swing.JButton();
    // jScrollPane3 = new javax.swing.JScrollPane();
    // jTextPane2 = new javax.swing.JTextPane();
    // jMenuBar1 = new javax.swing.JMenuBar();
    // jMenu1 = new javax.swing.JMenu();
    // jMenu2 = new javax.swing.JMenu();
    // jMenu3 = new javax.swing.JMenu();
    // jMenu4 = new javax.swing.JMenu();
    // jMenu5 = new javax.swing.JMenu();
    // jMenu6 = new javax.swing.JMenu();
    // jMenu7 = new javax.swing.JMenu();
    // jMenu8 = new javax.swing.JMenu();
    // setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    // jButton1.setText("Call Back");
    // jButton2.setText("Not Interested");
    // jButton3.setText("Person Not Available\n");
    // jButton4.setText("Answering Machine");
    // jButton5.setText("Person Available");
    // jButton6.setText("Do not Call");
    // jButton7.setText("Next>>...");
    // org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
    // jPanel2.setLayout(jPanel2Layout);
    // jPanel2Layout.setHorizontalGroup(
    // jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel2Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jButton2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
    // .add(jButton7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)))
    // jPanel2Layout.setVerticalGroup(
    // jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel2Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jButton1)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton2)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton3)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton4)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton5)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton6)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jButton7)
    // .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // jLabel1.setText("\nCustomer ID:");
    // jTextField1.setText("852");
    // jLabel2.setText("Customer Name:");
    // jTextField2.setText("Rajeshwari");
    // jLabel3.setText("Address:");
    // jTextArea1.setColumns(20);
    // jTextArea1.setRows(5);
    // jScrollPane1.setViewportView(jTextArea1);
    // jLabel4.setText("City:");
    // jTextField3.setText("HYD");
    // jLabel5.setText("State:");
    // jTextField4.setText("A.P");
    // jLabel6.setText("Zip:");
    // jTextField5.setText("39");
    // jLabel7.setText("Phone:");
    // jTextField6.setText("220288");
    // jLabel8.setText("Mobile:");
    // jTextField7.setText("9949162978");
    // jLabel9.setText("Fax:");
    // jTextField8.setText("2343535");
    // jLabel10.setText("Email:");
    // jTextField9.setText("[email protected]");
    // jLabel11.setText("Call Time:");
    // jTextField10.setText("12:34:23");
    // jButton8.setText("Call Backs");
    // jButton8.addActionListener(new java.awt.event.ActionListener() {
    // public void actionPerformed(java.awt.event.ActionEvent evt) {
    // jButton8ActionPerformed(evt);
    // jButton9.setText("Hang");
    // jLabel12.setText("Call Back Date:");
    // jTextField11.setText("12-03-98");
    // jLabel13.setText("Call Back Time:");
    // jTextField12.setText("12:23:45");
    // jLabel14.setText("Called on:");
    // jTextField13.setText("11:12:99");
    // jLabel15.setText("Called At:");
    // jTextField14.setText("jTextField14");
    // jScrollPane2.setViewportView(jTextPane1);
    // jButton10.setText("ADD");
    // org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
    // jPanel3.setLayout(jPanel3Layout);
    // jPanel3Layout.setHorizontalGroup(
    // jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel12)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField11, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel13)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField12, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
    // .add(27, 27, 27)
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel14)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 84, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jLabel15)
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jTextField14))))
    // .add(jPanel3Layout.createSequentialGroup()
    // .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 187, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(28, 28, 28)
    // .add(jButton10)))
    // .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // jPanel3Layout.setVerticalGroup(
    // jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel3Layout.createSequentialGroup()
    // .addContainerGap()
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel12)
    // .add(jTextField11, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel14)
    // .add(jTextField13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(17, 17, 17)
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel13)
    // .add(jTextField12, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel15)
    // .add(jTextField14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
    // .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
    // .add(jButton10)
    // .add(22, 22, 22))))
    // jScrollPane3.setViewportView(jTextPane2);
    // org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    // jPanel1.setLayout(jPanel1Layout);
    // jPanel1Layout.setHorizontalGroup(
    // jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(30, 30, 30)
    // .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(32, 32, 32)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jLabel2)
    // .add(jLabel1)
    // .add(jLabel3)
    // .add(jLabel4)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 46, Short.MAX_VALUE)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
    // .add(jTextField2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
    // .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 149, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(58, 58, 58))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jTextField3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
    // .add(jTextField4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE))
    // .add(66, 66, 66))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jTextField5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 149, Short.MAX_VALUE)
    // .add(66, 66, 66))))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(254, 254, 254)))
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jButton8)
    // .add(27, 27, 27)
    // .add(jButton9))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
    // .add(jLabel7, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    // .add(jLabel8, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    // .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel9))
    // .add(jLabel10)
    // .add(jLabel11))
    // .add(6, 6, 6)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
    // .add(jTextField10)
    // .add(jTextField9)
    // .add(jTextField8)
    // .add(jTextField7)
    // .add(jTextField6, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)))
    // .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 212, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(45, 45, 45))
    // jPanel1Layout.setVerticalGroup(
    // jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(23, 23, 23)
    // .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(42, 42, 42)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel1)
    // .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel7)
    // .add(jTextField6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(16, 16, 16)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel2)
    // .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(25, 25, 25)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jLabel3))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 17, Short.MAX_VALUE)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel4)
    // .add(jTextField3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(18, 18, 18)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel5)
    // .add(jTextField4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jTextField5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jButton8)
    // .add(jButton9)
    // .add(jLabel6, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 34, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED))
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(27, 27, 27)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel8)
    // .add(jTextField7, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(27, 27, 27)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel9)
    // .add(jTextField8, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(27, 27, 27)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel10)
    // .add(jTextField9, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    // .add(34, 34, 34)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    // .add(jLabel11)
    // .add(jTextField10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))))
    // .add(63, 63, 63)
    // .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
    // .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(jPanel1Layout.createSequentialGroup()
    // .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 88, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .add(44, 44, 44))))
    // jMenu1.setText("start");
    // jMenuBar1.add(jMenu1);
    // jMenu2.setText("Leads");
    // jMenuBar1.add(jMenu2);
    // jMenu3.setText("Campaign");
    // jMenuBar1.add(jMenu3);
    // jMenu4.setText("Reports");
    // jMenuBar1.add(jMenu4);
    // jMenu5.setText("Recordings");
    // jMenuBar1.add(jMenu5);
    // jMenu6.setText("Agents");
    // jMenuBar1.add(jMenu6);
    // jMenu7.setText("Time Zones");
    // jMenuBar1.add(jMenu7);
    // jMenu8.setText("Help");
    // jMenuBar1.add(jMenu8);
    // setJMenuBar(jMenuBar1);
    // org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
    // getContentPane().setLayout(layout);
    // layout.setHorizontalGroup(
    // layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(layout.createSequentialGroup()
    // .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    // .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // layout.setVerticalGroup(
    // layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    // .add(layout.createSequentialGroup()
    // .add(78, 78, 78)
    // .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    // pack();
    // }// </editor-fold>
    public void getConnection()
    // Object src=evt.getSource();
    String name="";
    String call_back_date="";
    String call_back_time="";
    String called_on="";
    String called_at="";
    String phone="";
    String comments="";
    // if(src==jButton8)
    try{
    colnames=new String[]{"name","call_back_date","call_back_time","called_on","called_at","phone","comments"};
    Class.forName("oracle.jdbc.driver.OracleDriver");
    String url="jdbc:oracle:thin:@localhost:1521:oracle";
    Connection con=DriverManager.getConnection(url,"scott","root");
    Statement st=con.createStatement();
    ResultSet rs=st.executeQuery("select * from Callbacks_details");
              while (rs.next())
              name=rs.getString("name");
              call_back_date=rs.getString("call_back_date");
              call_back_time=rs.getString("call_back_time");
    called_on=rs.getString("called_on");
    called_at=rs.getString("called_at");
              phone=rs.getString("phone");
    comments=rs.getString("comments");
    Vector row = new Vector(colnames.length);
    // Vector r=new Vector();
              row.addElement(name);
              row.addElement(call_back_date);
              row.addElement(call_back_time);
    row.addElement(called_on);
    row.addElement(called_at);
              row.addElement(phone);
    row.addElement(comments);
              data.addElement(row);
    // System.out.println(data);
    catch(Exception a)
    a.printStackTrace();
    System.out.println(a);
    table=new JTable(new MyTableModel(colnames,data));
    //int n=table.getColumnCount();
              TableColumn column=null;
              for (int i = 0; i<colnames.length; i++) {
              column = table.getColumnModel().getColumn(i);
         column.setPreferredWidth(100);
              JScrollPane scrollPane = new JScrollPane(table);
              getContentPane().add(scrollPane);
    public class MyTableModel extends AbstractTableModel{
    String[] columnNames;
         Vector d= new Vector(6);
    MyTableModel(String[] columnNames, Vector data){
         this.columnNames = columnNames;
         d = data;
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return d.size();
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
         Vector d

    for displaying table on same frame(do not cross post and use code tags just click CODE and paste the code in between)
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    public class TableShow extends JFrame{
        /** Creates a new instance of TableShow */
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        public TableShow() {
            jTable1 = new javax.swing.JTable(5,5);
            jScrollPane1 = new javax.swing.JScrollPane(jTable1);
            jButton1 = new javax.swing.JButton("Show");
            jPanel1 = new javax.swing.JPanel();
            jPanel1.setLayout(new BorderLayout());
            jPanel1.add(jScrollPane1);
            jScrollPane1.setVisible(false);
            getContentPane().add(jButton1, BorderLayout.NORTH);
            getContentPane().add(jPanel1, BorderLayout.CENTER);
            setVisible(true);
            setSize(300,300);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(jScrollPane1.isVisible()) {
                        jScrollPane1.setVisible(false);
                    } else{
                        jScrollPane1.setVisible(true);
                    jPanel1.validate();
        public static void main(String args[]){
            new TableShow();
    }

  • How can i  add more than 500 jPanels in a jScrollPane

    Hello to all ,
    I am facing a problem related to adding jPanels in jScrollPane. My application needs more than 500 jpanels in the jscrollpane.where in each jPanel 4 jtextboxes, 1 comboboxes, 1 check box is there.when the check box will be clicked then the total row( ie row means the panel containing the 4 jtextboxes, 1 comboboxes, 1 check box ).and when the user will click on move up or move down button then the selected jpanel will move up or down.
    The tool(sun java studio enterprise 8.1) is not allowing more Jpanels to add manually. so i have to add the jpanels by writing the code in to a loop. and the problem is that when i am trying to add the code in the code generated by the tool the code written out side the code by me is not integratable into the tool generated code.
    If u watch the code here am sending u ll get what am facing the problem. The idea of creating jpanels through loop is ok but when trying to impleent in tool facing difficulties.
    A example code am sending here. please tell me how i can add more panels to the scrollpane(it is the tool generated code)
    Thanks in advance , plz help me for the above
    package looptest;
    public class loopframe extends javax.swing.JFrame {
    /** Creates new form loopframe */
    public loopframe() {
    initComponents();
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jPanel1 = new javax.swing.JPanel();
    jPanel2 = new javax.swing.JPanel();
    jTextField1 = new javax.swing.JTextField();
    jComboBox1 = new javax.swing.JComboBox();
    jPanel3 = new javax.swing.JPanel();
    jTextField2 = new javax.swing.JTextField();
    jComboBox2 = new javax.swing.JComboBox();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setText("jTextField1");
    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
    org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
    jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel2Layout.createSequentialGroup()
    .add(28, 28, 28)
    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 109, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(54, 54, 54)
    .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 156, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(35, Short.MAX_VALUE))
    jPanel2Layout.setVerticalGroup(
    jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel2Layout.createSequentialGroup()
    .addContainerGap()
    .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .addContainerGap(21, Short.MAX_VALUE))
    jTextField2.setText("jTextField2");
    jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
    org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
    jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel3Layout.createSequentialGroup()
    .add(20, 20, 20)
    .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 111, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(33, 33, 33)
    .add(jComboBox2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 168, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(40, Short.MAX_VALUE))
    jPanel3Layout.setVerticalGroup(
    jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel3Layout.createSequentialGroup()
    .add(21, 21, 21)
    .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    .add(jComboBox2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .addContainerGap(21, Short.MAX_VALUE))
    org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .addContainerGap(58, Short.MAX_VALUE))
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel1Layout.createSequentialGroup()
    .add(21, 21, 21)
    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(49, 49, 49)
    .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(66, Short.MAX_VALUE))
    jScrollPane1.setViewportView(jPanel1);
    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .add(31, 31, 31)
    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 439, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(74, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .add(30, 30, 30)
    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 254, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(55, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new loopframe().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration
    and
    package looptest;
    public class Main {
    public Main() {
    public static void main(String[] args) {
    new loopframe().setVisible(true);
    }

    Thanks for here kind attention to solve my problem.
    I am thinking to create the classes separately for the components (i.e the jpanel, combobox,textbox etc)and call their instaces from the for loop .But the problem is the jpanel will contain the other components and that jpanels (unlimited jpanels will be added later)will be later added to the jscrollpane.
    By writing code, the problem is to place components( the comboboxes,textboxes etc placed on the jpanel ) in appropriate coordinates . So i am doing it through tool .
    I am sending here the sample code related to my actual need . In this i have taken a jScrollPane, on that i have added jPanel1 and on jPanel1 i have added jPanel2.On jPanel2 jTextField1, jComboBox1,jCheckBox are added. If the u ll see the code u can understand what problem i am facing.
    If i am still not clearly explained ,please ask me. plz help me if u can as u have already handled a problem similar to this.
    package addpanels;
    public class Main {
    /** Creates a new instance of Main */
        public Main() {
        public static void main(String[] args) {
            new addpanels().setVisible(true);
    } and
    package addpanels;
    public class addpanels extends javax.swing.JFrame {
        /** Creates new form addpanels */
        public addpanels() {
            initComponents();
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jPanel1 = new javax.swing.JPanel();
            jPanel2 = new javax.swing.JPanel();
            jTextField1 = new javax.swing.JTextField();
            jComboBox1 = new javax.swing.JComboBox();
            jCheckBox1 = new javax.swing.JCheckBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jTextField1.setText("jTextField1");
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
            jCheckBox1.setText("jCheckBox1");
            jCheckBox1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            jCheckBox1.setMargin(new java.awt.Insets(0, 0, 0, 0));
            org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 131, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 144, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jCheckBox1)
                    .addContainerGap(39, Short.MAX_VALUE))
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                    .addContainerGap(17, Short.MAX_VALUE)
                    .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jCheckBox1))
                    .addContainerGap())
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(34, Short.MAX_VALUE))
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .add(26, 26, 26)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(152, Short.MAX_VALUE))
            jScrollPane1.setViewportView(jPanel1);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(36, Short.MAX_VALUE)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 449, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(18, 18, 18))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(32, 32, 32)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 230, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(38, Short.MAX_VALUE))
            pack();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new addpanels().setVisible(true);
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JCheckBox jCheckBox1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration//GEN-END:variables
    }

  • Removing a window and adding a new one with swing.

    Hi,
    A friend of mine recently asked me to add a GUI for a small chat he made, so I thought I'd help him out. I've come across something that's troubled me in the past, and I could never find a solution. What I'm trying to do is make it so a log in window pops up (have that working alright) and then when you press sign in, it removes that window (log in) and adds the main chat window (have this fully functional, too).
    If someone could provide an example or point me in the direction of the proper API to look into, so that I don't have to look through them all, I'd be extremely grateful.
    Here's an SSCCE example:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTextPane;
    import javax.swing.ListSelectionModel;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.SwingUtilities;
    public class Gui extends JFrame {
         public static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
         public String sessionId;
         public int returnCode;
         public boolean recievedReturnCode;
         public boolean errorConnecting;
         public long lastActionDelay;
         private JScrollPane listScrollPane;
         private JList list;
         private JTextPane console;
         private JButton signInButton;
         private JScrollPane consoleScrollPane;
         private JTextField typingField;
         private DefaultListModel userList;
         private JButton sendButton;
         public static void main(String[] args) {
              try {
                   SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                             new Gui().setVisible(true);
              } catch (Exception e) {
                   e.printStackTrace();
         public Gui() {
              setResizable(false);
              setSize(500, 500);
              consoleScrollPane = new JScrollPane();
              console = new JTextPane();
              typingField = new JTextField();
              userList = new DefaultListModel();
              sendButton = new JButton();
              initializeLoginWindow();
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         public void initializeLoginWindow() {
              setTitle("Login");
              signInButton = new JButton("Sign in");
              signInButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt) {
                        initializeChatWindow();
              signInButton.setBounds(5, 100, 75, 20);
              getContentPane().add(signInButton);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(new JPanel());
         public void initializeChatWindow() {
              consoleScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
              consoleScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
              consoleScrollPane.setViewportView(console);
              consoleScrollPane.setBounds(5, 5, 575, 350);
              console.setEditable(false);
              typingField.setEditable(true);
              typingField.setBounds(5, 360, 575, 25);
              list = new JList(userList);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.setSelectedIndex(0);
            list.setVisibleRowCount(5);
            listScrollPane = new JScrollPane(list);
              listScrollPane.setBounds(585, 5, 110, 350);
              sendButton.setText("Send");
              sendButton.setBounds(585, 360, 111, 25);
              getContentPane().add(consoleScrollPane);
              getContentPane().add(typingField);
              getContentPane().add(listScrollPane);
              getContentPane().add(sendButton);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(new JPanel());
    }Thanks in advanced!

    jduprez wrote:
    I've come across something that's troubled me in the past, and I could never find a solutionWhat is the problem?
    a log in window pops up (have that working alright)
    and then when you press sign in, it removes that window (log in) and adds the main chat window (have this fully functional, too).Hum, between what is working alright and what is already functional, I fail to see what is missing. Again, what is your problem/question?
    If someone could provide an example or point me in the direction of the proper API to look into, so that I don't have to look through them all, I'd be extremely grateful.
    [url http://download.oracle.com/javase/tutorial/uiswing/components/frame.html]JFrames and [url http://download.oracle.com/javase/tutorial/uiswing/components/dialog.html]dialogs seem to show enough API usage to do that. Still, I stronlgy encourage you to read the whole Swing tutorial: http://download.oracle.com/javase/tutorial/uiswing/index.html
    Incase you didn't see the hyperlink above, here's the SSCCE link: http://www.mediafire.com/?e5e3ci3kbvickla
    The "S" in SSCCE stands for "Short" (or, depending on authors, "Simple"). Anyway, a decent SSCCE should fit within a forum post (between code tags please). The whole idea is to provide the simplest thing to people willing to help. No doubtful sites. No non-standard extensions.
    Best regards,
    The problem is that I cannot seem to remove the first pane, leaving the second one to be drawn on the current one.
    In reguards to SSCCE, I always thought it was just a short runnable class example, but I've added the class to the main post. I'll take a look at the API in a few as well.

  • Need help with using graphics in swing components

    Hi. I'm new to Java and trying to learn it while also developing an application for class this semester. I've been following online tutorials for about 2 months now, though, and so I'm not sure my question counts as a "new to Java" question any more as the code is quite long.
    Here is the basic problem. I started coding the application as a basic awt Applet (starting at "Hello World") and about a month in realized that Swing components offer better buttons, panels, layouts, etc. So I converted the application, called BsfAp, to a new JApplet and started adding JPanels and JComponents with layout managers. My problem is, none of the buffered graphics run in any kind of JPanel, only the buttons do. I assume the buffered graphics are written straight to the JApplet top level container instead but I'm not entirely sure.
    So as to not inundate the forum with code, the JApplet runs online at:
    http://mason.gmu.edu/~dho2/files/sensor.html
    The source code is also online at:
    http://mason.gmu.edu/~dho2/files/BsfAp.java
    What I would like to do is this - take everything in the GUI left of the tabbed button pane and put it into a JScrollPane so that I can use a larger grid size with map display I can scroll around. The grid size I would like to use is more like 700x1000 pixels, but I only want to display about 400x400 pixels of it at a time in the JScrollPane. Then I could also move this JScrollPane around with layout manager. I think this is possible, but I don't know how to do it.
    I'm sure the code is not organized or optimized appropriately to those of you who use Java every day, but again I'm trying to learn it. ;-)
    Thanks for any help or insight you could provide in this.
    Matt

    Couple of recs:
    * Don't override paint and paint directly on the JApplet. Paint on a JPanel and override paintComponent.
    * The simplest way to display a graphic is to put an image into an ImageIcon and show this in a JLabel. This can then easily go inside of the JScrollPane.
    * You can also create a graphics JPanel that overrides the paintComponent, draw the image in that and show that inside of the JScrollPane.
    * don't call paint() directly. Call repaint if you want the graphic to repaint.
    Here's a trivial example quickly put together:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GradientPaint;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Paint;
    import java.awt.RenderingHints;
    import java.awt.geom.Ellipse2D;
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JApplet;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class BsfCrap extends JApplet
        private JPanel mainPanel = new JPanel();
        private JScrollPane scrollPane;
        private JPanel graphicsPanel = new JPanel()
            @Override
            protected void paintComponent(Graphics g)
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D)g;
                RenderingHints rh = new RenderingHints(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setRenderingHints(rh);
                Paint gPaint = new GradientPaint(0, 0, Color.blue,
                    40, 40, Color.magenta, true);
                g2d.setPaint(gPaint);
                g2d.fill(new Ellipse2D.Double(0, 0, 800, 800));
        public BsfCrap()
            mainPanel.setPreferredSize(new Dimension(400, 400));
            mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            graphicsPanel.setPreferredSize(new Dimension(800, 800));
            graphicsPanel.setBackground(Color.white);
            scrollPane = new JScrollPane(graphicsPanel);
            scrollPane.setPreferredSize(new Dimension(300, 300));
            mainPanel.add(scrollPane);
        public JPanel getMainPanel()
            return mainPanel;
        @Override
        public void init()
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        setSize(new Dimension(400, 400));
                        getContentPane().add(new BsfCrap().getMainPanel());
            catch (InterruptedException e)
                e.printStackTrace();
            catch (InvocationTargetException e)
                e.printStackTrace();
    }

  • Install Application - TextArea inside JScrollPane

    I've been working on an install application to install another one of my programs (next/accept/next/ finish type of thing) and had a couple questions and would appreciate any help anyone can give.
    Some Background info:
    I made images and have them display as image icons through jlabels for the buttons and background. The labels have classes applying various mouselisteners (Mousepressed, MouseEntered, MouseExited, etc) changing the images and moving from screen to screen. I have my layout set to null, not for any particular reason, but because I have no formal education in layout managers.
    1) Is there a conical solution to moving through various windows? That is, right now I move through the various 'screens' with a check on an int called state, that gets incremented and decremented through forward and back buttons. I looked at some code given to us on a test by our teacher (we had to find bugs) and saw that he had implemented a fake "state" interface, with constants like "Account_State" to control where you were in the program. This seems a bit easier to read than ints, but is there a correct built in version of his states?
    2) On the second screen I have a license agreement (actually required for the application that gets installed), and a checkbox. The license is held inside of a JTextArea(scroll) inside a JScrollPane(textscroll). The JScrollPane is extending in weird ways. The following is a stripped down version of my code (it runs and demonstrates the problem):
    InstalleApp
    import javax.swing.*;
    import java.awt.*;
    public class InstalleApp {
        public static void main(String args[]) {
            InstalleFrame m = new InstalleFrame();
               Container content = m.getContentPane();
            m.setDefaultCloseOperation(3);
            m.setSize(550, 400);
            m.setUndecorated(true);
            m.setVisible(true);
            m.setTitle("Install");
    }InstalleFrame
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    import java.awt.event.*;
    import java.awt.Rectangle;
    import java.awt.Font;
    import java.awt.BorderLayout;
    import java.util.*;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import java.awt.event.ActionEvent;
    import javax.swing.text.BadLocationException;
    import javax.swing.JSlider;
    import java.awt.Dimension;
    public class InstalleFrame
        extends JFrame implements ActionListener {
      public InstalleFrame() {
        try {
          jbInit();
        catch (Exception ex) {
          ex.printStackTrace();
      public void actionPerformed(ActionEvent e) {
      JScrollPane textscroll;
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(null);
        this.getContentPane().setBackground(UIManager.getColor("window"));
        background.setBounds(new Rectangle(0, 0, 550, 400));
        readcheck.setOpaque(false);
        readcheck.setText("I have read and accept the license agreement");
        readcheck.setBounds(new Rectangle(31, 357, 319, 32));
        scroll.setWrapStyleWord(true);
        scroll.setLineWrap(true);
        scroll.setText(
            "Copyright ? 2006-2007 GonZor228.com \n\nBy using or distributing this " +
            "software (or any work based on the software) you shall be deemed " +
            "to have accepted the terms and conditions set out below.\n\nGonZor228.com " +
            "(\"GonZor\") is making this software freely available on the basis " +
            "that it is accepted as found and that the user checks its fitness " +
            "for purpose prior to use.\n\nThis software is provided \'as-is\', without " +
            "any express or implied warranties whatsoever. In no event will the " +
            "authors, partners or contributors be held liable for any damages, " +
            "claims or other liabilities direct or indirect, arising from the " +
            "use of this software.\n\nGonZor will from time to time make software " +
            "updates available.  However, GonZor accepts no obligation to provide " +
            "any support to free license holders.\n\nGonZor grants you a limited " +
            "non-exclusive license to use this software for any purpose that does " +
            "not violate any laws that apply to your person in your current jurisdiction, " +
            "subject to the following restrictions: \n\n1. The origin of this software " +
            "must not be misrepresented; you must not claim that you wrote the " +
            "original software.\n2. You must not alter the software, user license " +
            "or installer in any way unless given permission to do so.\n3. This " +
            "notice may not be removed or altered from any distribution.\n4. You " +
            "may not resell or charge for the software.\n5. You may not reverse " +
            "engineer, decompile, disassemble, derive the source code of or modify " +
            "[or create derivative work from] the program without the express " +
            "permission of GonZor.\n6. You must not use this software to engage " +
            "in or allow others to engage in any illegal activity.\n7. You may " +
            "not claim any sponsorship by, endorsement by, or affiliation with " +
            "GonZor228.com\n8. You acknowledge that GonZor owns the copyright and " +
            "all associated intellectual property rights relating to the software.\n\n" +
            " This software license is governed by and construed in accordance " +
            "with the laws of Australia and you agree to submit to the exclusive " +
            "jurisdiction of the Australian courts.\n\nBy clicking the \"I agree\" " +
            "button below, you agree to these software license terms. If you disagree " +
            "with any of the terms below, GonZor does not grant you a license " +
            "to use the software ? exit the window.\n\nYou agree that by your installation " +
            "of the GonZor?s software, you acknowledge that you are at least 18 " +
            "years old, have read this software license, understand it, and agree " +
            "to be bound by its terms.\n\nGonZor reserves the right to update and " +
            "change, from time to time, this software license and all documents " +
            "incorporated by reference. You can always find the most recent version " +
            "of this software license at GonZor228.com.  GonZor may change this " +
            "software license by posting a new version without notice to you. " +
            "Use of the GonZor?s software after such change constitutes acceptance " +
            "of such changes.\n\n1.\tOwnership and Relationship of Parties.\n\nThe " +
            "software is protected by copyrights, trademarks, service marks, international " +
            "treaties, and/or other proprietary rights and laws of the U.S. and " +
            "other countries. You agree to abide by all applicable proprietary " +
            "rights laws and other laws, as well as any additional copyright notices " +
            "or restrictions contained in this software license. GonZor owns all " +
            "rights, titles, and interests in and to the applicable contributions " +
            "to the software. This software license grants you no right, title, " +
            "or interest in any intellectual property owned or licensed by GonZor, " +
            "including (but not limited to) the software, and creates no relationship " +
            "between yourself and GonZor other than that of GonZor to licensee.\n\n" +
            "The software and its components contain software licensed from " +
            "GonZor. The licensor software enables the software to perform certain " +
            "functions including, without limitation, access proprietary data " +
            "on third-party data servers as well as GonZor?s own server. You agree " +
            "that you will use the software, and any data accessed through the " +
            "software, for your own personal non-commercial use only. You agree " +
            "not to assign, copy, transfer, or transmit the software, or any data " +
            "obtained through the software, to any third party. Your license to " +
            "use the software, its components, and any third-party data, will " +
            "terminate if you violate these restrictions. If your license terminates, " +
            "you agree to cease any and all use of the software, its components, " +
            "and any third-party data. All rights in any third-party data, any " +
            "third-party software, and any third-party data servers, including " +
            "all ownership rights are reserved and remain with the respective " +
            "third parties. You agree that these third parties may enforce their " +
            "rights under this Agreement against you directly in their own name.\n\n" +
            "2.\tSupport and Software Updates.\n\nGonZor may elect to provide " +
            "you with customer support and/or software upgrades, enhancements, " +
            "or modifications for the software (collectively, \"Support\"), in its " +
            "sole discretion, and may terminate such Support at any time without " +
            "notice to you. GonZor may change, suspend, or discontinue any aspect " +
            "of the software at any time, including the availability of any software " +
            "feature, database, or content. GonZor may also impose limits on certain " +
            "features and services or restrict your access to parts or all of " +
            "the software or the GonZor228.com web site without notice or liability.\n\n" +
            "3.  \tFees and Payments.\n\nGonZor reserves the right to charge fees " +
            "for future use of or access to the software in GonZor?s sole discretion. " +
            "If GonZor decides to charge for the software, such charges will be " +
            "disclosed to you 28 days before they are applied if such fees will " +
            "affect your use of the product.\n\n4.\tDisclaimer of Warranties by " +
            "GonZor.\n\nUse of the software and any data accessed through the software " +
            "is at your sole risk. They are provided \"as is.\"  Any material or " +
            "service downloaded or otherwise obtained through the use of the software " +
            "(such as the \"plug-in\" feature) is done at your own discretion and " +
            "risk, and you will be solely responsible for any damage to your computer " +
            "system or loss of data that results from the download and/or use " +
            "of any such material or service.  GonZor, its officers, directors, " +
            "employees, contractors, agents, affiliates, assigns, and GonZor?s " +
            "licensors (collectively ?Associates?) do not represent that the software " +
            "or any data accessed there from is appropriate or available for use " +
            "outside the Australia.\n\nThe Associates expressly disclaim all warranties " +
            "of any kind, whether express or implied, relating to the software " +
            "and any data accessed there from, or the accuracy, timeliness, completeness, " +
            "or adequacy of the software and any data accessed there from, including " +
            "the implied warranties of title, merchantability, satisfactory quality, " +
            "fitness for a particular purpose, and non-infringement.\n\nIf the " +
            "software or any data accessed there from proves defective, you (and " +
            "not the Associates) assume the entire cost of all repairs or injury " +
            "of any kind, even if the Associates have been advised of the possibility " +
            "of such a defect or damages. Some jurisdictions do not allow restrictions " +
            "on implied warranties so some of these limitations may not apply " +
            "to you.\n\n5. \tLimitation of liability.\n\nThe Associates will not " +
            "be liable to you for claims and liabilities of any kind arising out " +
            "of or in any way related to the use of the software by yourself or " +
            "by third parties, to the use or non-use of any brokerage firm or " +
            "dealer, or to the sale or purchase of any security, whether such " +
            "claims and liabilities are based on any legal or equitable theory." +
            "\n\nThe Associates are not liable to you for any and all direct, incidental, " +
            "special, indirect, or consequential damages arising out of or related " +
            "to any third-party software, any data accessed through the software, " +
            "your use or inability to use or access the software, or any data " +
            "provided through the software, whether such damage claims are brought " +
            "under any theory of law or equity. Damages excluded by this clause " +
            "include, without limitation, those for loss of business profits, " +
            "injury to person or property, business interruption, loss of business " +
            "or personal information. Some jurisdictions do not allow limitation " +
            "of incidental or consequential damages so this restriction may not " +
            "apply to you.\n\nInformation provided through the software may be " +
            "delayed, inaccurate, or contain errors or omissions, and the Associates " +
            "will have no liability with respect thereto. GonZor may change or " +
            "discontinue any aspect or feature of the software or the use of all " +
            "or any features or technology in the software at any time without " +
            "prior notice to you, including, but not limited to, content, hours " +
            "of availability.\n\n6.  \tControlling Law.\n\nThis software license " +
            "and the relationship between you and GonZor is governed by the laws " +
            "of Australia without regard to its conflict of law provisions. You " +
            "and GonZor agree to submit to the personal and exclusive jurisdiction " +
            "of the courts located within Australia. The United Nations Convention " +
            "on the International Sale of Goods does not apply to this software " +
            "license.\n\n7.\tPrecedence.\n\nThis software license constitutes the " +
            "entire understanding between the parties respecting use of the software, " +
            "superseding all prior agreements between you and GonZor.\n\n8.\tSurviving " +
            "Provisions.\n\nSections 1, and 3 through 5, will survive any termination " +
            "of this Agreement.\n\n---------------------------------------------------------------------------------" +
            "---\nIf you accept the terms of the agreements, click I Agree to continue. " +
            " You must accept the agreement to download and use the software. ");
        scroll.setBounds(new Rectangle(36, 36, 478, 305));
        this.getContentPane().add(readcheck);
        readcheck.setVisible(false);
       this.getContentPane().add(scroll);
       textscroll = new JScrollPane (scroll, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        textscroll.setBounds(36,36,400,400);
          getContentPane().add( textscroll );
        this.getContentPane().add(background);
      JLabel background = new JLabel();
      JCheckBox readcheck = new JCheckBox();
      JTextArea scroll = new JTextArea();
    }Sorry about all the text for the agreement. I've tried a number of different things I got from searching the forums at different points in the code (setting the number of rows/columns, setting max and min sizes, etc etc) The code above that wraps the text I could have sworn I tried 3 times before it magically worked... I also tried using the awt component for textareas that had the scrollbars built in, but scrapped it after having even more difficulties with that one. I'm trying to get the textbox to only go down about 300 px and 300 px to the right. Using the graphical editor to change it produces a null pointer error at compile time(?!?). Can anyone help me to get the textbox to render as I want it to?
    Edited by: rpk5000 on Jan 27, 2008 9:43 AM

    for instance, boxlayout would work nicely with the installer frame (or dialog)
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    public class InstalleFrame
        public InstalleFrame()
            try
                jbInit();
            catch (Exception ex)
                ex.printStackTrace();
        private JScrollPane textscroll;
        private JPanel contentPane = new JPanel();
        private JLabel background = new JLabel();
        private JCheckBox readcheck = new JCheckBox();
        private JTextArea scroll = new JTextArea();
        private void jbInit() throws Exception
            contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
            contentPane.setBackground(UIManager.getColor("window"));
            contentPane.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
            scroll.setWrapStyleWord(true);
            scroll.setLineWrap(true);
            String text = "Copyright ? 2006-2007 GonZor228.com \n\nBy using or distributing this "
                            + "software (or any work based on the software) you shall be deemed "
                            + "to have accepted the terms and conditions set out below.\n\nGonZor228.com "
                            + "(\"GonZor\") is making this software freely available on the basis "
                            + "that it is accepted as found and that the user checks its fitness "
                            + "for purpose prior to use.\n\nThis software is provided \'as-is\', without "
                            + "any express or implied warranties whatsoever. In no event will the "
                            + "authors, partners or contributors be held liable for any damages, "
                            + "claims or other liabilities direct or indirect, arising from the "
                            + "use of this software.\n\nGonZor will from time to time make software "
                            + "updates available.  However, GonZor accepts no obligation to provide "
                            + "any support to free license holders.\n\nGonZor grants you a limited "
                            + "non-exclusive license to use this software for any purpose that does "
                            + "not violate any laws that apply to your person in your current jurisdiction, "
                            + "subject to the following restrictions: \n\n\nblah, blah, blah,..."
                            + "\n\n";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 5; i++)
                sb.append(text);
            scroll.setText(sb.toString());
            contentPane.add(readcheck);
            contentPane.add(scroll);
            textscroll = new JScrollPane(scroll,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            textscroll.setPreferredSize(new Dimension(400, 400));
            contentPane.add(textscroll);
            JPanel bottomPane = new JPanel();
            bottomPane.setOpaque(false);
            final JButton okButton = new JButton("OK");
            final JButton cancelButton = new JButton("Cancel");
            okButton.setEnabled(false);
            readcheck.setOpaque(false);
            readcheck.setText("I have read and accept the license agreement");
            readcheck.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JCheckBox radioBtn = (JCheckBox)e.getSource();
                    if (radioBtn.isSelected())
                        okButton.setEnabled(true);                   
                    else
                        okButton.setEnabled(false);
            okButton.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    // TODO: whatever needs to be done here
            cancelButton.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    SwingUtilities.getWindowAncestor(contentPane).dispose();
            bottomPane.add(readcheck);
            bottomPane.add(okButton);
            bottomPane.add(cancelButton);
            contentPane.add(bottomPane);
            //readcheck.setVisible(false);
            contentPane.add(background);
        public JPanel getContentPane()
            return contentPane;
        public static void main(String[] args)
            EventQueue.invokeLater(new Runnable()
                public void run()
                    InstalleFrame install = new InstalleFrame();
                    JFrame frame = new JFrame("Install");
                    frame.getContentPane().add(install.getContentPane());
                    frame.setDefaultCloseOperation(3);
                    frame.setSize(550, 400);
                    frame.setUndecorated(false);  //**
                    frame.pack();  //**
                    frame.setLocationRelativeTo(null); //**
                    frame.setVisible(true);
    }

  • I need to control the position and size of each java swing component, help!

    I setup a GUI which include 2 panels, each includes some components, I want to setup the size and position of these components, I use setBonus or setSize, but doesn't work at all. please help me to fix it. thanks
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.FlowLayout;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.event.*;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JTextField;
    import javax.swing.JPanel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.DefaultListModel;
    public class weather extends JFrame {
    private String[] entries={"1","22","333","4444"} ;
    private JTextField country;
    private JList jl;
    private JTextField latitude;
    private JTextField currentTime;
    private JTextField wind;
    private JTextField visibilityField;
    private JTextField skycondition;
    private JTextField dewpoint;
    private JTextField relativehumidity;
    private JTextField presure;
    private JButton search;
    private DefaultListModel listModel;
    private JPanel p1,p2;
    public weather() {
         setUpUIComponent();
    setTitle("Weather Report ");
    setSize(600, 400);
    setResizable(false);
    setVisible(true);
    private void setUpUIComponent(){
         p1 = new JPanel();
    p2 = new JPanel();
         country=new JTextField(10);
         latitude=new JTextField(12);
    currentTime=new JTextField(12);
    wind=new JTextField(12);
    visibilityField=new JTextField(12);
    skycondition=new JTextField(12);
    dewpoint=new JTextField(12);
    relativehumidity=new JTextField(12);
    presure=new JTextField(12);
    search=new JButton("SEARCH");
    listModel = new DefaultListModel();
    jl = new JList(listModel);
    // jl=new JList(entries);
    JScrollPane jsp=new JScrollPane(jl);
    jl.setVisibleRowCount(8);
    jsp.setBounds(120,120,80,80);
    p1.add(country);
    p1.add(search);
    p1.add(jsp);
    p2.add(new JLabel("latitude"));
    p2.add(latitude);
    p2.add(new JLabel("time"));
    p2.add(currentTime);
    p2.add(new JLabel("wind"));
    p2.add(wind);
    p2.add(new JLabel("visibility"));
    p2.add(visibilityField);
    p2.add(new JLabel("skycondition"));
    p2.add(skycondition);
    p2.add(new JLabel("dewpoint"));
    p2.add(dewpoint);
    p2.add(new JLabel("relativehumidity"));
    p2.add(relativehumidity);
    p2.add(new JLabel("presure"));
    p2.add(presure);
    this.getContentPane().setLayout(new FlowLayout());
    this.setLayout(new GridLayout(1,2));
    p2.setLayout(new GridLayout(8, 2));
    this.add(p1);
    this.add(p2);
    public static void main(String[] args) {
    JFrame frame = new weather();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    [http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]
    db

  • JScrollPane not working? Please help

    Hi there,
    I am trying to incorporate a JScrollPane into a JList in my program, basically I make it so that JList is comprised of array of Strings. So the code looks like:
    javax.swing.JPanel          jpanelListSnps            = new javax.swing.JPanel();
    jpanelListSnps.setLayout(new java.awt.BorderLayout());
    String[] stringArray    =  new String[123] //that's the actual amount of elements in the string
    //initializing each elements of array....I will skip that part
    javax.swing.JScrollPane  jscroll  =  new javax.swing.JScrollPane(stringArray);
    jscroll.setPreferredSize(new java.awt.Dimension(30,30));
    jlistSnps.addListSelectionListener(this);
    jpanelListSnps.add(jlistSnps,"West");
    jpanelListSnps.add(jscroll  ,"East");
    jscroll.setAlignmentX(jpanelListSnps.RIGHT_ALIGNMENT);And I see the scrollbar, but I don't think the size is not properly adjusted. Also, I don't see the tab for the scrollbar. I don't know what is wrong with this code. Any suggestions or ideas would be much appreciated. Thank you in advance.
    Regards,
    Young

    JList list = new JList( stringArray );
    JScrollPane scrollPane = new JScrollPane( list );
    panel.add(scrollPane, BorderLayout.EAST);

  • Populating Swing JList using SQL Database

    Sup peeps, im trying to to populate a JList using the entries in a table in a database i created.
    package networks;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.PrintWriter;
    import java.sql.*;
    public class Contestantlist extends javax.swing.JFrame {
        /** Creates new form contestantList */
        public Contestantlist() {
            initComponents();
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
             try
               // Load driver's class, inilialize, register with DriverManager
               //Class.forName("oracle.jdbc.driver.OracleDriver");
               Class.forName("org.gjt.mm.mysql.Driver");
            catch (ClassNotFoundException e)
               System.out.println("Unable to load driver class");
               return;
            ResultSet rs = null;
            try
               // Call DriverManager's methods (all are static)
               // To print log on sysout
               //DriverManager.setLogStream(System.out); //JDBC 1.x driver
              // DriverManager.setLogWriter(new PrintWriter(System.out) );
               // Connect to database.  DriverManager loads each registered driver
               // in turn until one can handle the database URL format
               //Connection con = DriverManager.getConnection(
               //                     "jdbc:oracle:thin:@host.domain.com:1521:db_name"
               //                     ,"scott","tiger");
              // Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
               // Get the DatabaseMetaData object to display database info
            //   DatabaseMetaData dmd = con.getMetaData();
             //  Statement stmt = con.createStatement();
           //     String sql;
             //  sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
              // rs = stmt.executeQuery(sql); //throws SQLExecption if fails
              // printResultSet(rs);
               DriverManager.setLogWriter(new PrintWriter(System.out) );
               Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
               // Get the DatabaseMetaData object to display database info
               DatabaseMetaData dmd = con.getMetaData();
               String sql;
                 Statement stmt = con.createStatement();
             sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
             rs = stmt.executeQuery(sql); //throws SQLExecption if fails
            ResultSetMetaData rsmd = rs.getMetaData();
            int numCols = rsmd.getColumnCount();*
            // Display data, fetching until end of the result set
            // Calling next moves to first or next row and returns true if success
            while(rs.next() )
               // Each rs after next() contains next rows data
               for(final int i=1; i<=numCols; i++)
                  if(i > 1) System.out.print(",");
                  // Almost all SQL types can be cast to a string by JDBC
                 // System.out.print(rs.getString(i));
                  theList.setModel(new javax.swing.AbstractListModel() {
                      String[] strings = { rs.getString(i) };
                      public int getSize() { return strings.length; }
                      public Object getElementAt(int i) { return rs.getString(i); }
               System.out.println("");
            catch(Exception f)
            titleLabel = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
           // theList.setVisibleRowCount(6);
            theList = new javax.swing.JList();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            titleLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
            titleLabel.setText("The Scrupulous Contestants!");
           /* theList.setModel(new javax.swing.AbstractListModel() {
                String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 3", "Item 4", "Item 5", "Item 4", "Item 5"  };
                public int getSize() { return strings.length; }
                public Object getElementAt(int i) { return strings; }
    jScrollPane1.setViewportView(theList);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(70, 70, 70)
    .addComponent(titleLabel))
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addContainerGap(71, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(titleLabel)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(124, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    /* private static void printResultSet(ResultSet rs) throws SQLException
         DriverManager.setLogWriter(new PrintWriter(System.out) );
    Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
    // Get the DatabaseMetaData object to display database info
    DatabaseMetaData dmd = con.getMetaData();
    String sql;
         Statement stmt = con.createStatement();
    sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
    rs = stmt.executeQuery(sql); //throws SQLExecption if fails
    ResultSetMetaData rsmd = rs.getMetaData();
    int numCols = rsmd.getColumnCount();
    // Display data, fetching until end of the result set
    // Calling next moves to first or next row and returns true if success
    while(rs.next() )
    // Each rs after next() contains next rows data
    for(int i=1; i<=numCols; i++)
    if(i > 1) System.out.print(",");
    // Almost all SQL types can be cast to a string by JDBC
    System.out.print(rs.getString(i));
    System.out.println("");
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Contestantlist().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JList theList;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel titleLabel;
    // End of variables declaration
    I can tell that im not using something correctly. Can you guys just point out how i should proceed through this? I encapsulated the piece of code that has got me confused.
    Edited by: 860597 on May 29, 2011 6:29 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    package networks;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.PrintWriter;
    import java.sql.*;
    public class Contestantlist extends javax.swing.JFrame {
        public Contestantlist() {
            initComponents();
        @SuppressWarnings("unchecked")
        private void initComponents() {
             try
               Class.forName("org.gjt.mm.mysql.Driver");
            catch (ClassNotFoundException e)
               System.out.println("Unable to load driver class");
               return;
            try
                 ResultSet rs = null;
               DriverManager.setLogWriter(new PrintWriter(System.out) );
               Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
               DatabaseMetaData dmd = con.getMetaData();
               String sql;
                 Statement stmt = con.createStatement();
             sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
             rs = stmt.executeQuery(sql);
             printResultSet(rs);
            ResultSetMetaData rsmd = rs.getMetaData();
            int numCols = rsmd.getColumnCount();
            catch(Exception f)
            titleLabel = new javax.swing.JLabel();
            jScrollPane2 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            titleLabel.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
            titleLabel.setText("The Scrupulous Contestants!");
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            jScrollPane2.setViewportView(jTable1);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(0, 0, 0)
                            .addComponent(titleLabel))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(0, 0, 0)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 454, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(33, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(titleLabel)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(263, Short.MAX_VALUE))
            pack();
        }// </editor-fold>/ </editor-fold>
        private static void printResultSet(ResultSet rs) throws SQLException
               DriverManager.setLogWriter(new PrintWriter(System.out) );
              Connection con = DriverManager.getConnection("jdbc:mySql://localhost:3306/Contest","root","blink182");
              DatabaseMetaData dmd = con.getMetaData();
              String sql;
                Statement stmt = con.createStatement();
            sql = "SELECT Username FROM Contestant WHERE Username IS NOT NULL";
            rs = stmt.executeQuery(sql); //throws SQLExecption if fails
           ResultSetMetaData rsmd = rs.getMetaData();
           int numCols = rsmd.getColumnCount();
           while(rs.next() )
              for(int i=1; i<=numCols; i++)
                 if(i > 1) System.out.print(",");
                 System.out.print(rs.getString(i));
              System.out.println("");
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Contestantlist().setVisible(true);
        private javax.swing.JList theList;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JLabel titleLabel;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JTable jTable1;
    }I have amended the code and now it does print out the specified contents of my table.
    I have added a a JTable, but excuse my ignorance because i have no idea as to how to proceed from here. I can't figure out how call database entries from the array in the JTable.
    Edited by: 860597 on May 29, 2011 7:27 AM

Maybe you are looking for

  • Receiving SQL Error: INTERNAL_ERROR  while executing the query

    Dear All, I am receiving the below error while executing a query. SQL Error: INTERNAL_ERROR Diagnosis The database system registered an SQL error. As available, the error number and a description are included in the short text. Possible causes for SQ

  • X-Fi with D PLII Movie Mode Speak

    Hi, I have an X-Fi soundcard (Fatalty one) and Logitech Z5500 speakers. They have several modes. When watching movies with a DTS soundtrack or a 5. soundtrack is it best to use the D PLII Movie mode or the 6 channel mode. I also have a mode for music

  • Organizational Structure in OM

    Dear All There are 3 ways of building an Organizational Structure --- Simple Maintenance, Organization and Staffing and Expert Mode. Could anyone let me know how to decide which one to adopt from these and under what scenarios, when it comes to build

  • Getting smaller file sizes

    Hi I'm starting to use Acrobat 3d using large .wrl files from Unigraphics. The .wrl files are about 17 MB and the Acrobat 3d files I'm creating are about 3.5 MB. Is there any way I can reduce the Acrobat 3d file size to create a faster working file?

  • Volume settings for my ipod

    How do you adjust the volume for this ipod? I can't seem to adjust it. Please help.