Re: JScrollPane in Applet




Lukasz wrote:
[cut]

OK. Here's the best I could hack together quickly,
I had not noticed your ..interesting strategy of layout
in the early version.

<sscce>
import java.io.*;
import java.awt.*;
import java.awt.event.*;
// what is this import supposed to do?
import java.*;
import javax.swing.*;
import javax.swing.border.*;

/*
<APPLET
CODE="ShortVersion.class"
WIDTH="1000" HEIGHT="500">
</APPLET>
*/
public class ShortVersion
extends JApplet
implements ActionListener {

// don't mix Swing and AWT unless you can explain why
// (and when) they should -not- be mixed!
JButton button, back;
int op = 0;
JScrollPane scrollPane;
JTable table;
String[] columnNames = {"A", "B", "C"};
int size = 100;
String[][] data = new String[size][3];
BoxLayout bl;
Container c;

public void init() {
c = getContentPane();
bl = new BoxLayout(c, BoxLayout.Y_AXIS);
c.setLayout(bl);

button = new JButton("Click me");
button.addActionListener(this);
// this is not the best way to size
// and layout components!
// instead you should overide the getPreferredSize()
// method and use a layout to position the component
// ..see the layouts section of the Java Tutorial
// button.setBounds(10,90,130,30);
c.add(button);

back = new JButton("Back");
back.addActionListener(this);
// back.setBounds(10, 300, 130, 30);

table = new JTable(data, columnNames);
// note how I 'break' this line to make it shorter
table.setPreferredScrollableViewportSize(
new Dimension(500, 100));
// you should always validate() or pack()
// the layout
validate();
}


public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
c.removeAll();
c.add(back);
op = 1;
// add the scrollpane here!
scrollPane = new JScrollPane(table);
c.add(scrollPane);
// but do not forget to 'validate' the layout.
validate();
repaint();
} else if (e.getSource() == back) {
c.removeAll();
menu();
op = 0;
validate();
repaint();
}
}

public void paint(Graphics g) {
super.paint(g);
if (op == 1) {
try {
int t = 0;
data[t][0] = "text1";
data[t][1] = "text2";
data[t][2] = "text3";
if (t == size) {
String[][] temp = new String[size * 2][3];
System.arraycopy(data, 0, temp, 0, data.length);
data = temp;
temp = null;
}
t++;
} catch (Exception error) {
error.printStackTrace();
g.drawString("Error while querying", 250, 250);
}
c.add(scrollPane);
}
}

public void menu() {
c.add(button);
}
}
</sscce>

Note that each 'level' is indented by two spaces ' ',
rather than an entire 'tab'. This allows a viewer to get
the basic idea of where the brackets line up, but still
makes the code lines fairly short.

HTH

Andrew T.

.