JTabbedPane : JPanel transparent to 2D drawings
Hi.
I am using ptolemy/ptplot package for 2D graphics. I use a JTabbedPane to managae my plots by pages. Each plot is updated continuously by a Thread which get data from a datatbase.
The problem: when a plot is refreshed in a hidden Tab, the plot appears also in the selected Tab. Only
the data points appear, not the axes and the background. Result: I have a supperposition of "undesired
plots" on the selected Tab.
Please some one tell me how to solve this problem ?
N.B.: I don't have a real experience with Java 2D.
Christophe.
Hi.
I have found a workaround : my JTabbedPane now implements ChangeListener and "pauses" the plotting
when a new Tab is selected. Only the plots on the selected Tab are refreshed the other are "paused".
Thanks to hpsmartyz for the reply but I am new to Java2D, and I was not ready to modify the plot
package I am using and implements his solution.
Christophe.
Similar Messages
-
How to make a JPanel transparent? Not able to do it with setOpaque(false)
Hi all,
I am writing a code to play a video and then draw some lines on the video. For that first I am playing the video on a visual component and I am trying to overlap a JPanel for drawing the lines. I am able to overlap the JPanel but I am not able to make it transparent. So I am able to draw lines but not able to see the video. So, I want to make the JPanel transparent so that I can see the video also... I am posting my code below
import javax.media.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.lang.Math;
import javax.media.control.FramePositioningControl;
import javax.media.protocol.*;
import javax.swing.*;
class MPEGPlayer2 extends JFrame implements ActionListener,ControllerListener,ItemListener
Player player;
Component vc, cc;
boolean first = true, loop = false;
String currentDirectory;
int mediatime;
BufferedWriter out;
FileWriter fos;
String filename = "";
Object waitSync = new Object();
boolean stateTransitionOK = true;
JButton bn = new JButton("DrawLine");
MPEGPlayer2 (String title)
super (title);
addWindowListener(new WindowAdapter ()
public void windowClosing (WindowEvent e)
dispose ();
public void windowClosed (WindowEvent e)
if (player != null)
player.close ();
System.exit (0);
Menu m = new Menu ("File");
MenuItem mi = new MenuItem ("Open...");
mi.addActionListener (this);
m.add (mi);
m.addSeparator ();
CheckboxMenuItem cbmi = new CheckboxMenuItem ("Loop", false);
cbmi.addItemListener (this);
m.add (cbmi);
m.addSeparator ();
mi = new MenuItem ("Exit");
mi.addActionListener (this);
m.add (mi);
MenuBar mb = new MenuBar ();
mb.add (m);
setMenuBar (mb);
setSize (500, 500);
setVisible (true);
public void actionPerformed (ActionEvent ae)
FileDialog fd = new FileDialog (this, "Open File",FileDialog.LOAD);
fd.setDirectory (currentDirectory);
fd.show ();
if (fd.getFile () == null)
return;
currentDirectory = fd.getDirectory ();
try
player = Manager.createPlayer (new MediaLocator("file:" +fd.getDirectory () +fd.getFile ()));
filename = fd.getFile();
catch (Exception exe)
System.out.println(exe);
if (player == null)
System.out.println ("Trouble creating a player.");
return;
setTitle (fd.getFile ());
player.addControllerListener (this);
player.prefetch ();
}// end of action performed
public void controllerUpdate (ControllerEvent e)
if (e instanceof EndOfMediaEvent)
if (loop)
player.setMediaTime (new Time (0));
player.start ();
return;
if (e instanceof PrefetchCompleteEvent)
player.start ();
return;
if (e instanceof RealizeCompleteEvent)
vc = player.getVisualComponent ();
if (vc != null)
add (vc);
cc = player.getControlPanelComponent ();
if (cc != null)
add (cc, BorderLayout.SOUTH);
add(new MyPanel());
pack ();
public void itemStateChanged(ItemEvent ee)
public static void main (String [] args)
MPEGPlayer2 mp = new MPEGPlayer2 ("Media Player 2.0");
System.out.println("111111");
class MyPanel extends JPanel
int i=0,j;
public int xc[]= new int[100];
public int yc[]= new int[100];
int a,b,c,d;
public MyPanel()
setOpaque(false);
setBorder(BorderFactory.createLineBorder(Color.black));
JButton bn = new JButton("DrawLine");
this.add(bn);
bn.addActionListener(actionListener);
setBackground(Color.CYAN);
addMouseListener(new MouseAdapter()
public void mouseClicked(MouseEvent e)
saveCoordinates(e.getX(),e.getY());
ActionListener actionListener = new ActionListener()
public void actionPerformed(ActionEvent aae)
repaint();
public void saveCoordinates(int x, int y)
System.out.println("x-coordinate="+x);
System.out.println("y-coordinate="+y);
xc=x;
yc[i]=y;
System.out.println("i="+i);
i=i+1;
public Dimension getPreferredSize()
return new Dimension(500,500);
public void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2D = (Graphics2D)g;
//g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
g2D.setColor(Color.GREEN);
for (j=0;j<i;j=j+2)
g2D.drawLine(xc[j],yc[j],xc[j+1],yc[j+1]);camickr wrote:
"How to Use Layered Panes"
http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html
Add your video component to one layer and your non-opaque panel to another layer.Did you try that with JMF? It does not work for me. As I said, the movie seems to draw itself always on top! -
In the application I am writing I want to allow for some popups on my interface. I am using a JLayeredPane, with two JPanels. The main JPanel, on the default layer, holds all the main components. A second JPanel, at the popup layer, will hold any components which should "pop up".
The layered pane is using a border layout, with both JPanels in the Center.
Unfortunately the bottom panel cannot be seen. It is covered by the top panel, even after I called setOpague(false) on the top panel.
Am I taking the wrong approach? Or is it just not possible to make a JPanel transparent?It should work.I have fiddled around, but have been unable to get this to work. It seems obvious that I'm doing something wrong. :( Below is an example which mimicks my real code, and hopefully is simple enough.
I appreciate any help you can provide.
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class MyPanel extends JPanel
public MyPanel()
setLayout(new BorderLayout());
add(createLayeredPane(), BorderLayout.CENTER);
private JLayeredPane createLayeredPane()
JPanel mainPanel = createMainPanel();
JPanel popupPanel = createPopupPanel();
JLayeredPane pane = new JLayeredPane();
pane.setLayout(new BorderLayout());
pane.add(mainPanel, BorderLayout.CENTER);
pane.add(popupPanel, BorderLayout.CENTER);
pane.setLayer(mainPanel, JLayeredPane.DEFAULT_LAYER.intValue());
pane.setLayer(popupPanel, JLayeredPane.POPUP_LAYER.intValue());
return pane;
private JPanel createMainPanel()
JList list = new JList(new Object[]{"One","Two","Three"});
JButton button = new JButton("Do Nothing");
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(new JScrollPane(list), BorderLayout.CENTER);
panel.add(button, BorderLayout.SOUTH);
return panel;
private JPanel createPopupPanel()
JLabel label = new JLabel("Hello world!");
label.setOpaque(false);
JPanel panel = new JPanel();
panel.setOpaque(false);
panel.add(label);
return panel;
public static void main(String[] args)
MyPanel panel = new MyPanel();
JFrame mainFrame = new JFrame("Testing");
mainFrame.setContentPane(panel);
mainFrame.pack();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.show();
} -
Advice for JPanel transparency idea
Hi!
I've spent all day reading about the CardLayout and JLayeredPane and am confused as to which route to take.
Here's what I'm planning to build:
- One frame containing three panels.
- Each panel holds an invididual image and and stretches to the extents of the frame, thus the panels sit on top of each other.
- I would like to be able to change the order of the panels
- Here's the killer: I'd like to change the transparancy of the top panel (either partially or completely) so that I can peer through to the panel below.
Any advice would be appreciated. Many thanks...To summarise (thanks J_Rooze for advice):
- Setting the AlphaComposite value before calling super.paintComponent(g2) will change the transparency of the whole panel.
- Performance will drop in the order of ~40%, but using J_Rooze's suggestion to force the OpenGL rendering pipeline (above) completely remedies this (is there a similar hack for java3D?? :-).
- Using these panels with JLayeredPane worked completely for my spec (top post).
- I also tried them in CardLayout, however, whilst I could get the top panel to go transparent the underneath panel would not show through. This might not necessarily be a problem for other specs.
- Panels should be .setOpaque(false) to eliminate crazy phasing effects.
Here's my working code for reference:
import java.awt.*;
import javax.swing.JPanel;
public class DisplayPanel extends JPanel{
private boolean antiAlias;
private float alpha = 1.0f;
public DisplayPanel(boolean setAntiAlias) {
antiAlias = setAntiAlias;
this.setOpaque(false);
public void setAlpha(float a) {
alpha = a;
if (alpha > 1) alpha = 1.0f;
if (alpha < 0) alpha = 0.0f;
repaint();
public float getAlpha() {
return alpha;
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getAlpha());
g2.setComposite(ac);
super.paintComponent(g2);
// for speed
g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
if (antiAlias) g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//draw commands go here
}Edited by: .eD on May 7, 2008 4:46 AM -
JPanel Transparency Causes Artifacts
I am working on a battleship game an have a JPanel class which has a transparent color for a background (setBackground(new Color(1f, 1f, 1f, .25f));). When the panel is repainted, lots of artifacts appear and the background is one-half as transparent. Also, the current text is repainted on top of the previous text. I have searched the bug database and found that this is a common issue and can be worked around using setOpaque(false) and overriding paintComponent to paint the background. I did this, but there are still a significant amount of artifacts on the panel. Any ideas? Has anyone else seen this issue before? If so, how did you solve it?
Conditions:
J2SDK1.5.0 Beta1
Windows XP Pro (2 Different Machines)
Here's my paintComponent code:
public void paintComponent(Graphics g)
g.setColor(new Color(1f, 1f, 1f, .25f));
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}Thanks
Blake
[email protected]The artifacts are not caused by paintComponent. I posted it for reference to my second question. Maybe I should have seperated the questions for more clarity.
1. How do I work around the artifact issue?
2. I've read of a custom background painting workaround. Has anyone else heard of it? Did the paintComponent method body I posted in the initial post correctly address this issue?
To answer your question, I initialize no explicit Threads of any kind. I tried, but it made the artifacts worse.
Thanks.
Blake
[email protected] -
Making JPanels transparent changes the look of the frame
Hi,
I wanted to set a background image on my internal frame, which contains more edits and buttons. This was easy, I set the image as background on the frame panel, then made all the JPanels containing elements transparent (=opaque(false)) so that the background is now visible.
Now my problem is that when there is no image to load (or no background wished) the former look of my frame became strage: there are 2 nouances of grey, the old gray from buttons is still there, but the containing panels are in a darker gray then the before. It seems to hang together with the new transparent panels. Setting a background color doesn't seem to help too...Do you have any idea, how could I restore the old "same gray overall" look?
Thanks for helping,
mariaYou may find the answer at the link shown below:
http://java.sun.com/products/jfc/tsc/articles/swing2d/index.html
Without seeing any code, I am guessing that the container's background is showing thru the first transparent component and the next's component's background is being added on top of it.
;o)
V.V. -
Hello!
I have a JFrame with a background painted on it and everything works fine so far, but when I create a JPanel in the JFrame the JPanels grey colour is laying on top of the background. So my question is how to make the JPanel transparent. I read about overriding the paintComponent method, but it didn't work, I'm probably doing something wrong.
This is what I did:
class Transparency extends JPanel {
public Transparency() {}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
contentPanel = new JPanel();
contentPanel.setPreferredSize(new Dimension(mainFrame.getWidth(), 200));
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
contentPanel.add(new Transparency());
mainPanel.add(contentPanel);I would really appreciate some help!Newly created JPanel's have their opacity set to true. This means "I guarantee that I will paint all the pixels within my bounds." For many components this amounts to simply filling in the entire bounds of the component with the background color as the first thing they paint. So by setting the opacity to false the JPanel in question will no longer be a gray blob and will allow any components beneath it to show through.
JPanel#setOpacity(false); The panel in question doesn't even need to be a custom subclass (read: delete that Transparency JPanel subclass). -
Problem with gridbaglayout in JPanel
Hello I am trying to display contact information in three serperate Jpanels on tabbbed panes.I would like to get help in configuring maybe just the pane of void showPane1().I need something like
Searchlb | Combodropname1
firstnamelb | firstnametxt | lastnamelb | lastnametxt
Addresslb addresslb.Horizontal-----------------------*-
citylb | citytxt | statelb | statetxt
postcodelb | postcodetxt | countrylb | countrytxt
emaillb | emailtxt | homephonelb | homephonetxt
faxnumberlb | faxnumbertxt
Other panes have buttons
Here`s the code it operates on login of MSAccess table called persons:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.io.*;
import java.util.Date;
import java.text.NumberFormat;
public class Addressbook extends JFrame{
// Define constant variables
final static String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
final static String url = "jdbc:odbc:addBKTAFE";
final static String login = "LOG-IN";
final static String tab_login = "Log-in";
final static String tab1 = "INQUIRE Personnel Details";
final static String tab2 = "UPDATE/DELETE Personnel Details";
final static String tab3 = "INSERT Personnel Details";
final static String insert = "SAVE RECORD";
final static String update = "UPDATE RECORD";
final static String delete = "DELETE RECORD";
final static String inquire = "INQUIRE RECORD";
final static String clear = " CLEAR ";
final static String relogin = "Log-in failed! Please relog-in!";
final static String norecfound = "No Record Found!";
final static String recinserted = "Record Inserted!";
final static String recupdated = "Record Updated!";
final static String recdeleted = "Record Deleted!";
final static String numericerror = "Age should be numeric!";
final static String information = "INFORMATION";
final static String error = "ERROR";
final static String genexception = "GENERAL EXCEPTION";
final static String sqlexception = "SQL EXCEPTION";
final static String confdelete = "CONFIRM DELETE";
final static String slash = "/";
final static String table1 = "persons";
final static String table2 = "Addresses";
// Events events = new Events(this);
// Define variables for general use
String sql = ""; // Used to store sql statements
int pane_number = 0; // Used to indicate what screen needs to be processed
// like resetting input fields and comboboxes
boolean abort = false;// Used to indicate if error found to avoid further
// processing/validations
// Define container, panels and tabbedpane
Container cntr = getContentPane();
JTabbedPane tpane = new JTabbedPane();
JPanel cbpanel1 , cbpanel2 , cbpanel3,
panel1 , panel2 , panel3;
// Setup constraints and type of layout
GridBagConstraints constraints = new GridBagConstraints();
GridBagConstraints constraints1 = new GridBagConstraints();
GridBagConstraints constraints2 = new GridBagConstraints();
GridBagConstraints constraints3 = new GridBagConstraints();
GridBagLayout layout = new GridBagLayout ();
// Define fonts to be used
Font labelFont = new Font("Arial",Font.PLAIN,12);
Font buttonFont = new Font("Arial",Font.BOLD,13);
// Define labels
JLabel lbUser = new JLabel("Enter User ID: " );
JLabel lbPassword = new JLabel("Enter Password: ");
JLabel lbSelectName = new JLabel("Search Name: " );
JLabel lbFirstName = new JLabel("First Name: " );
JLabel lbLastName = new JLabel("Last Name: " );
JLabel lbAddress = new JLabel("Address: " );
JLabel lbCity = new JLabel("City" );
JLabel lbState = new JLabel("State: " );
JLabel lbPostcode = new JLabel("Postcode" );
JLabel lbCountry = new JLabel("Country" );
JLabel lbEmailAddress = new JLabel("Email Address: " );
JLabel lbHomeNumber = new JLabel("Home Phone No.: " );
JLabel lbFaxNumber = new JLabel("Fax No.: " );
// Define combo boxes in third screen (insert pane)
JComboBox cbName1 = new JComboBox();
JComboBox cbPersonId1 = new JComboBox();
// Define combo boxes in second (update/delete pane)
JComboBox cbName2 = new JComboBox();
JComboBox cbPersonId2 = new JComboBox();
// Define buttons, text fields and password field
JButton btLogin = new JButton (login );
JButton btInsert = new JButton (insert );
JButton btUpdate = new JButton (update );
JButton btDelete = new JButton (delete );
JButton btInquire = new JButton (inquire);
JButton btClear = new JButton (clear );
JPasswordField jpPassword = new JPasswordField(10 );
JTextField tfUser = new JTextField("",10 );
// Inquiry fields on first screen (inquiry pane)
JTextField tfFirstName1 = new JTextField("",30);
JTextField tfLastName1 = new JTextField("",30);
JTextField tfAddress1 = new JTextField("",30);
JTextField tfCity1 = new JTextField("",15);
JTextField tfState1 = new JTextField("",15);
JTextField tfPostcode1 = new JTextField("",30);
JTextField tfCountry1 = new JTextField("",15 );
JTextField tfEmailAddress1 = new JTextField("",30);
JTextField tfHomeNumber1 = new JTextField("",15);
JTextField tfFaxNumber1 = new JTextField("",15 );
// Input fields on second screen (update/delete pane)
JTextField tfFirstName2 = new JTextField("",30);
JTextField tfLastName2 = new JTextField("",30);
JTextField tfAddress2 = new JTextField("",30);
JTextField tfCity2 = new JTextField("",15);
JTextField tfState2 = new JTextField("",15);
JTextField tfPostcode2 = new JTextField("",30);
JTextField tfCountry2 = new JTextField("",15 );
JTextField tfEmailAddress2 = new JTextField("",30);
JTextField tfHomeNumber2 = new JTextField("",15);
JTextField tfFaxNumber2 = new JTextField("",15 );
// Input fields on third screen (insert pane)
JTextField tfFirstName3 = new JTextField("",30);
JTextField tfLastName3 = new JTextField("",30);
JTextField tfAddress3 = new JTextField("",30);
JTextField tfCity3 = new JTextField("",15);
JTextField tfState3 = new JTextField("",15);
JTextField tfPostcode3 = new JTextField("",30);
JTextField tfCountry3 = new JTextField("",15 );
JTextField tfEmailAddress3 = new JTextField("",30);
JTextField tfHomeNumber3 = new JTextField("",15);
JTextField tfFaxNumber3 = new JTextField("",15 );
//------------------------------------------------------------------------------>>>
//-----------------------Start Addressbook()------------------------------------>>>
Addressbook(){
// define listener after adding items to CB to avoid triggering it
// cbName1.addItemListener(new ItemListener());
// public void itemStateChanged(ItemEvent e){
//--------------------------END Addressbook constructor------------------------------------->>>
//------------------------------------------------------------------------------>>>
//------------------------------------------------------------------------------>>>
//--------------------Start setupLoginPanel()----------------------------------->>>
// Setup the login screen
public void setupLoginPanel(){
// set application title
setTitle("Address Book Application");
// center screen
setLocation((Toolkit.getDefaultToolkit().getScreenSize().width
- getWidth())/2,
(Toolkit.getDefaultToolkit().getScreenSize().height
- getHeight())/2);
panel1 = new JPanel();
// set screen border
panel1.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),""));
// add tabbedpane to panel
tpane.addTab(tab_login, panel1);
// add panel to container
cntr.add(tpane);
// setup layout as GridBagLayout
constraints.insets = new Insets(2,2,2,2);
panel1.setLayout(layout);
// setup User ID label in display area
lbUser.setFont(labelFont);
constraints.ipadx = 2;
constraints.ipady = 2;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbUser, constraints);
panel1.add(lbUser);
// setup User ID input field in display area
tfUser.setFont(labelFont);
constraints.ipadx = 2;
constraints.ipady = 2;
constraints.gridx = 1;
constraints.gridy = 0;
constraints.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(tfUser, constraints);
panel1.add(tfUser);
// setup Password label in display area
lbPassword.setFont(labelFont);
constraints.ipadx = 2;
constraints.ipady = 2;
constraints.gridx = 0;
constraints.gridy = 1;
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbPassword, constraints);
panel1.add(lbPassword);
// setup Password input field in display area
jpPassword.setEchoChar('*');
constraints.ipadx = 2;
constraints.ipady = 2;
constraints.gridx = 1;
constraints.gridy = 1;
layout.setConstraints(jpPassword, constraints);
panel1.add(jpPassword);
// setup Login button in display area
btLogin.setFont(buttonFont);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridy = 3;
constraints.gridx = 1;
layout.setConstraints(btLogin, constraints);
panel1.add(btLogin);
// setup login button listener
btLogin.addActionListener(new ButtonHandler());
// allow ALT L to press login button
btLogin.setMnemonic('l');
//--------------------End setupLoginPanel()------------------------------------->>>
//--------------------Start login()--------------------------------------------->>>
// Validate user input from the login screen based on information from login
// table (note: manually create/update your login from table LOGIN).
public void login(){
String user = tfUser.getText();
user = user.trim();
char[] pw = jpPassword.getPassword();
String password = new String(pw).trim();
sql = "SELECT * FROM persons WHERE username='"+
user+"' AND password='"+password+"'";
try{
// load MS Access driver
Class.forName(driver);
}catch(java.lang.ClassNotFoundException ex){
JOptionPane.showMessageDialog(null,ex.getMessage(), error ,
JOptionPane.PLAIN_MESSAGE);
try{
// setup connection to DBMS
Connection conn = DriverManager.getConnection(url);
// create statement
Statement stmt = conn.createStatement();
// execute sql statement
stmt.execute(sql);
ResultSet rs = stmt.getResultSet();
boolean recordfound = rs.next();
if (recordfound){
tpane.removeTabAt(0);
showPane1();
showPane2();
showPane3();
else{
// username/password invalid
JOptionPane.showMessageDialog(null,relogin, error,
JOptionPane.INFORMATION_MESSAGE);
//clear login and password fields
tfUser.setText ("");
jpPassword.setText("");
conn.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage(), genexception,
JOptionPane.INFORMATION_MESSAGE);
//--------------------End login()----------------------------------------------->>>
//--------------------Start showPane1()----------------------------------------->>>
// Setup screen 1(inquiry pane) including labels, input fields, comboboxes.
// Table PERSONS is read to list inquiry parameters.
void showPane1(){
panel1 = new JPanel();
cbpanel1 = new JPanel();
// set screen border
panel1.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),""));
// add tabbedpane to panel
tpane.addTab(tab1, panel1);
// setup layout as GridBagLayout
constraints1.insets = new Insets(2,2,2,2);
panel1.setLayout (layout);
cbpanel1.setLayout (layout);
// setup Name combobox label
lbSelectName.setFont(labelFont);
constraints1.gridx = 0;
constraints1.gridy = 0;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbSelectName, constraints1);
panel1.add(lbSelectName);
// setup Name combobox as search key
cbName1.setFont(labelFont);
constraints1.ipady = 10;
constraints1.gridx = 1;
constraints1.gridy = 0;
constraints1.gridwidth = 3;
constraints1.anchor = GridBagConstraints.WEST;
constraints1.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(cbName1, constraints1);
panel1.add(cbName1);
// setup search combobox (Name and corresponding key)
cbName1.addItem ("Choose one:");
cbPersonId1.addItem("0");
// setup First Name label in display area
lbFirstName.setFont(labelFont);
constraints1.gridx = 0;
constraints1.gridy = 1;
constraints1.anchor = GridBagConstraints.WEST;
constraints1.fill = GridBagConstraints.NONE;
constraints1.gridwidth = 1;
layout.setConstraints(lbFirstName, constraints1);
panel1.add(lbFirstName);
// setup First Name input field in display area
tfFirstName1.setFont(labelFont);
tfFirstName1.setEditable(false);
constraints1.gridx = 1;
constraints1.gridy = 1;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfFirstName1, constraints1);
panel1.add(tfFirstName1);
// setup Last Name label in display area
lbLastName.setFont(labelFont);
constraints1.gridx = 2;
constraints1.gridy = 1;
constraints1.anchor = GridBagConstraints.WEST;
constraints1.fill = GridBagConstraints.NONE;
layout.setConstraints(lbLastName, constraints1);
panel1.add(lbLastName);
// setup Last Name input field in display area
tfLastName1.setFont(labelFont);
tfLastName1.setEditable(false);
constraints1.gridx = 3;
constraints1.gridy = 1;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfLastName1, constraints1);
panel1.add(tfLastName1);
// setup Address label in display area
lbAddress.setFont(labelFont);
constraints1.gridx = 0;
constraints1.gridy = 2;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbAddress, constraints1);
panel1.add(lbAddress);
// setup Address input field in display area
tfAddress1.setFont(labelFont);
tfAddress1.setEditable(false);
constraints1.gridx = 1;
constraints1.gridy = 2;
constraints1.gridwidth = 3;
constraints1.anchor = GridBagConstraints.WEST;
constraints1.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(tfAddress1, constraints1);
panel1.add(tfAddress1);
// setup City label in display area
lbCity.setFont(labelFont);
constraints1.gridx = 0;
constraints1.gridy = 3;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbCity, constraints1);
panel1.add(lbCity);
// setup City input field in display area
tfCity1.setFont(labelFont);
tfCity1.setEditable(false);
constraints1.gridx = 1;
constraints1.gridy = 3;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfCity1, constraints1);
panel1.add(tfCity1);
// setup State label in display area
lbState.setFont(labelFont);
constraints1.gridx = 2;
constraints1.gridy = 3;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbState, constraints1);
panel1.add(lbState);
// setup State input field in display area
tfState1.setFont(labelFont);
tfState1.setEnabled(false);
constraints1.gridx = 3;
constraints1.gridy = 3;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfState1, constraints1);
panel1.add(tfState1);
// setup Postcode label in display area
lbPostcode.setFont(labelFont);
constraints1.gridx = 0;
constraints1.gridy = 4;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbPostcode, constraints1);
panel1.add(lbPostcode);
// setup Address input field in display area
tfPostcode1.setFont(labelFont);
tfPostcode1.setEditable(false);
constraints1.gridx = 1;
constraints1.gridy = 4;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfPostcode1, constraints1);
panel1.add(tfPostcode1);
// setup Country label in display area
lbCountry.setFont(labelFont);
constraints1.gridx = 2;
constraints1.gridy = 4;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbCountry, constraints1);
panel1.add(lbCountry);
// setup Country input field in display area
tfCountry1.setFont(labelFont);
tfCountry1.setEditable(false);
constraints1.gridx = 3;
constraints1.gridy = 4;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfCountry1, constraints1);
panel1.add(tfCountry1);
// setup Email Address label in display area
lbEmailAddress = new JLabel ("Email Address:");
lbEmailAddress.setFont(labelFont);
constraints1.gridx = 0;
constraints1.gridy = 5;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbEmailAddress, constraints1);
panel1.add(lbEmailAddress);
// setup Email Address input field in display area
tfEmailAddress1.setFont(labelFont);
constraints1.gridx = 1;
constraints1.gridy = 5;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfEmailAddress1, constraints1);
panel1.add(tfEmailAddress1);
// setup Home Phone Number label in display area
lbHomeNumber.setFont(labelFont);
constraints1.gridx = 2;
constraints1.gridy = 5;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbHomeNumber, constraints1);
panel1.add(lbHomeNumber);
// setup Home Phone Number input field in display area
tfHomeNumber1.setFont(labelFont);
tfHomeNumber1.setEditable(false);
constraints1.gridx = 3;
constraints1.gridy = 5;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfHomeNumber1, constraints1);
panel1.add(tfHomeNumber1);
// setup Fax Number label in display area
lbFaxNumber.setFont(labelFont);
constraints1.gridx = 0;
constraints1.gridy = 6;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbFaxNumber, constraints1);
panel1.add(lbFaxNumber);
// setup Fax Number input field in display area
tfFaxNumber1.setFont(labelFont);
tfFaxNumber1.setEditable(false);
constraints1.gridx = 1;
constraints1.gridy = 6;
constraints1.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfFaxNumber1, constraints1);
panel1.add(tfFaxNumber1);
// indicate inquiry pane
pane_number = 1;
// read table get the list of names in CB search key
accessDBInit();
// define listener after adding items to CB to avoid triggering it
cbName1.addItemListener(new ComboBoxHandler());
//--------------------End showPane1()------------------------------------------->>>
//--------------------Start showPane2()----------------------------------------->>>
// Setup screen 2(update and delete pane) including labels, input fields,
// comboboxes, and buttons. Table PERSONS is read to list inquiry parameters.
void showPane2(){
panel2 = new JPanel();
cbpanel2 = new JPanel();
labelFont = new Font("Arial",Font.PLAIN,12);
buttonFont = new Font("Arial",Font.BOLD,12);
// set screen border
panel2.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),""));
// add tabbedpane to panel
tpane.addTab(tab2, panel2);
// setup layout as GridBagLayout
constraints2.insets = new Insets(2,2,2,2);
panel2.setLayout (layout);
cbpanel2.setLayout (layout);
// setup Name combobox label
lbSelectName.setFont(labelFont);
constraints2.gridx = 0;
constraints2.gridy = 0;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbSelectName, constraints2);
panel1.add(lbSelectName);
// setup Name combobox as search key
cbName2.setFont(labelFont);
constraints2.ipady = 10;
constraints2.gridx = 1;
constraints2.gridy = 0;
constraints2.gridwidth = 3;
constraints2.anchor = GridBagConstraints.WEST;
constraints2.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(cbName1, constraints2);
panel1.add (cbName1);
// setup search combobox (Name and corresponding key)
cbName1.addItem ("Choose one:");
cbPersonId1.addItem("0");
// setup First Name label in display area
lbFirstName.setFont(labelFont);
constraints2.gridx = 0;
constraints2.gridy = 1;
constraints2.anchor = GridBagConstraints.WEST;
constraints2.fill = GridBagConstraints.NONE;
constraints2.gridwidth = 1;
layout.setConstraints(lbFirstName, constraints2);
panel1.add(lbFirstName);
// setup First Name input field in display area
tfFirstName2.setFont(labelFont);
tfFirstName2.setEditable(false);
constraints2.gridx = 1;
constraints2.gridy = 1;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfFirstName2, constraints2);
panel1.add(tfFirstName2);
// setup Last Name label in display area
lbLastName.setFont(labelFont);
constraints2.gridx = 2;
constraints2.gridy = 1;
constraints2.anchor = GridBagConstraints.WEST;
constraints2.fill = GridBagConstraints.NONE;
layout.setConstraints(lbLastName, constraints2);
panel1.add(lbLastName);
// setup Last Name input field in display area
tfLastName2.setFont(labelFont);
tfLastName2.setEditable(false);
constraints2.gridx = 3;
constraints2.gridy = 1;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfLastName2, constraints2);
panel1.add(tfLastName2);
// setup Address label in display area
lbAddress.setFont(labelFont);
constraints2.gridx = 0;
constraints2.gridy = 2;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbAddress, constraints2);
panel1.add(lbAddress);
// setup Address input field in display area
tfAddress2.setFont(labelFont);
tfAddress2.setEditable(false);
constraints2.gridx = 1;
constraints2.gridy = 2;
constraints2.gridwidth = 3;
constraints2.anchor = GridBagConstraints.WEST;
constraints2.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(tfAddress2, constraints2);
panel1.add(tfAddress2);
// setup City label in display area
lbCity.setFont(labelFont);
constraints2.gridx = 0;
constraints2.gridy = 3;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbCity, constraints2);
panel1.add(lbCity);
// setup City input field in display area
tfCity2.setFont(labelFont);
tfCity2.setEditable(false);
constraints2.gridx = 1;
constraints2.gridy = 3;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfCity2, constraints2);
panel1.add(tfCity2);
// setup State label in display area
lbState.setFont(labelFont);
constraints2.gridx = 2;
constraints2.gridy = 3;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbState, constraints2);
panel1.add(lbState);
// setup State input field in display area
tfState2.setFont(labelFont);
tfState2.setEnabled(false);
constraints2.gridx = 3;
constraints2.gridy = 3;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfState2, constraints2);
panel1.add(tfState2);
// indicate inquiry pane
pane_number = 1;
// setup Address label in display area
lbPostcode.setFont(labelFont);
constraints2.gridx = 0;
constraints2.gridy = 4;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbPostcode, constraints2);
panel1.add(lbPostcode);
// setup Address input field in display area
tfPostcode2.setFont(labelFont);
tfPostcode2.setEditable(false);
constraints2.gridx = 1;
constraints2.gridy = 4;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfPostcode2, constraints2);
panel1.add(tfPostcode2);
// setup Country label in display area
lbCountry.setFont(labelFont);
constraints2.gridx = 2;
constraints2.gridy = 4;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbCountry, constraints2);
panel1.add(lbCountry);
// setup Country input field in display area
tfCountry2.setFont(labelFont);
tfCountry2.setEditable(false);
constraints2.gridx = 3;
constraints2.gridy = 4;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfCountry2, constraints2);
panel1.add(tfCountry2);
// setup Email Address label in display area
lbEmailAddress = new JLabel ("Email Address:");
lbEmailAddress.setFont(labelFont);
constraints2.gridx = 0;
constraints2.gridy = 5;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbEmailAddress, constraints2);
panel1.add(lbEmailAddress);
// setup Email Address input field in display area
tfEmailAddress2.setFont(labelFont);
constraints2.gridx = 1;
constraints2.gridy = 5;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfEmailAddress2, constraints2);
panel1.add(tfEmailAddress2);
// setup Home Phone Number label in display area
lbHomeNumber.setFont(labelFont);
constraints2.gridx = 2;
constraints2.gridy = 5;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbHomeNumber, constraints2);
panel1.add(lbHomeNumber);
// setup Home Phone Number input field in display area
tfHomeNumber2.setFont(labelFont);
tfHomeNumber2.setEditable(false);
constraints2.gridx = 3;
constraints2.gridy = 5;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfHomeNumber2, constraints2);
panel1.add(tfHomeNumber2);
// setup Fax Number label in display area
lbFaxNumber.setFont(labelFont);
constraints2.gridx = 0;
constraints2.gridy = 6;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbFaxNumber, constraints2);
panel1.add(lbFaxNumber);
// setup Fax Number input field in display area
tfFaxNumber2.setFont(labelFont);
tfFaxNumber2.setEditable(false);
constraints2.gridx = 1;
constraints2.gridy = 6;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfFaxNumber2, constraints2);
panel1.add(tfFaxNumber2);
// setup UPDATE button in display area
btUpdate.setFont(buttonFont);
constraints2.gridx = 3;
constraints2.gridy = 7;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(btUpdate, constraints2);
panel2.add(btUpdate);
// setup DELETE button in display area
btDelete.setFont(buttonFont);
constraints2.gridx = 1;
constraints2.gridy = 7;
constraints2.anchor = GridBagConstraints.WEST;
layout.setConstraints(btDelete, constraints2);
panel2.add(btDelete);
btUpdate.addActionListener(new ButtonHandler());
btDelete.addActionListener(new ButtonHandler());
// allow ALT U to press update button
btUpdate.setMnemonic('u');
// allow ALT D to press delete button
btDelete.setMnemonic('d');
// read table get the list of names in combo box search key
accessDBInit();
// define listener after adding items to CB to avoid triggering it
cbName2.addItemListener(new ComboBoxHandler());
//--------------------End showPane2()------------------------------------------->>>
//--------------------Start showPane3()----------------------------------------->>>
// Setup screen 2(insert pane) including labels, input fields, comboboxes,
// and buttons.
void showPane3(){
panel3 = new JPanel();
// set screen border
panel3.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),""));
// add tabbedpane to panel
tpane.addTab(tab3, panel3);
// setup layout as GridBagLayout
constraints3.insets = new Insets(2,2,2,2);
panel3.setLayout (layout);
// setup First Name label in display area
JLabel lbFirstName = new JLabel("First Name:");
lbFirstName.setFont(labelFont);
constraints3.gridx = 0;
constraints3.gridy = 0;
constraints3.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbFirstName, constraints3);
panel3.add(lbFirstName);
// setup First Name input field in display area
tfFirstName3.setFont(labelFont);
constraints3.ipady = 8; // adjust heigth of input field
constraints3.gridx = 1;
constraints3.gridy = 0;
constraints3.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfFirstName3, constraints3);
panel3.add(tfFirstName3);
// setup Last Name label in display area
lbLastName = new JLabel("Last Name: ");
lbLastName.setFont(labelFont);
constraints3.gridx = 2;
constraints3.gridy = 0;
constraints3.anchor = GridBagConstraints.WEST;
layout.setConstraints(lbLastName, constraints3);
panel3.add(lbLastName);
// setup Last Name input field in display area
tfLastName3.setFont(labelFont);
constraints3.gridx = 3;
constraints3.gridy = 0;
constraints3.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfLastName3, constraints3);
panel3.add(tfLastName3);
// setup Middle Name label in display area
lbAddress = new JLabel("Address: ");
lbAddress.setFont(labelFont);
constraints3.gridx = 0;
constraints3.gridy = 1;
constraints3.anchimport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class andy extends JFrame {
// Define constant variables
final static String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
final static String url = "jdbc:odbc:addBKTAFE";
final static String login = "LOG-IN";
final static String tab_login = "Log-in";
final static String tab1 = "INQUIRE Personnel Details";
final static String tab2 = "UPDATE/DELETE Personnel Details";
final static String tab3 = "INSERT Personnel Details";
final static String tab4 = "PRINT";
final static String insert = "SAVE RECORD";
final static String update = "UPDATE RECORD";
final static String delete = "DELETE RECORD";
final static String inquire = "INQUIRE RECORD";
final static String clear = " CLEAR ";
final static String relogin = "Log-in failed! Please relog-in!";
final static String norecfound = "No Record Found!";
final static String recinserted = "Record Inserted!";
final static String recupdated = "Record Updated!";
final static String recdeleted = "Record Deleted!";
final static String numericerror = "Age should be numeric!";
final static String information = "INFORMATION";
final static String error = "ERROR";
final static String genexception = "GENERAL EXCEPTION";
final static String sqlexception = "SQL EXCEPTION";
final static String confdelete = "CONFIRM DELETE";
final static String slash = "/";
final static String table1 = "persons";
final static String table2 = "Addresses";
// Define container, panels and tabbedpane
Container cntr = getContentPane();
JTabbedPane tpane = new JTabbedPane();
JPanel cbpanel1 , cbpanel2 , cbpanel3,
panel1 , panel2 , panel3, panel4;
// Define fonts to be used
Font labelFont = new Font("Arial",Font.PLAIN,12);
Font buttonFont = new Font("Arial",Font.BOLD,13);
// Define labels
JLabel lbUser = new JLabel("Enter User ID: " );
JLabel lbPassword = new JLabel("Enter Password: ");
JLabel lbSelectName = new JLabel("Search Name: " );
JLabel lbFirstName = new JLabel("First Name: " );
JLabel lbLastName = new JLabel("Last Name: " );
JLabel lbAddress = new JLabel("Address: " );
JLabel lbCity = new JLabel("City: " );
JLabel lbState = new JLabel("State: " );
JLabel lbPostcode = new JLabel("Postcode: " );
JLabel lbCountry = new JLabel("Country: " );
JLabel lbEmailAddress = new JLabel("Email Address: " );
JLabel lbHomeNumber = new JLabel("Home Phone No.: " );
JLabel lbFaxNumber = new JLabel("Fax No.: " );
// Define combo boxes in third screen (insert pane)
JComboBox cbName1 = new JComboBox();
JComboBox cbName2 = new JComboBox();
JComboBox cbName3 = new JComboBox();
JComboBox cbPersonId1 = new JComboBox();
JComboBox cbPersonId2 = new JComboBox();
JComboBox cbPersonId3 = new JComboBox();
// Inquiry fields on first screen (inquiry pane)
JTextField tfFirstName1 = new JTextField("",30);
JTextField tfLastName1 = new JTextField("",30);
JTextField tfAddress1 = new JTextField("",30);
JTextField tfCity1 = new JTextField("",15);
JTextField tfState1 = new JTextField("",15);
JTextField tfPostcode1 = new JTextField("",30);
JTextField tfCountry1 = new JTextField("",15 );
JTextField tfEmailAddress1 = new JTextField("",30);
JTextField tfHomeNumber1 = new JTextField("",15);
JTextField tfFaxNumber1 = new JTextField("",15 );
// Input fields on second screen (update/delete pane)
JTextField tfFirstName2 = new JTextField("",30);
JTextField tfLastName2 = new JTextField("",30);
JTextField tfAddress2 = new JTextField("",30);
JTextField tfCity2 = new JTextField("",15);
JTextField tfState2 = new JTextField("",15);
JTextField tfPostcode2 = new JTextField("",30);
JTextField tfCountry2 = new JTextField("",15);
JTextField tfEmailAddress2 = new JTextField("",30);
JTextField tfHomeNumber2 = new JTextField("",15);
JTextField tfFaxNumber2 = new JTextField("",15);
// Input fields on third screen (inset details pane)
JTextField tfFirstName3 = new JTextField("",30);
JTextField tfLastName3 = new JTextField("",30);
JTextField tfAddress3 = new JTextField("",30);
JTextField tfCity3 = new JTextField("",15);
JTextField tfState3 = new JTextField("",15);
JTextField tfPostcode3 = new JTextField("",30);
JTextField tfCountry3 = new JTextField("",15);
JTextField tfEmailAddress3 = new JTextField("",30);
JTextField tfHomeNumber3 = new JTextField("",15);
JTextField tfFaxNumber3 = new JTextField("",15);
GridBagLayout layout = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
public andy() {
super("Address Book Application");
showPane1();
showPane2();
showPane3();
showPane4();
cntr.add(tpane, "Center");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(900,385);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screenSize.width - getWidth())/2,
(screenSize.height - getHeight())/2);
setVisible(true);
// Setup screen 1(inquiry pane) including labels, input fields, comboboxes.
// Table PERSONS is read to list inquiry parameters.
void showPane1() {
panel1 = new JPanel();
cbpanel1 = new JPanel();
// set screen border
panel1.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),""));
// add tabbedpane to panel
tpane.addTab(tab1, panel1);
// setup layout as GridBagLayout
constraints.insets = new Insets(2,2,2,2);
panel1.setLayout (layout);
cbpanel1.setLayout (layout);
// setup Name combobox label
lbSelectName.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
layout.setConstraints(lbSelectName, constraints);
panel1.add(lbSelectName);
// setup Name combobox as search key
cbName1.setFont(labelFont);
constraints.ipady = 10;
constraints.gridwidth = constraints.REMAINDER;
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(cbName1, constraints);
panel1.add(cbName1);
// setup search combobox (Name and corresponding key)
cbName1.addItem ("Choose one:");
cbPersonId1.addItem("0");
// setup First Name label in display area
lbFirstName.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
layout.setConstraints(lbFirstName, constraints);
panel1.add(lbFirstName);
// setup First Name input field in display area
tfFirstName1.setFont(labelFont);
tfFirstName1.setEditable(false);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfFirstName1, constraints);
panel1.add(tfFirstName1);
// setup Last Name label in display area
lbLastName.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(lbLastName, constraints);
panel1.add(lbLastName);
// setup Last Name input field in display area
tfLastName1.setFont(labelFont);
tfLastName1.setEditable(false);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(tfLastName1, constraints);
panel1.add(tfLastName1);
// setup Address label in display area
lbAddress.setFont(labelFont);
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.EAST;
layout.setConstraints(lbAddress, constraints);
panel1.add(lbAddress);
// setup Address input field in display area
tfAddress1.setFont(labelFont);
tfAddress1.setEditable(false);
constraints.gridwidth = constraints.REMAINDER;
constraints.anchor = GridBagConstraints.WEST;
constraints.weightx = 1.0;
constraints.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(tfAddress1, constraints);
panel1.add(tfAddress1);
// setup City label in display area
lbCity.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
constraints.fill = GridBagConstraints.NONE;
layout.setConstraints(lbCity, constraints);
panel1.add(lbCity);
// setup City input field in display area
tfCity1.setFont(labelFont);
tfCity1.setEditable(false);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfCity1, constraints);
panel1.add(tfCity1);
// setup State label in display area
lbState.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(lbState, constraints);
panel1.add(lbState);
// setup State input field in display area
tfState1.setFont(labelFont);
tfState1.setEnabled(false);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(tfState1, constraints);
panel1.add(tfState1);
// setup Postcode label in display area
lbPostcode.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
layout.setConstraints(lbPostcode, constraints);
panel1.add(lbPostcode);
// setup Address input field in display area
tfPostcode1.setFont(labelFont);
tfPostcode1.setEditable(false);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfPostcode1, constraints);
panel1.add(tfPostcode1);
// setup Country label in display area
lbCountry.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(lbCountry, constraints);
panel1.add(lbCountry);
// setup Country input field in display area
tfCountry1.setFont(labelFont);
tfCountry1.setEditable(false);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(tfCountry1, constraints);
panel1.add(tfCountry1);
// setup Email Address label in display area
lbEmailAddress.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
layout.setConstraints(lbEmailAddress, constraints);
panel1.add(lbEmailAddress);
// setup Email Address input field in display area
tfEmailAddress1.setFont(labelFont);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfEmailAddress1, constraints);
panel1.add(tfEmailAddress1);
// setup Home Phone Number label in display area
lbHomeNumber.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(lbHomeNumber, constraints);
panel1.add(lbHomeNumber);
// setup Home Phone Number input field in display area
tfHomeNumber1.setFont(labelFont);
tfHomeNumber1.setEditable(false);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(tfHomeNumber1, constraints);
panel1.add(tfHomeNumber1);
// setup Fax Number label in display area
lbFaxNumber.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
layout.setConstraints(lbFaxNumber, constraints);
panel1.add(lbFaxNumber);
// setup Fax Number input field in display area
tfFaxNumber1.setFont(labelFont);
tfFaxNumber1.setEditable(false);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfFaxNumber1, constraints);
panel1.add(tfFaxNumber1);
// indicate inquiry pane
// pane_number = 1;
// read table get the list of names in CB search key
// accessDBInit();
// define listener after adding items to CB to avoid triggering it
// cbName1.addItemListener(new ComboBoxHandler());
//--------------------End showPane1()------------------------------------------->>>
//--------------------Start showPane2()----------------------------------------->>>
void showPane2() {
panel2 = new JPanel();
cbpanel2 = new JPanel();
// set screen border
panel2.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),""));
// add tabbedpane to panel
tpane.addTab(tab2, panel2);
// setup layout as GridBagLayout
constraints.ipady = 0;
panel2.setLayout (layout);
cbpanel2.setLayout (layout);
// setup Name combobox label
lbSelectName = new JLabel("Search Name: ");
lbSelectName.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
layout.setConstraints(lbSelectName, constraints);
panel2.add(lbSelectName);
// setup Name combobox as search key
cbName2.setFont(labelFont);
constraints.ipady = 10;
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(cbName2, constraints);
panel2.add(cbName2);
// setup search combobox (Name and corresponding key)
cbName2.addItem ("Choose one:");
cbPersonId2.addItem("0");
// setup UPDATE button in display area
JButton btUpdate = new JButton("Update");
btUpdate.setFont(buttonFont);
// btUpdate.addActionListener(new ButtonHandler());
btUpdate.setMnemonic(KeyEvent.VK_U);
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(btUpdate, constraints);
panel2.add(btUpdate);
// setup DELETE button in display area
JButton btDelete = new JButton("Delete");
btDelete.setFont(buttonFont);
// btDelete.addActionListener(new ButtonHandler());
btDelete.setMnemonic(KeyEvent.VK_D);
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(btDelete, constraints);
panel2.add(btDelete);
// setup First Name label in display area
lbFirstName = new JLabel("First Name: ");
lbFirstName.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
layout.setConstraints(lbFirstName, constraints);
panel2.add(lbFirstName);
// setup First Name input field in display area
tfFirstName2.setFont(labelFont);
tfFirstName2.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfFirstName2, constraints);
panel2.add(tfFirstName2);
// setup Last Name label in display area
lbLastName = new JLabel("Last Name: ");
lbLastName.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(lbLastName, constraints);
panel2.add(lbLastName);
// setup Last Name input field in display area
tfLastName2.setFont(labelFont);
tfLastName2.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(tfLastName2, constraints);
panel2.add(tfLastName2);
// setup Address label in display area
lbAddress = new JLabel("Address: ");
lbAddress.setFont(labelFont);
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.EAST;
layout.setConstraints(lbAddress, constraints);
panel2.add(lbAddress);
// setup Address input field in display area
tfAddress2.setFont(labelFont);
tfAddress2.setEditable(true);
constraints.gridwidth = constraints.REMAINDER;
constraints.anchor = GridBagConstraints.WEST;
constraints.weightx = 1.0;
constraints.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(tfAddress2, constraints);
panel2.add(tfAddress2);
// setup City label in display area
lbCity = new JLabel("City: ");
lbCity.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
constraints.fill = GridBagConstraints.NONE;
layout.setConstraints(lbCity, constraints);
panel2.add(lbCity);
// setup City input field in display area
tfCity2.setFont(labelFont);
tfCity2.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfCity2, constraints);
panel2.add(tfCity2);
// setup State label in display area
lbState = new JLabel("State: ");
lbState.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(lbState, constraints);
panel2.add(lbState);
// setup State input field in display area
tfState2.setFont(labelFont);
tfState2.setEnabled(true);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(tfState2, constraints);
panel2.add(tfState2);
// setup Postcode label in display area
lbPostcode = new JLabel("Postcode: ");
lbPostcode.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
layout.setConstraints(lbPostcode, constraints);
panel2.add(lbPostcode);
// setup Address input field in display area
tfPostcode2.setFont(labelFont);
tfPostcode2.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfPostcode2, constraints);
panel2.add(tfPostcode2);
// setup Country label in display area
lbCountry = new JLabel("Country: ");
lbCountry.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(lbCountry, constraints);
panel2.add(lbCountry);
// setup Country input field in display area
tfCountry2.setFont(labelFont);
tfCountry2.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(tfCountry2, constraints);
panel2.add(tfCountry2);
// setup Email Address label in display area
lbEmailAddress = new JLabel ("Email Address: ");
lbEmailAddress.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
layout.setConstraints(lbEmailAddress, constraints);
panel2.add(lbEmailAddress);
// setup Email Address input field in display area
tfEmailAddress2.setFont(labelFont);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfEmailAddress2, constraints);
panel2.add(tfEmailAddress2);
// setup Home Phone Number label in display area
lbHomeNumber = new JLabel("Home Phone No.: ");
lbHomeNumber.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(lbHomeNumber, constraints);
panel2.add(lbHomeNumber);
// setup Home Phone Number input field in display area
tfHomeNumber2.setFont(labelFont);
tfHomeNumber2.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(tfHomeNumber2, constraints);
panel2.add(tfHomeNumber2);
// setup Fax Number label in display area
lbFaxNumber = new JLabel("Fax No.: ");
lbFaxNumber.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
layout.setConstraints(lbFaxNumber, constraints);
panel2.add(lbFaxNumber);
// setup Fax Number input field in display area
tfFaxNumber2.setFont(labelFont);
tfFaxNumber2.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfFaxNumber2, constraints);
panel2.add(tfFaxNumber2);
//-----------------------------End showpane2()---------------------------------->>
//--------------------Start showPane3()----------------------------------------->>>
void showPane3() {
panel3 = new JPanel();
// cbpanel3 = new JPanel();
// set screen border
panel3.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(),""));
// add tabbedpane to panel
tpane.addTab(tab3, panel3);
// setup layout as GridBagLayout
panel3.setLayout(layout);
constraints.ipady = 0;
panel3.setLayout (layout);
// cbpanel3.setLayout (layout);
// setup Name combobox label
lbSelectName = new JLabel("Search Name: ");
lbSelectName.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
layout.setConstraints(lbSelectName, constraints);
panel3.add(lbSelectName);
// setup Name combobox as search key
cbName3 = new JComboBox();
cbName3.setFont(labelFont);
constraints.ipady = 10;
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(cbName3, constraints);
panel3.add(cbName3);
// setup search combobox (Name and corresponding key)
cbName3.addItem ("Choose one:");
cbPersonId3.addItem("0");
// setup INSERT button in display area
JButton btInsert = new JButton("Insert");
btInsert.setFont(buttonFont);
// btInsert.addActionListener(new ButtonListener());
btInsert.setMnemonic(KeyEvent.VK_S);
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(btInsert, constraints);
panel3.add(btInsert);
// setup CLEAR button in display area
JButton btClear = new JButton("Clear");
btClear.setFont(buttonFont);
// btClear.addActionListener(new ButtonListener());
btClear.setMnemonic(KeyEvent.VK_C);
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(btClear, constraints);
panel3.add(btClear);
// setup First Name label in display area
lbFirstName = new JLabel("First Name: ");
lbFirstName.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
layout.setConstraints(lbFirstName, constraints);
panel3.add(lbFirstName);
// setup First Name input field in display area
tfFirstName3.setFont(labelFont);
tfFirstName3.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfFirstName3, constraints);
panel3.add(tfFirstName3);
// setup Last Name label in display area
lbLastName = new JLabel("Last Name: ");
lbLastName.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(lbLastName, constraints);
panel3.add(lbLastName);
// setup Last Name input field in display area
tfLastName3.setFont(labelFont);
tfLastName3.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(tfLastName3, constraints);
panel3.add(tfLastName3);
// setup Address label in display area
lbAddress = new JLabel("Address: ");
lbAddress.setFont(labelFont);
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.EAST;
layout.setConstraints(lbAddress, constraints);
panel3.add(lbAddress);
// setup Address input field in display area
tfAddress3.setFont(labelFont);
tfAddress3.setEditable(true);
constraints.gridwidth = constraints.REMAINDER;
constraints.anchor = GridBagConstraints.WEST;
constraints.weightx = 1.0;
constraints.fill = GridBagConstraints.HORIZONTAL;
layout.setConstraints(tfAddress3, constraints);
panel3.add(tfAddress3);
// setup City label in display area
lbCity = new JLabel("City: ");
lbCity.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
constraints.fill = GridBagConstraints.NONE;
layout.setConstraints(lbCity, constraints);
panel3.add(lbCity);
// setup City input field in display area
tfCity3.setFont(labelFont);
tfCity3.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfCity3, constraints);
panel3.add(tfCity3);
// setup State label in display area
lbState = new JLabel("State: ");
lbState.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(lbState, constraints);
panel3.add(lbState);
// setup State input field in display area
tfState3.setFont(labelFont);
tfState3.setEnabled(true);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(tfState3, constraints);
panel3.add(tfState3);
// setup Postcode label in display area
lbPostcode = new JLabel("Postcode: ");
lbPostcode.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
layout.setConstraints(lbPostcode, constraints);
panel3.add(lbPostcode);
// setup Address input field in display area
tfPostcode3.setFont(labelFont);
tfPostcode3.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfPostcode3, constraints);
panel3.add(tfPostcode3);
// setup Country label in display area
lbCountry = new JLabel("Country: ");
lbCountry.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(lbCountry, constraints);
panel3.add(lbCountry);
// setup Country input field in display area
tfCountry3.setFont(labelFont);
tfCountry3.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(tfCountry3, constraints);
panel3.add(tfCountry3);
// setup Email Address label in display area
lbEmailAddress = new JLabel ("Email Address: ");
lbEmailAddress.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
layout.setConstraints(lbEmailAddress, constraints);
panel3.add(lbEmailAddress);
// setup Email Address input field in display area
tfEmailAddress3.setFont(labelFont);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfEmailAddress3, constraints);
panel3.add(tfEmailAddress3);
// setup Home Phone Number label in display area
lbHomeNumber = new JLabel("Home Phone No.: ");
lbHomeNumber.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = constraints.RELATIVE;
layout.setConstraints(lbHomeNumber, constraints);
panel3.add(lbHomeNumber);
// setup Home Phone Number input field in display area
tfHomeNumber3.setFont(labelFont);
tfHomeNumber3.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(tfHomeNumber3, constraints);
panel3.add(tfHomeNumber3);
// setup Fax Number label in display area
lbFaxNumber = new JLabel("Fax No.: ");
lbFaxNumber.setFont(labelFont);
constraints.anchor = GridBagConstraints.EAST;
constraints.gridwidth = 1;
layout.setConstraints(lbFaxNumber, constraints);
panel3.add(lbFaxNumber);
// setup Fax Number input field in display area
tfFaxNumber3.setFont(labelFont);
tfFaxNumber3.setEditable(true);
constraints.anchor = GridBagConstraints.WEST;
layout.setConstraints(tfFaxNumber3, constraints);
panel3.add(tfFaxNumber3);
//-----------------------------End showpane3()---------------------------------->>
//-----------------------------Start showPane4()-------------------------------->>
void showPane4() {
// qtm = new QueryTableModel();
// JTable table = new JTable(qtm);
// String query = "SELECT FirstName, LastName, HomePhone, " +
// "FROM Addresses ORDER By LastName";
// qtm.setQuery(query);
JPanel demoPanel = new JPanel();
demoPanel.setPreferredSize(new Dimension(400,500));
demoPanel.setBackground(Color.pink);
demoPanel.add(new JLabel("Demo Panel in place of table",
SwingConstants.CENTER));
JScrollPane scrollPane = new JScrollPane(demoPanel);
panel4 = new JPanel();
// pane_number = 4;
panel4.setLayout(layout);
constraints.ipady = 0;
// labelFont = new Font("Arial", Font.PLAIN, 12); defined above
buttonFont = new Font("Arial", Font.PLAIN, 13);
// set screen border
panel4.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), ""));
// add panel to tabbed pane
tpane.addTab(tab4, panel4);
JLabel lbPrint = new JLabel("Print");
lbPrint.setFont(labelFont);
constraints.anchor = constraints.EAST;
layout.setConstraints(lbPrint, constraints);
panel4.add(lbPrint);
JButton btPrint = new JButton("Print");
btPrint.setFont(buttonFont);
// btPrint.addActionListener(new ButtonListener());
btPrint.setMnemonic(KeyEvent.VK_P);
constraints.anchor = constraints.WEST;
constraints.gridwidth = constraints.REMAINDER;
layout.setConstraints(btPrint, constraints);
panel4.add(btPrint);
constraints.weighty = 1.0;
constraints.fill = constraints.BOTH;
constraints.anchor = constraints.CENTER;
layout.setConstraints(scrollPane, constraints);
panel4.add(scrollPane);
public static void main(String[] args) {
new andy();
} -
Given the FileTableDemo from the Java Foundation Class in a Nutshell book.(O'Reilly) Chapter 3 page 51 in my addition.
I have modified the example to place the JTable in a JTabbedPane. Now when the window (JFrame) is resized by the user the JTable no longer resizes. How do I passing the "resizing" into the component (JTable) placed in the JTabbedPane?
Here is the code: My deviation from the example is enclosed in "///////////KBS" and of course the line frame.getContentPane().add(myTP, "Center"); where "pane" has been replaced with "myTP"
Thanks Brad
import javax.swing.*;
import javax.swing.table.*;
import java.io.File;
import java.util.Date;
public class FileTableDemo
public static void main(String[] args)
// Figure out what directory to display
File dir;
if (args.length > 0)
dir = new File(args[0]);
else
dir = new File(System.getProperty("user.home"));
// Create a TableModel object to represent the contents of the directory
FileTableModel model = new FileTableModel(dir);
// Create a JTable and tell it to display our model
JTable table = new JTable(model);
JScrollPane pane = new JScrollPane(table);
pane.setBorder(BorderFactory.createEmptyBorder(60,20,20,20));
////////KBS
JTabbedPane myTP = new JTabbedPane();
JPanel myOne = new JPanel();
JPanel myTwo = new JPanel();
myOne.add(pane);
myTP.add("One", myOne);
myTP.add("Two", myTwo);
////////KBS
// Display it all in a scrolling window and make the window appear
JFrame frame = new JFrame("FileTableDemo");
frame.getContentPane().add(myTP, "Center");
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
// The methods in this class allow the JTable component to get
// and display data about the files in a specified directory.
// It represents a table with six columns: filename, size, modification date,
// plus three columns for flags: direcotry, readable, writable
class FileTableModel extends AbstractTableModel
protected File dir;
protected String[] filenames;
protected String[] columnNames = new String[] {
"name",
"size",
"last modified",
"directory?",
"readable?",
"writable?"
protected Class[] columnClasses = new Class[] {
String.class,
Long.class,
Date.class,
Boolean.class,
Boolean.class,
Boolean.class
// This table model works for any one given directory
public FileTableModel(File dir)
this.dir = dir;
this.filenames = dir.list();
// These are easy methods
public int getColumnCount()
return 6;
public int getRowCount()
return filenames.length;
// Information about each column
public String getColumnName(int col)
return columnNames[col];
public Class getColumnClass(int col)
return columnClasses[col];
// The method that must actually return the value of each cell
public Object getValueAt(int row, int col)
File f = new File(dir, filenames[row]);
switch(col)
case 0: return filenames[row];
case 1: return new Long(f.length());
case 2: return new Date(f.lastModified());
case 3: return f.isDirectory() ? Boolean.TRUE : Boolean.FALSE;
case 4: return f.canRead() ? Boolean.TRUE : Boolean.FALSE;
case 5: return f.canWrite() ? Boolean.TRUE : Boolean.FALSE;
default: return null;
}Well, I didn't find an answer but I did find a solution.
The JPanel is the problem. I use it to help with layout which is not obvious in this example.
As you can see in the code the JTable is placed in a JScrollPane which is place in a JPanel which is placed in a JTabbedPane.
If I use Box instead of JPanel the JTable in the JScrollPane in the Box in the TabbedPane in the JFrame resizes correclty.
So although JPanel is resizable with setSize it does not get resized when it's JFrame gets resized.
I would still like to know why?
////////KBS
JTabbedPane myTP = new JTabbedPane();
Box myOne = Box.createHorizontalBox();
Box myTwo = Box.createHorizontalBox();
myOne.add(pane);
myTP.add("One", myOne);
myTP.add("Two", myTwo);
////////KBS -
In my project, I build a dialog box. I build a JTabbedPane within. Each tab is a panel with JChecxBox. When I add my first panel using the method addTab() no problem, with my second panel still no problem. When I try adding a third, an exception occurs: java.lang.ArrayIndexOutOfBoundsException: 2>1
I have also used the method printStackTrace to know what's going on:
java.lang.ArrayIndexOutOfBoundsException: 2 > 1
at java.util.Vector.insertElementAt(Vector.java:551)
at javax.swing.JTabbedPane.insertTab(JTabbedPane.java:441)
at javax.swing.JTabbedPane.addTab(JTabbedPane.java:512)
at myprojects.hopital.Cl�sComp.<init>(Cl�sComp.java:113)
at myprojects.hopital.Hopital$1$MenuAction.actionPerformed(Hopital.java:72)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1450)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1504)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:378)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:250)
at javax.swing.AbstractButton.doClick(AbstractButton.java:279)
at javax.swing.plaf.basic.BasicMenuItemUI$MouseInputHandler.mouseReleased(BasicMenuItemUI.java:886)
at java.awt.Component.processMouseEvent(Component.java:3717)
at java.awt.Component.processEvent(Component.java:3546)
at java.awt.Container.processEvent(Container.java:1164)
at java.awt.Component.dispatchEventImpl(Component.java:2595)
at java.awt.Container.dispatchEventImpl(Container.java:1213)
at java.awt.Component.dispatchEvent(Component.java:2499)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:2451)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2216)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2125)
at java.awt.Container.dispatchEventImpl(Container.java:1200)
at java.awt.Window.dispatchEventImpl(Window.java:912)
at java.awt.Component.dispatchEvent(Component.java:2499)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:319)
at java.awt.EventDispatchThread.pumpOneEvent(EventDispatchThread.java:103)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:84)
It seems that addTab call insertTab calling himself insertElementAt which throw this exception? I don't understand what's going on. Here my code for my DialogBox:
package myprojects.hopital;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.util.*;
//import java.lang.*;
public class Cl�sComp extends JDialog {
Comparateur[] cl�s;
int nbCl�s;
boolean ok;
JCheckBox jcbAdd;
JCheckBox jcbMoy;
JCheckBox jcbM�d;
JCheckBox jcbEct;
JCheckBox jcbSamj;
JCheckBox jcbAll;
JCheckBox jcbProv;
JCheckBox jcbTadm;
JCheckBox jcbTpat;
JCheckBox jcbAmoy;
JCheckBox jcbAmed;
JCheckBox jcbAect;
JCheckBox jcbVobsinf;
public Cl�sComp(){
super((JFrame)null,"Choix des cl�s de comparaisons",true);
Container contentPane=getContentPane();
//setLayout(new GridBagLayout());
nbCl�s=0;
cl�s=new Comparateur[10];
class ButtonAction implements ActionListener
public void actionPerformed(ActionEvent e) {
String commande;
commande=e.getActionCommand();
if (commande.compareTo("Cancel")==0){
hide();
if (commande.compareTo("OK")==0){
if (jcbAdd.isSelected()) {
Comparateur c=new Comparateur(1);
addCl�(c);
ok=true;
if (jcbMoy.isSelected()) {
Comparateur c=new CompMoy(0);
addCl�(c);
ok=true;
if (jcbM�d.isSelected()) {
Comparateur c=new CompMed(0);
addCl�(c);
ok=true;
if (jcbEct.isSelected()) {
Comparateur c=new CompET(0);
addCl�(c);
ok=true;
if (jcbSamj.isSelected()) {
Comparateur c=new CompSAMJ(0);
addCl�(c);
ok=true;
hide();
JTabbedPane jtpMisc=new JTabbedPane();
JPanel jpCheckBox=new JPanel(new GridLayout(2,2));
jcbAdd=new JCheckBox("Nombre");
jcbMoy=new JCheckBox("Moyenne");
jcbM�d=new JCheckBox("M�diane");
jcbEct=new JCheckBox("Ecart-type");
jcbSamj=new JCheckBox("Sapi activit� moyenne");
jcbAll=new JCheckBox("Tout");
jcbProv=new JCheckBox("Provenance");
jcbTadm=new JCheckBox("Type d'admission");
jcbTpat=new JCheckBox("Type de pathologie");
jcbAmoy=new JCheckBox("Moyenne");
jcbAmed=new JCheckBox("M�diane");
jcbAect=new JCheckBox("Ecart-Type");
jpCheckBox.add(jcbAdd);
jpCheckBox.add(jcbMoy);
jpCheckBox.add(jcbM�d);
jpCheckBox.add(jcbEct);
jpCheckBox.add(jcbSamj);
jtpMisc.addTab("Divers",null,jpCheckBox,"C'est compl�tement foireux");
jtpMisc.setSelectedIndex(0);
JPanel jpParamPhys=new JPanel();
jcbVobsinf=new JCheckBox("Valeur obs. inf.");
jpParamPhys.add(jcbVobsinf);
jtpMisc.addTab("Param�tres physiologiques",jpParamPhys);
JPanel jpActivit�s=new JPanel();
jpActivit�s.add(jcbProv);
JPanel jpSapiSev=new JPanel();
jpSapiSev.add(jcbTpat);
JPanel jpSapiAct=new JPanel();
jpSapiAct.add(jcbTadm);
try{ jtpMisc.addTab("Activit�s",jpParamPhys);
// jtpMisc.addTab("SAPI-SEVERITE",jpParamPhys);
// jtpMisc.addTab("SAPI-ACTIVITE",jpParamPhys);
catch(Exception e){
System.out.println(e.toString());
System.out.println(e.getMessage());
System.out.println(e.getLocalizedMessage());
try{e.printStackTrace(new PrintStream(new FileOutputStream("c:\\Beno�t\\error.txt")));}
catch(Exception exc){System.out.println("Encore une exception, putain");}
ButtonAction bAction=new ButtonAction();
JPanel jpButton=new JPanel(new GridLayout(1,2));
JButton jbOk=new JButton("OK");
JButton jbCancel=new JButton("Cancel");
jpButton.add(jbOk);
jpButton.add(jbCancel);
jbCancel.addActionListener(bAction);
jbOk.addActionListener(bAction);
contentPane.add(jpButton,BorderLayout.SOUTH);
contentPane.add(jtpMisc,BorderLayout.CENTER);
// contentPane.add(jpCheckBox,BorderLayout.CENTER);
setSize(500,400);
setLocation(200,150);
public Comparateur getCl�(int index){
return cl�s[index];
public boolean ok(){
return ok;
public int getNbCl�s(){
return nbCl�s;
public void addCl�(Comparateur c){
nbCl�s++;
cl�s[nbCl�s-1]=c;
}Conceptually wrong.
Hints: every tab in a JTabbedPane is a JPanel in fact. -
Doubt in JTabbedPane ..
Hi,
I am having a JTabbedPane and using the following code to add Panels to JTabbedPane.
public class IntegratedUI extends JPanel{
public IntegratedUI() {
JTabbedPane tabbedPane = new JTabbedPane();
JPanel usagepanel = UsageConsole.makeFrame();
tabbedPane.addTab("UsageConsole",usagepanel);
tabbedPane.setSelectedIndex(0);
JPanel deploymentpanel =Generator.makedeploymentFrame();
tabbedPane.addTab("Deployment",deploymentpanel);
JPanel generatorpanel =WGenarator.makegeneratorFrame();
tabbedPane.addTab("Generator",generatorpanel);
setLayout(new GridLayout(1,1));
add(tabbedPane);
public static void main(String[] args) {
JFrame frame = new JFrame("XYZ");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
frame.getContentPane().add(new IntegratedUI()
frame.setBounds(0,0,800,400);
frame.setVisible(true);
My JTabbedPane is displaying fine but my first Panel USageConsole is getting displayed.My second and third panel is not getting displayed.While i tried to debug using breakpoints.its calling the first class fine.The second and third class is not getting called.What could be the problem..
Thanks for your reply in advance.It looks like your Generator and WGenerator classes have static methods that are supposed to return JPanels, hopefully with components on them. I would write a small test app to verify that you can show these on their own; say, add each one to a JPanel with GridBagLayout, one panel per row. This way you can really see what's going on. I don't see any obvious problems in your tabbed pane code.
-
JTabbedPane, JPane PROBLEM
Hi!, I have a several problem with JApplet, this is the code:
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
import java.awt.*;
public class NuevoApplet extends JApplet{
JMenuBar menuBar;
JMenu menuArchivo, submenu;
JMenuItem menuNuevo;
JTabbedPane Tabbed1 = new JTabbedPane();
JPanel Panel = new JPanel();
class EventHandler implements ActionListener
public void actionPerformed(ActionEvent e)
//Si se elige salir en el menu
if (e.getSource() == menuNuevo)
CreaTab();
ActionListener eventHandler = new EventHandler();
public void start(){}
public void init () {
try {
UIManager.setLookAndFeel(new com.sun.java.swing.plaf.windows.WindowsLookAndFeel());
} catch (Exception e) { }
Panel.setBorder(BorderFactory.createEtchedBorder());
Panel.setLayout(new java.awt.BorderLayout());
this.Panel.updateUI();
this.setContentPane(this.Panel);
this.CreaMenus();
this.getContentPane().add(this.Tabbed1,java.awt.BorderLayout.CENTER);
initConnections();
private void CreaMenus(){
//Creamos la barra de men�s
menuBar = new JMenuBar();
this.setJMenuBar(menuBar);
//Creamos el men� de Archivo
menuArchivo = new JMenu("Archivo");
menuBar.add(menuArchivo);
//Creamos los elementos del men� archivo
menuNuevo = new JMenuItem("Abrir Archivo *.hex");
menuArchivo.add(menuNuevo);
public void initConnections()
//se suscriben todas las componentes que quieren escuchar los eventos
menuNuevo.addActionListener(eventHandler);
public void CreaTab(){
JPanel a = new JPanel();
Entorno1 b = new Entorno1();
a.add(new JButton("BOTON1"),java.awt.BorderLayout.CENTER);
a.add(new JButton("BOTON2"),java.awt.BorderLayout.EAST);
this.Tabbed1.addTab("Primera Pesta�a", b); --> PROBLEM, not insert the JPanel b extends Entorno1
b.repaint();
Tabbed1.invalidate();
Tabbed1.getParent().invalidate();
Tabbed1.validate();
Tabbed1.repaint();
this.Tabbed1.updateUI();
/*this.Tabbed1.validate();
this.Tabbed1.updateUI();
this.Tabbed1.revalidate();*/
public class Entorno1 extends JPanel{
public void Entorno1(){
setLayout(new BorderLayout());
Border raisedBevel = BorderFactory.createRaisedBevelBorder();
Border loweredBevel = BorderFactory.createLoweredBevelBorder();
Border compound = BorderFactory.createCompoundBorder
(raisedBevel, loweredBevel);
this.setBorder(compound);
this.add(new JButton("Boton1"),java.awt.BorderLayout.CENTER);
this.add(new JButton("Boton2"),java.awt.BorderLayout.EAST);
this.updateUI();
this.setVisible(true);
this.revalidate();
this.repaint();
} //Fin de la clase Applet16F84
When I use b extends Entorno1 and I insert as JPanel of JTabbedPane, not show it.
this.Tabbed1.addTab("Primera Pesta�a", b);
But this yes show it:
this.Tabbed1.addTab("Primera Pesta�a", a);
Why ? ..
Thanks !Your constructor is actually a method and not a constructor.
Therefore calling new Entorno1() returns you a blank panel.
change this
public void Entorno1(){
...to this.
public Entorno1(){that should do it..
nes -
How to switch between pages in a JTabbedPane
I hava form with a JTabbedPane whit 5 "pages" om page 1 there is a button that when pressed i want to switch to page 5 and display that content
I have tried the setSelectedIndex method but i does not work.. Any tips?How about the source code?
It must be buggy somewhere! There is no problem with those methods in my example.
Try this one:
package tabs;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
* <p>�berschrift: </p>
* <p>Beschreibung: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Organisation: </p>
* @author Florian Fray
* @version 1.0
public class TabExample extends JFrame {
private JPanel root = new JPanel();
JTabbedPane jTabbedPane1 = new JTabbedPane();
JPanel jPanel1 = new JPanel();
JButton jButton1 = new JButton();
JPanel jPanel2 = new JPanel();
JButton jButton2 = new JButton();
FlowLayout flowLayout1 = new FlowLayout();
public TabExample() throws HeadlessException {
try {
jbInit();
pack();
show();
catch(Exception e) {
e.printStackTrace();
public static void main(String[] args) throws HeadlessException {
TabExample tabExample1 = new TabExample();
private void jbInit() throws Exception {
setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
this.setState(Frame.NORMAL);
this.setTitle("Tabbing around");
setContentPane(root);
jButton1.setText("to Tab 2");
jButton1.addActionListener(new TabExample_jButton1_actionAdapter(this));
jButton2.setText("back to Tab 1");
jButton2.addActionListener(new TabExample_jButton2_actionAdapter(this));
jTabbedPane1.setMinimumSize(new Dimension(155, 83));
jTabbedPane1.setPreferredSize(new Dimension(155, 83));
root.add(jTabbedPane1, null);
jTabbedPane1.add(jPanel1, "jPanel1");
jPanel1.add(jButton1, null);
jTabbedPane1.add(jPanel2, "jPanel2");
jPanel2.add(jButton2, null);
void jButton1_actionPerformed(ActionEvent e) {
jTabbedPane1.setSelectedIndex(1);
void jButton2_actionPerformed(ActionEvent e) {
jTabbedPane1.setSelectedIndex(0);
class TabExample_jButton1_actionAdapter implements java.awt.event.ActionListener {
TabExample adaptee;
TabExample_jButton1_actionAdapter(TabExample adaptee) {
this.adaptee = adaptee;
public void actionPerformed(ActionEvent e) {
adaptee.jButton1_actionPerformed(e);
class TabExample_jButton2_actionAdapter implements java.awt.event.ActionListener {
TabExample adaptee;
TabExample_jButton2_actionAdapter(TabExample adaptee) {
this.adaptee = adaptee;
public void actionPerformed(ActionEvent e) {
adaptee.jButton2_actionPerformed(e);
} -
Strangeness Using HTML with JTabbedPane
I'm getting some weird behavior when using html format for a JTabbedPane. It seems when I create tabs using HTML, it works fine, but when I subsequently try to change the tab title using JTabbedPane.setTitleAt(), the title doesn't change. The title doesn't change only when I create it with html. If I use "normal" text, the title changes fine.
I imagine JTabbedPane has a problem with html. I am using version 1.3 and compiling with JBuilder. Below is an example of my program. Uncomment mentioned lines to see it react strangely.
Any help would be appreciated.
-joel
package junk;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BugExample extends JFrame {
BugExample() {
super( "Bug Example" );
JTabbedPane tabs = new JTabbedPane();
JPanel aPan= new JPanel();
//html for tab index 0
tabs.addTab("<html><center><font face=\"Dialog\" size = -1><b>Rate 1: " +
"<font color=#008040>5.6%</b></font></font></center></html>", new JPanel());
//"Normal" text for tab index 0. If I use this, then the setTitleAt works
// properly. To try this, make sure the previous addTab() is commented out
// tabs.addTab("Rate 1:5.7%", new JPanel());
//html for tab index 1
tabs.addTab("<html><center><font face=\"Dialog\" size = -1><b>Rate 2: " +
"<font color=#008040>9.2%</b></font></font></center></html>", new JPanel());
getContentPane().add(tabs);
//Uncomment next line and run again using the html style addTab() for index 0.
// I would think the tab at index 0 would show this new text
// In fact, it will if I do not use html for index 1.
// tabs.setTitleAt(0, "Rate it again");
setSize( 400, 220 );
public static void main(String[] args) {
BugExample frame = new BugExample();
frame.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
System.exit(0);
System.err.println("Starting");
frame.setVisible(true);import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BugExample extends JFrame {
BugExample() {
super( "Bug Example" );
JTabbedPane tabs = new JTabbedPane();
JPanel aPan= new JPanel();
//html for tab index 0
tabs.addTab("<html><center><font face=\"Dialog\" size = -1><b>Rate 1: <font color=#008040>5.6%</b></font></font></center></html>", new JPanel());
//"Normal" text for tab index 0. If I use this, then the setTitleAt works
// properly. To try this, make sure the previous addTab() is commented out
// tabs.addTab("Rate 1:5.7%", new JPanel());
//html for tab index 1
tabs.addTab("<html><center><font face=\"Dialog\" size = -1><b>Rate 2: <font color=#008040>9.2%</b></font></font></center></html>", new JPanel());
getContentPane().add(tabs);
//Uncomment next line and run again using the html style addTab() for index 0.
// I would think the tab at index 0 would show this new text
// In fact, it will if I do not use html for index 1.
tabs.setTitleAt(0, "Rate it again");
setSize( 400, 220 );
public static void main(String[] args) {
BugExample frame = new BugExample();
frame.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
System.exit(0);
System.err.println("Starting");
frame.setVisible(true); -
Tab key event not fired in JTabbedPane
Hello,
I wanted to add the functionality of moving between tabs when Ctrl+Tab is pressed like Windows tabs.
But the tab key listener event is not getting fired by pressing Tab. For all the other key pushes it is working good. It this a problem with Java? Any workarounds?
Here is the sample code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TestTab extends JFrame
public void drawGUI()
//getContentPane().setLayout(new GridLayout(1, 1));
JTabbedPane lTabbedPane = new JTabbedPane();
JPanel lFirstPanel = new JPanel();
lFirstPanel.add(new JLabel("First Panel"));;
JPanel lSecondPanel = new JPanel();
lSecondPanel.add(new JLabel("Second Panel"));;
lTabbedPane.addTab("Tab1", null, lFirstPanel, "Does nothing");
lTabbedPane.addTab("Tab1", null,lSecondPanel, "Does nothing");
getContentPane().add(lTabbedPane);
lTabbedPane.addKeyListener(new KeyAdapter()
public void keyPressed(KeyEvent lKeyEvent)
System.out.println(lKeyEvent.getKeyText(lKeyEvent.getKeyCode()));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
public static void main(String[] args)
TestTab lTestTab = new TestTab();
lTestTab.drawGUI();
lTestTab.setSize(200, 200);
lTestTab.setVisible(true);The KeyPressed events for TAB and CTRL-TAB are typically consumed by the KeyboardFocusManager for component traversal. What you have to do is adjust traversal keys and add CTRL-TAB as an action of your JTabbedPane. This is usually done with the InputMap/ActionMap, not a KeyListener:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class X {
public static void main(String[] args) {
Set tabSet = Collections.singleton(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
KeyStroke ctrlTab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.CTRL_DOWN_MASK);
final int FORWARD = KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS;
final JTabbedPane tp = new JTabbedPane();
//setFocusTraversalKeys to remove ctrl-tab as a forward gesture
tp.setFocusTraversalKeys(FORWARD, tabSet);
for (int i=0; i<6; ++i) {
JPanel p = new JPanel(new GridLayout(0,1));
JTextArea area = new JTextArea();
area.setFocusTraversalKeys(FORWARD, Collections.EMPTY_SET);
p.add(new JScrollPane(area));
area = new JTextArea();
area.setFocusTraversalKeys(FORWARD, Collections.EMPTY_SET);
p.add(new JScrollPane(area));
tp.addTab("tab " + i,p);
//add ctrlTab as an action to move to next tab
Action nextTab = new AbstractAction("nextTab") {
public void actionPerformed(ActionEvent evt) {
int idx = tp.getSelectedIndex();
if (idx != -1) {
idx = (idx + 1) % tp.getTabCount();
tp.requestFocusInWindow();
tp.setSelectedIndex(idx);
InputMap im = tp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
im.put(ctrlTab, nextTab.getValue(Action.NAME));
tp.getActionMap().put(nextTab.getValue(Action.NAME), nextTab);
JFrame f= new JFrame("X");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(tp);
f.setSize(400,300);
f.setVisible(true);
[/code[
Maybe you are looking for
-
How to get back the data from 'AddressBook.data.previous' ?
Hi! First of all: After using iSync all my address book data were duplicated, and I deleted all duplicated data manually. Then, I resetted the iSync data under 'Advanced' in '.Mac Sync Preferences'. Unfortunately, iSync deleted all my AddressBook dat
-
Hi All, I have given below the jca connection factory details. I am creating dynamic ftp using jca.jndi and I would also like to overwrite the IncludeFiles property dynamically. At runtime i will choose what type of files that i need to list(xml, txt
-
Where can I find Adobe Acrobat 8 Professional download?
My computer crashed and I lost the Adobe Acrobat 8 Professional software that was on it, however I do have it's serial number. I just need the software to re-install it. Anyone have pointers to locations that I can get it?
-
Problem printing files to Adobe PDF printer using VBA
I have an Excel project. Part of the code prints the active sheet range as a PDF file. Later code then sends the PDF file as an e-mail attachment. The Code was originally written using the free application PDFCreator and works as intended. However th
-
Hi, I had a nasty surprise this morning with my iMac (white iMac, C2D, 24"): I powered it up, the fans started blowing like crazy, and then it just powered back down. Nothing else, no display, no startup sound, just that. When I tried to turn it back