Resetting a JPanel
I am writing to my JPanel (output) a variety of JLabels which contain images. This is the below snipped code.
output.add(imageLabel[count]);This works fantastically, but the output JPanel is only reset when I close and reopen the application. Is there any way that I can just reset all of the contents of this JPanel? I'm struggling to find a method.
Thank you very much in advance.
Edited by: simon33 on Mar 8, 2009 7:37 PM
Your best bet here is to show us more code. We don't want to see all of it, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:
[http://homepage1.nifty.com/algafield/sscce.html|http://homepage1.nifty.com/algafield/sscce.html]
Again, if the code is compilable and runnable more people will be able to help you.
Similar Messages
-
How to reset a the contents of a JPanel
I was just wondering the different ways one could go about resetting a JPanel. That is to clear everything then reload it.
AKA a game of chess where the pieces have already been moved...then on the click of a button the pieces go back to their original starting positions.
I've checked the API and fiddled about with hide(), show(), dispose() and re-adding the contents but to no avail. Well one method sort've worked but my algorithms became un-workable.
Just wondering what the best (most efficient perhaps?) way of going about this would be.
Thank you in advance.There's an example of replacing a JPanel here...
http://forum.java.sun.com/thread.jspa?forumID=54&threadID=5248903&start=14
It's in there somewhere, trust me... somewhere in the bit that changes the screen size. -
Hi, I'm creating a Boggle game in Java and I'm in need of help importing what outputs on the 'status' into the JTextArea called 'textL' which is the left text area of the program. If you run the program, it should show a main panel with two text area on each side. I just need words to be sent to the left text area when the 'Submit' or 'Reset' button is clicked. I'm just trying to test out the JText to make sure it works. I've tried coding it myself in the AcitionPerform method, but had no luck. What I have tested was calling my 'text'(JText variable) and having it setText("asdf") when 'button' is clicked, there's not output into the text area.
All help is greatly appreciated.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
// Your Class
public class Boggle extends JPanel implements ActionListener {
public final static int NUM_ROWS_COLUMNS = 5;
private JButton reset;
private JButton submit;//submit
// private JButton clrwrd;
private JButton arrayofButtons[][] = new JButton[NUM_ROWS_COLUMNS][NUM_ROWS_COLUMNS];
private JLabel status;
private JLabel messStatus;
private JTextArea textL;
private JTextArea textR;
private JButton prevButton;
private int prevRow, prevCol;
private Lexicon lex = new Lexicon("ENABL.txt");
// Your Constructor
public Boggle() {
BoxLayout ourLayout = new BoxLayout(this, BoxLayout.X_AXIS);
setLayout(ourLayout);
JScrollPane scrollLeft = new JScrollPane(buildTextAreaLeft());
scrollLeft.setVerticalScrollBar(scrollLeft.createVerticalScrollBar());
scrollLeft.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel MainAreaPanel = new JPanel();
MainAreaPanel.setLayout(new BoxLayout(MainAreaPanel, BoxLayout.Y_AXIS));
// MainAreaPanel.setPreferredSize(new Dimension(1000, 1000));
add(scrollLeft);
add(MainAreaPanel);
JScrollPane scrollRight = new JScrollPane(buildTextAreaRight());
scrollRight.setVerticalScrollBar(scrollRight.createVerticalScrollBar());
scrollRight.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(scrollRight);
MainAreaPanel.add(buildMainPanel());
MainAreaPanel.add(buildControlPanel());
MainAreaPanel.add(buildMessagePanel());
//Right JTextArea
private JTextArea buildTextAreaRight(){
JTextArea textR = new JTextArea();
textR = new JTextArea();
textR.setPreferredSize(new Dimension(300,200));
textR.setBorder(BorderFactory.createLineBorder(Color.black));
textR.setLineWrap(true);
textR.setEditable(true);
return textR;
//Left JTextArea
private JTextArea buildTextAreaLeft(){
JTextArea textL = new JTextArea();
textL= new JTextArea();
textL.setPreferredSize(new Dimension(300,200));
textL.setBorder(BorderFactory.createLineBorder(Color.black));
textL.setLineWrap(true);
textL.setEditable(true);
return textL;
// Your MainPanel
private JPanel buildMainPanel() {
JPanel panel = new JPanel();
GridLayout gridLayout = new GridLayout(0, NUM_ROWS_COLUMNS);
panel.setLayout(gridLayout);
for (int row = 0; row < arrayofButtons.length; ++row)
for (int column = 0; column < arrayofButtons[0].length; ++column) {
char letters = (char)(Math.random()*26+65);
// System.out.println(letters + 0);
arrayofButtons[row][column] = new JButton();
arrayofButtons[row][column].setBackground(Color.white);
arrayofButtons[row][column].setText(letters+"");// Set your letters
// in boxes.
arrayofButtons[row][column].setPreferredSize(new Dimension(100, 100));
arrayofButtons[row][column].addActionListener(this);
// Use actionCommand to store x,y location of button
arrayofButtons[row][column].setActionCommand(Integer.toString(row)+ " " + Integer.toString(column));
panel.add(arrayofButtons[row][column]);
// JTextArea textA = new JTextArea();
// panel.add(textA);
// BoxLayout ourLayout = new BoxLayout(textA, BoxLayout.X_AXIS);
// textA.setLayout(ourLayout);
// textA.setPreferredSize(new Dimension (100, 50));
return panel;
* Called when user clicks buttons with ActionListeners.
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == reset){
status.setText("");
for (int row = 0; row < arrayofButtons.length; ++row)
for (int column = 0; column < arrayofButtons[0].length; ++column){
char letters = (char)(Math.random()*26+65);
arrayofButtons[row][column].setText(letters+"");
arrayofButtons[row][column].setBackground(Color.white);
prevButton = null;
messStatus.setText("");
else if (button == submit){
boolean b = lex.contains(status.getText());
// System.out.println(lex); // checking what came in.
if (b==true){
messStatus.setText("'" + status.getText() + "'" + " found. ");
status.setText("");
textL.setText(status.getText());
for (int row = 0; row < arrayofButtons.length; ++row)
for (int column = 0; column < arrayofButtons[0].length; ++column){
arrayofButtons[row][column].setBackground(Color.white);
prevButton = null;
if (b!=true){
messStatus.setText("'" + status.getText() + "'" + " not found. ");
status.setText("");
for (int row = 0; row < arrayofButtons.length; ++row)
for (int column = 0; column < arrayofButtons[0].length; ++column){
arrayofButtons[row][column].setBackground(Color.white);
prevButton = null;
else {
String rowColumn[] = button.getActionCommand().split(" ");
int row = Integer.parseInt(rowColumn[0]);
int column = Integer.parseInt(rowColumn[1]);
if(prevButton == null){
prevButton = button;
prevRow = row;
prevCol = column;
arrayofButtons[row][column].setBackground(Color.orange);
status.setText(status.getText()+ arrayofButtons[row][column].getText());
else{
int dist = (int)Math.pow((prevRow - row)*(prevRow - row) + (prevCol - column)*(prevCol - column),0.5);
if(dist == 1 && button.getBackground() == Color.white ){
prevButton.setBackground(Color.green);
arrayofButtons[row][column].setBackground(Color.orange);
status.setText(status.getText()+ arrayofButtons[row][column].getText());
prevButton = button;
prevRow = row;
prevCol = column;
* when submit button is clicked, grab status and place in messStatus
// Your Control Panel
private JPanel buildControlPanel() {
JPanel panel = new JPanel();
BoxLayout ourLayout = new BoxLayout(panel, BoxLayout.X_AXIS);
panel.setLayout(ourLayout);
//Your reset button
reset = new JButton("Reset");
reset.addActionListener(this);
panel.add(reset);
//distance of status from Reset button
JPanel space = new JPanel();
space.setPreferredSize(new Dimension (10,10));
panel.add(space);
//Your status label
status = new JLabel();
panel.add(status);
//the distance from Reset button to Submit button
JPanel blank = new JPanel();
blank.setPreferredSize(new Dimension(400, 30));
panel.add(blank);
//your Submit button
submit= new JButton("SUMBIT");
submit.addActionListener(this);
panel.add(submit);
//button panel
panel.add(Box.createHorizontalGlue());
JLabel statusLabel = new JLabel();
panel.add(statusLabel);
panel.setBorder(BorderFactory.createLineBorder(Color.black));
return panel;
private JPanel buildMessagePanel(){
JPanel messPanel = new JPanel();
BoxLayout ourLayout = new BoxLayout(messPanel, BoxLayout.X_AXIS);
messPanel.setLayout(ourLayout);
messPanel.setPreferredSize(new Dimension(100,50));
messStatus = new JLabel();
messPanel.add(messStatus);
return messPanel;
// create and show GUI
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("BoggleUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add contents to the window.
frame.add(new Boggle());
// Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}Edited by: user13813121 on Mar 22, 2011 8:39 AMI found this code, which is not so different from mine, but a lot simpler easier to understand. I just don't know how this code works even without implementing the Policies for JScroll.
import java.awt.*;
import javax.swing.*;
public class scrollDemo extends JFrame {
//============================================== instance variables
JTextArea _resultArea = new JTextArea(6, 20);
//====================================================== constructor
public scrollDemo() {
//... Set textarea's initial text, scrolling, and border.
_resultArea.setText("Enter more text to see scrollbars");
_resultArea.setLineWrap(true);
JScrollPane scrollingArea = new JScrollPane(_resultArea);
//... Get the content pane, set layout, add to center
JPanel content = new JPanel();
content.setLayout(new BorderLayout());
content.add(scrollingArea, BorderLayout.CENTER);
//... Set window characteristics.
this.setContentPane(content);
this.setTitle("TextAreaDemo B");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
//============================================================= main
public static void main(String[] args) {
JFrame win = new scrollDemo();
win.setVisible(true);
} -
JLabel.getText doesn't work properly
I have a main JFrame to build up the application GUI (using NetBeans 6.0.1). This mainPanel contains a JSplitPane and a StatusBar beneath. In the right side of the JSplitPane I put a JPanel with JComboBoxes and JButtons. After selecting an item in the JComboBox and clicking a JButton, the text in the StatusBar (implemented using a simple JLabel) shall be faded out by simply removing the first character until the text is erased and I use a Timer for this. This works well for itself.
The problem now is that I want to start the 'fading' only if the StatusBar (the JLabel) contains a text at all. Checking this with:
if ( !targetLabel.getText().equals("") ) {
<start fading>
}the getText() method returns "" (an empty string) ever. Even although I initialized this JLabel with a dummy text during initialization. Why?
Here's the code for trying to set a JLabel in the StatusBar (this part works well) and fading a probably displayed text prior:
class StatusMessageSetter implements Runnable{
String myText;
Color color;
JLabel target;
public StatusMessageSetter(JLabel target, Color color, String text) {
myText = text;
this.color = color;
this.target = target;
public void run() {
//try {
System.out.println("StatusMessageSetter: target=" + target);
//SwingUtilities.invokeLater(new Runnable(){
// public void run() {
System.out.println("StatusMessageSetter: target.getText()=" + target.getText());
if ( !target.getText().trim().equals("") ) {
try {
MessageFader fader = new MessageFader(target);
Thread th = new Thread(fader);
th.start();
th.join();
} catch(InterruptedException intEx){}
}//end if
Thread t = new Thread(new Runnable(){
public void run(){
try {
SwingUtilities.invokeAndWait(new Runnable() {
//SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println("Setting label...: " + myText);
target.setForeground(color);
target.setText(myText);
}//end run
} catch(InterruptedException intEx) {}
catch(InvocationTargetException invocEx) {}
}); //end new Runnable
t.start();
}//end run
};+(Even when I only request the text from the JLabel when the JButton is clicked (in the JButton's actionPerformed() method) and doing nothing else the result is an empty String!!! And it doesn't matter if I do this directly or using SwingUtilities.invokeLater(); Why? I don't undertand this. I am asking: parentView.getStatusMessageLabel().getText(); (No NullPointerException is thrown. Thus, parentView as well as statusMessageLabel exist and I can see the set text in the statusBar.)+
What I want to do (and I didn't managed this for the time being) is, that I want to display a message to the user what the app is going to do and inform the user afterwards about the result (failure/success) using the JLabel in the StatusBar. (Saying: "I'm going to do this...", executing a time consuming action (parsing a website) and the display the result in the StatusBar. Of course, the messages MUST be displayed well synchronized which means:
Displaying what the app is currently doing and after the action returns this messagfe shall fade and the new message will be displayed.
Maybe anyone could give me some code to solve my problem?!!?
Thanks in advance
Dirk
Edited by: dirku on May 8, 2008 5:05 AMdirku wrote:
2. A time consuming operation needs to be executed:
--> In this case the time consuming operation begins but the message which should tell the user what the time consuming operation does is displayed
only AFTER the operation has already completed. (The time consuming operation connects to parses a website and must return a state (OK,
ERROR, ...).
Thus, I think I need some kind of synchronization, don't I?Hm, not sure. You're probably not even going to see this, but no matter. I played with my code some more and got something like so:
StatusMessageSetter .java
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.Timer;
class StatusMessageSetter
private static final int DELAY = 1000;
private String myText;
private Color color;
private JLabel target;
private int delay = DELAY;
public StatusMessageSetter(JLabel target)
this.target = target;
public void setDelay(int delay)
this.delay = delay;
public void fadeLabel(Color color, String text)
this.color = color;
this.myText = text;
if (!target.getText().trim().equals(""))
new Timer(delay, new MessageFader(target, color, myText)).start();
private class MessageFader implements ActionListener
private JLabel label;
private StringBuilder sb;
private Color color;
private String text;
public MessageFader(JLabel target, Color c, String t)
label = target;
color = c;
text = t;
sb = new StringBuilder(label.getText().trim());
@Override
public void actionPerformed(ActionEvent e)
if (sb.length() > 0)
sb.deleteCharAt(0);
if (sb.length() == 0)
label.setText(" ");
else
label.setText(sb.toString());
else
label.setForeground(color);
label.setText(text);
Timer timer = (Timer)e.getSource();
timer.stop();
}StatusBr.java
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class StatusBr
private JPanel mainPanel = new JPanel();
private JLabel label = new JLabel();
public StatusBr()
mainPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
mainPanel.add(label);
public JLabel getLabel()
return label;
public void setColor(Color c)
label.setForeground(c);
public void setText(String text)
label.setText(text);
public String getText()
return label.getText();
public void setBorder(Border border)
mainPanel.setBorder(border);
public JPanel getMainPanel()
return mainPanel;
}StatusMsgrTester.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.Timer;
public class StatusMsgrTester
private static final String STATUS_BAR = "Status Bar";
private static final String CONFIRMED = "Confirmed";
private static final String QUICK_CONFIRM = "Quick Confirmation";
private static final String SLOW_CONFIRM = "Slow Confirmation";
private static final String RESET = "Reset";
private JPanel mainPanel = new JPanel();
private StatusBr statusbar = new StatusBr();
StatusMessageSetter statusMsgSetter = new StatusMessageSetter(statusbar
.getLabel());
public StatusMsgrTester()
JButton quickConfirmBtn = new JButton(QUICK_CONFIRM);
JButton slowConfirmBtn = new JButton(SLOW_CONFIRM);
JButton resetBtn = new JButton(RESET);
ConfirmBtnListener confirmListener = new ConfirmBtnListener();
quickConfirmBtn.addActionListener(confirmListener);
slowConfirmBtn.addActionListener(confirmListener);
resetBtn.addActionListener(confirmListener);
JPanel confirmPanel = new JPanel(new GridLayout(1, 0, 10, 10));
confirmPanel.add(quickConfirmBtn);
confirmPanel.add(slowConfirmBtn);
confirmPanel.add(resetBtn);
JPanel buttonPanel = new JPanel();
buttonPanel.add(confirmPanel);
statusMsgSetter.setDelay(60);
statusbar.setText(STATUS_BAR);
statusbar.setBorder(BorderFactory.createCompoundBorder(BorderFactory
.createRaisedBevelBorder(), BorderFactory
.createLoweredBevelBorder()));
mainPanel.setPreferredSize(new Dimension(500, 200));
mainPanel.setLayout(new BorderLayout());
mainPanel.add(statusbar.getMainPanel(), BorderLayout.SOUTH);
mainPanel.add(buttonPanel, BorderLayout.NORTH);
private class ConfirmBtnListener implements ActionListener
@Override
public void actionPerformed(ActionEvent e)
String command = e.getActionCommand();
if (command.equals(QUICK_CONFIRM))
statusMsgSetter.fadeLabel(Color.blue, CONFIRMED);
else if (command.equals(SLOW_CONFIRM))
slowConfirmation();
else if (command.equals(RESET))
statusbar.setColor(null);
statusbar.setText(STATUS_BAR);
public JPanel getMainPanel()
return mainPanel;
private void slowConfirmation()
final Timer timer = new Timer(2000, new ActionListener()
@Override
public void actionPerformed(ActionEvent e)
statusMsgSetter.setDelay(30);
statusMsgSetter.fadeLabel(Color.red, "Confirming User, Please Wait.......");
timer.setInitialDelay(5);
timer.start();
SwingWorker<String, Void> swingworker = new SwingWorker<String, Void>()
@Override
protected String doInBackground() throws Exception
System.out.println("Long process");
for (int i = 0; i < 10; i++)
System.out.println(String.valueOf(i));
Thread.sleep(1400);
return null;
@Override
protected void done()
timer.stop();
System.out.println("Done");
statusMsgSetter.fadeLabel(Color.blue, CONFIRMED);
swingworker.execute();
private static void createAndShowUI()
JFrame frame = new JFrame("StatusMsgrTester");
frame.getContentPane().add(new StatusMsgrTester().getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
public static void main(String[] args)
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
createAndShowUI();
} -
How can I reset the background color of a JPanel to it's default value?
I have some JPanels that I set their background color to white when I add some objects in them. After some operations the objects are removed and I'd like to reset the background color back to it's default gray. Any suggestions on how to do this? Thanks.
I took a guess and I figured it out. Just set the background color to null.
JPanel panel = new JPanel();
panel.setBackground(Color.white); //Set Panel to White
Operations......
panel.setBackground(null); //Reset Panel Color to Default Gray -
Is it possible to reposition the origin in a JPanel so the reference point is not the top left. I am trying to draw a graph in Graphics2D and it would be handy if I could chose my own origin instead of having to alter the values of each point on the graph.
Is it possible to reposition the origin in a JPanel so
the reference point is not the top left. I am trying
to draw a graph in Graphics2D and it would be handy if
I could chose my own origin instead of having to alter
the values of each point on the graph.Use JFreeChart and your problem will be taken care of by code that has been reviewed by many developers:
http://www.object-refinery.com/jfreechart/index.html
Complete source code included (GNU LGPL).
Regards,
Dave Gilbert
www.object-refinery.com -
friends,
i have a jpanel with image as background and i am adding jlabels dynamically to the jpanel. i have to move the jlabel on the image so i added mouse listener to jlabel. now i want to add zooming functionality to the jpanel.
now if zoom out jpanel everything works well but jlabel mouse listener location is not changing so if i click on jlabel its not activating listener - i need to click outside of jlabel/jpanel (its original location when its 100% zoom) to activate the listener. how can i correct this ?
thanks in advance
i will add example after i cutdown (its part of big application)import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class PP3 extends JFrame {
private JButton btnStart;
private JButton btnStop;
private JLabel logoLabel;
private JSlider zoom;
private JPanel mainPanel;
private JPanel btnPanel;
private JScrollPane jspane;
private BackPanel3 secondPanel;
private boolean start = false;
public PP3() {
initComponents();
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
private void initComponents() {
logoLabel = new JLabel();
mainPanel = new JPanel();
btnPanel = new JPanel();
btnStart = new JButton();
btnStop = new JButton();
zoom = new JSlider(0,100,100);
setBackground(Color.white);
setLayout(new BorderLayout());
mainPanel.setBackground(Color.white);
mainPanel.setBorder(new EtchedBorder());
mainPanel.setPreferredSize(new Dimension(650, 600));
mainPanel.setLayout(new CardLayout());
jspane = new JScrollPane(getSecondPanel());
mainPanel.add(jspane,"Second Panel");
add(mainPanel, BorderLayout.CENTER);
btnPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2,2,2,2);
gbc.weighty = 1.0;
gbc.gridwidth = gbc.REMAINDER;
btnPanel.setBackground(Color.white);
btnPanel.setBorder(new EtchedBorder());
btnPanel.setPreferredSize(new Dimension(150, 600));
btnStart.setText("Start Labelling");
btnPanel.add(btnStart, gbc);
btnStart.setEnabled(true);
btnStart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
start = true;
btnStart.setEnabled(false);
btnStop.setEnabled(true);
if(secondPanel != null){
secondPanel.setStart(start);
Cursor moveCursor = new Cursor(Cursor.TEXT_CURSOR);
secondPanel.setCursor(moveCursor);
btnStop.setText("Done Labelling");
btnPanel.add(btnStop, gbc);
btnStop.setEnabled(false);
btnStop.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
start = false;
btnStart.setEnabled(true);
btnStop.setEnabled(false);
if(secondPanel != null){
secondPanel.setStart(start);
Cursor moveCursor = new Cursor(Cursor.DEFAULT_CURSOR);
secondPanel.setCursor(moveCursor);
final JLabel zoomLabel = new JLabel("Zoom");
zoomLabel.setBorder(BorderFactory.createEtchedBorder());
gbc.weighty = 0;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
btnPanel.add(zoomLabel, gbc);
btnPanel.add(zoom, gbc);
zoom.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
JSlider source = (JSlider)ce.getSource();
if(secondPanel != null) {
secondPanel.setZoomFactor((double)source.getValue());
zoomLabel.setText("Zoom = " + source.getValue()/100.0);
String id = "<html><nobr>show label</nobr><br><center>locations";
JCheckBox check = new JCheckBox(id, secondPanel.showLocations);
check.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
secondPanel.toggleShowLocations();
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.NONE;
btnPanel.add(check, gbc);
add(btnPanel, BorderLayout.EAST);
pack();
public JPanel getSecondPanel() {
if(secondPanel == null) {
secondPanel = new BackPanel3("images/cougar.jpg", 850, 1100);
secondPanel.setStart(false);
return secondPanel;
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PP3();
class BackPanel3 extends JPanel implements MouseListener,
MouseMotionListener{
String imgPath = null;
BufferedImage image;
private int width = 0;
private int height = 0;
private double zoomFactor = 1.0;
private boolean start = false;
private boolean same = false;
Cursor hourglassCursor = new Cursor(Cursor.MOVE_CURSOR);
// choose a declaration according to your java version
List<JLabel> labels; // declaration for j2se 1.5+
// List labels; // j2se 1.4-
JLabel lastSelected;
boolean showLocations;
JLabel selectedLabel;
boolean dragging;
Point offset;
int count = 0;
private static String SELECTED = "selected";
public BackPanel3(String path, int width, int height){
setLayout(null);
this.width = width;
this.height = height;
setPreferredSize(new Dimension(width,height));
addMouseListener(this);
addMouseMotionListener(this);
// chose an instantiation according to your java version
labels = new ArrayList<JLabel>(); // j2se 1.5+
// labels = new ArrayList(); // j2se 1.4-
lastSelected = new JLabel();
lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
showLocations = true;
dragging = false;
offset = new Point();
this.imgPath = path;
setImage();
public void setImage(){
try{
image = getImage(imgPath);
}catch(Exception e){
System.out.println(" (init) ERROR: " + e);
e.printStackTrace();
public void setStart(boolean flag){
start = flag;
public void setZoomFactor(double zoom){
zoomFactor = (zoom/100);
setPreferredSize(new Dimension((int)(850*zoomFactor), (int)(1100*zoomFactor)));
repaint();
revalidate();
public double getZoomFactor(){
return zoomFactor;
public void toggleShowLocations() {
showLocations = !showLocations;
repaint();
public void mouseClicked(MouseEvent e) {
if(start){
JLabel msgLabel = new JLabel("Test " + count++);
this.add(msgLabel);
Dimension d = msgLabel.getPreferredSize();
msgLabel.setBounds(e.getX(), e.getY(), d.width, d.height);
labels.add(msgLabel);
msgLabel.putClientProperty(SELECTED, Boolean.FALSE);
return;
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
for(int j = 0; j < labels.size(); j++) {
JLabel label = (JLabel)labels.get(j);
Rectangle bounds = label.getBounds();
AffineTransform at =
AffineTransform.getScaleInstance(zoomFactor, zoomFactor);
Shape xs = at.createTransformedShape(bounds);
if(xs.contains(p)) {
selectedLabel = label;
Rectangle r = xs.getBounds();
offset.x = p.x - r.x;
offset.y = p.y - r.y;
dragging = true;
break;
public void mouseReleased(MouseEvent e) {
dragging = false;
public void mouseDragged(MouseEvent me){
if(dragging) {
Rectangle bounds = selectedLabel.getBounds();
AffineTransform at =
AffineTransform.getScaleInstance(1.0/zoomFactor, 1.0/zoomFactor);
Point2D p = at.transform(me.getPoint(), null);
int x = (int)(p.getX() - offset.x);
int y = (int)(p.getY() - offset.y);
selectedLabel.setLocation(x, y);
repaint();
public void mouseMoved(MouseEvent me){
if(labels.size() == 0)
return;
Point p = me.getPoint();
boolean hovering = false;
boolean selectionChanged = false;
for(int j = 0; j < labels.size(); j++) {
final JLabel label = (JLabel)labels.get(j);
Rectangle r = label.getBounds();
AffineTransform at =
AffineTransform.getScaleInstance(zoomFactor, zoomFactor);
Shape scaledBounds = at.createTransformedShape(r);
if(scaledBounds.contains(p)) {
hovering = true;
if(!((Boolean)label.getClientProperty(SELECTED)).booleanValue()) {
label.putClientProperty("selected", Boolean.TRUE);
setCursor(hourglassCursor);
if(lastSelected != label) // for only one JLabel
lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
lastSelected = label;
selectionChanged = true;
break;
// reset lastSelected when there is no selection/hovering
if(!hovering &&
((Boolean)lastSelected.getClientProperty(SELECTED)).booleanValue()) {
lastSelected.putClientProperty(SELECTED, Boolean.FALSE);
setCursor(Cursor.getDefaultCursor());
selectionChanged = true;
if(selectionChanged)
repaint();
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.scale(zoomFactor, zoomFactor);
g2.drawImage(image, 0, 0, this);
if(showLocations) {
// show bounds of the actual JLabel children
// components as they exist on this component
AffineTransform at = AffineTransform.getScaleInstance(1.0/zoomFactor,
1.0/zoomFactor);
g2.setPaint(Color.blue);
Component[] c = getComponents();
for(int j = 0; j < c.length; j++)
g2.draw(at.createTransformedShape(c[j].getBounds()));
// show selected label
g2.setPaint(Color.red);
for(int j = 0; j < labels.size(); j++) {
JLabel label = (JLabel)labels.get(j);
if(((Boolean)label.getClientProperty("selected")).booleanValue()) {
g2.draw(label.getBounds());
break;
protected BufferedImage getImage(String path){
try{
URL imgURL = BackPanel3.class.getResource(path);
if (imgURL == null &&
(path.indexOf(":\\") > 0 || path.indexOf(":/") > 0))
imgURL = new URL("file:///"+path);
return getImage(imgURL);
}catch(MalformedURLException mue){
System.out.println("error "+mue);
return null;
protected BufferedImage getImage(URL url){
try{
if (url != null) {
BufferedImage source = ImageIO.read(url);
double xScale = (double)width / source.getWidth();
double yScale = (double)height / source.getHeight();
double scale = Math.min(xScale, yScale);
int w = (int)(scale*source.getWidth());
int h = (int)(scale*source.getHeight());
BufferedImage scaled = new BufferedImage(w, h, source.getType());
Graphics2D g2 = scaled.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
// scales faster than getScaledInstance
AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
g2.drawRenderedImage(source, at);
g2.dispose();
return scaled;
}else{
return null;
}catch(IOException ioe){
System.out.println("read error "+ioe);
return null;
} -
Problem with 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();
} -
HELP!!! How to create a modal JPanel
Hi
I've been creating an applet that uses transparent JPanels to draw boxes that look like windows.
I'm in need, now, to create one that asks for user input (ie "click the OK button") and that blocks the current thread and other panels until the user has answered.
It's totally similar to a windows message box.
How do i do it????
I've been taking examples from this tech tip (http://java.sun.com/developer/JDCTechTips/2001/tt1220.html) that explains almost everything (but uses JInternalFrame), and also 2 ways of doing the thread-blocking work:
One way uses a worker thread to compose the UI and wait() while the java dispatcher thread does the app events (action, paint) and notifyAll() when the user presses "OK".
In the other way, the author copied the code from EventQueue's dispatchEvent() and created a dispatcher thread into the modal JFrame, so that events could be processed without having to use another thread.
I think this last method is a hack because of portabilityu issues, for example code in my dispatchEvent() (JRE1.6.0) contains more checks and cases than the code he postet in that page.
I think I would have problem running similar code on a previous or future version of the JRE.
Anyway I haven't succeeded yet to wake up the waiting thread when the user has clicked OK. The notifyAll method executes, no exception is thrown, but the other thread remains asleep.
Here's my code (note the "synchronized" keywords)
synchronized public int show(String title, String message, int buttons, boolean isError) {
if (isError)
jptBox = new TLPanel(title, new Color(104,10,11), new Color(234,30,34), new Color(241,79,83));
else
jptBox = new TLPanel(title, new Color(6,29,108), new Color(80,103,184), new Color(120,138,200));
jptBox.setBounds(TLStartup.centerSize(400, 100));
btn1 = new JButton("OK");
btn1.setBounds(180, 75, 40, 20);
btn1.addActionListener(new ActionListener() {
public synchronized void actionPerformed(ActionEvent e) {
this.notify();
jptBox.add(btn1);
cnt.add(jptBox);
cnt.setComponentZOrder(jptBox, 0);
try {
this.wait();
} catch (Exception ex) {
System.out.println(ex.toString());
return MB_ANSWER_YES;
}I put a boolean variable test=true into my class, and modified the code to check it into the waiting cycle:
try {
while (test)
this.wait(1000);
} catch (Exception ex) {
System.out.println(ex.toString());
}and to reset it into the actionPerformed:
btn1.addActionListener(new ActionListener() {
public synchronized void actionPerformed(ActionEvent e) {
test = false;
this.notifyAll();
});And HOW COME it does work now ??? (with some delay) -
Who can help me :)--a problem with java program(reset problem in java )
I do not know how to make the button reset,my program only could reset diagram but button.If any one who could help me to solve this problem.The problem is When the reset button is pressed, the image should immediately revert to the black square, and the 4 widgets listed above should show values that
correspond to the black square.The code like this,first one is shapes:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class shapes extends JFrame {
private JPanel buttonPanel; // panel for buttons
private DrawPanel myPanel; // panel for shapes
private JButton resetButton;
private JComboBox colorComboBox;
private JRadioButton circleButton, squareButton;
private ButtonGroup radioGroup;
private JCheckBox filledButton;
private JSlider sizeSlider;
private boolean isShow;
private int shape;
private boolean isFill=true;
private String colorNames[] = {"black", "blue", "cyan", "darkGray", "gray",
"green", "lightgray", "magenta", "orange",
"pink", "red", "white", "yellow"}; // color names list in ComboBox
private Color colors[] = {Color.black, Color.blue, Color.cyan, Color.darkGray,
Color.gray, Color.green, Color.lightGray, Color.magenta,
Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
public shapes() {
super("Draw Shapes");
// creat custom drawing panel
myPanel = new DrawPanel(); // instantiate a DrawPanel object
myPanel.setBackground(Color.white);
// set up resetButton
// register an event handler for resetButton's ActionEvent
resetButton = new JButton ("reset");
resetButton.addActionListener(
// anonymous inner class to handle resetButton events
new ActionListener() {
// draw a black filled square shape after clicking resetButton
public void actionPerformed (ActionEvent event) {
// call DrawPanel method setShowStatus and pass an parameter
// to decide if show the shape
myPanel.setShowStatus(true);
isShow = myPanel.getShowStatus();
shape = DrawPanel.SQUARE;
// call DrawPanel method setShape to indicate shape to draw
myPanel.setShape(shape);
// call DrawPanel method setFill to indicate to draw a filled shape
myPanel.setFill(true);
// call DrawPanel method draw
myPanel.draw();
myPanel.setFill(true);
myPanel.setForeground(Color.black);
}// end anonymous inner class
);// end call to addActionListener
// set up colorComboBox
// register event handlers for colorComboBox's ItemEvent
colorComboBox = new JComboBox(colorNames);
colorComboBox.setMaximumRowCount(5);
colorComboBox.addItemListener(
// anonymous inner class to handle colorComboBox events
new ItemListener() {
// select shape's color
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED)
// call DrawPanel method setForeground
// and pass an element value of colors array
myPanel.setForeground(colors[colorComboBox.getSelectedIndex()]);
myPanel.draw();
}// end anonymous inner class
); // end call to addItemListener
// set up a pair of RadioButtons
// register an event handler for RadioButtons' ItemEvent
squareButton = new JRadioButton ("Square", true);
circleButton = new JRadioButton ("Circle", false);
radioGroup = new ButtonGroup();
radioGroup.add(squareButton);
radioGroup.add(circleButton);
squareButton.addItemListener(
// anonymous inner class to handle squareButton events
new ItemListener() {
public void itemStateChanged (ItemEvent event) {
if (isShow==true) {
shape = DrawPanel.SQUARE;
myPanel.setShape(shape);
myPanel.draw();
}// end anonymous inner class
);// end call to addItemListener
circleButton.addItemListener(
// anonymous inner class to handle circleButton events
new ItemListener() {
public void itemStateChanged (ItemEvent event) {
if (isShow==true) {
shape = DrawPanel.CIRCLE;
myPanel.setShape(shape);
myPanel.draw();
else
System.out.println("Please click Reset button first");
}// end anonymous inner class
);// end call to addItemListener
// set up filledButton
// register an event handler for filledButton's ItemEvent
filledButton = new JCheckBox("Filled", true);
filledButton.addItemListener(
// anonymous inner class to handle filledButton events
new ItemListener() {
public void itemStateChanged (ItemEvent event) {
if (isShow==true) {
if (event.getStateChange() == ItemEvent.SELECTED) {
isFill=true;
myPanel.setFill(isFill);
myPanel.draw();
else {
isFill=false;
myPanel.setFill(isFill);
myPanel.draw();
else
System.out.println("Please click Reset button first");
}// end anonymous inner class
);// end call to addItemListener
// set up sizeSlider
// register an event handler for sizeSlider's ChangeEvent
sizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, 100);
sizeSlider.setMajorTickSpacing(10);
sizeSlider.setPaintTicks(true);
sizeSlider.addChangeListener(
// anonymous inner class to handle sizeSlider events
new ChangeListener() {
public void stateChanged(ChangeEvent event) {
myPanel.setShapeSize(sizeSlider.getValue());
myPanel.draw();
}// end anonymous inner class
);// end call to addChangeListener
// set up panel containing buttons
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 1, 0, 50));
buttonPanel.add(resetButton);
buttonPanel.add(filledButton);
buttonPanel.add(colorComboBox);
JPanel radioButtonPanel = new JPanel();
radioButtonPanel.setLayout(new GridLayout(2, 1, 0, 20));
radioButtonPanel.add(squareButton);
radioButtonPanel.add(circleButton);
buttonPanel.add(radioButtonPanel);
// attach button panel & draw panel to content panel
Container container = getContentPane();
container.setLayout(new BorderLayout(10,10));
container.add(myPanel, BorderLayout.CENTER);
container.add(buttonPanel, BorderLayout.EAST);
container.add(sizeSlider, BorderLayout.SOUTH);
setSize(500, 400);
setVisible(true);
public static void main(String args[]) {
shapes application = new shapes();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}second one is drawpanel:
import java.awt.*;
import javax.swing.*;
public class DrawPanel extends JPanel {
public final static int CIRCLE = 1, SQUARE = 2;
private int shape;
private boolean fill;
private boolean showStatus;
private int shapeSize = 100;
private Color foreground;
// draw a specified shape
public void paintComponent (Graphics g){
super.paintComponent(g);
// find center
int x=(getSize().width-shapeSize)/2;
int y=(getSize().height-shapeSize)/2;
if (shape == CIRCLE) {
if (fill == true){
g.setColor(foreground);
g.fillOval(x, y, shapeSize, shapeSize);
else{
g.setColor(foreground);
g.drawOval(x, y, shapeSize, shapeSize);
else if (shape == SQUARE){
if (fill == true){
g.setColor(foreground);
g.fillRect(x, y, shapeSize, shapeSize);
else{
g.setColor(foreground);
g.drawRect(x, y, shapeSize, shapeSize);
// set showStatus value
public void setShowStatus (boolean s) {
showStatus = s;
// return showstatus value
public boolean getShowStatus () {
return showStatus;
// set fill value
public void setFill(boolean isFill) {
fill = isFill;
// set shape value
public void setShape(int shapeToDraw) {
shape = shapeToDraw;
// set shapeSize value
public void setShapeSize(int newShapeSize) {
shapeSize = newShapeSize;
// set foreground value
public void setForeground(Color newColor) {
foreground = newColor;
// repaint DrawPanel
public void draw (){
if(showStatus == true)
repaint();
}If any kind people who can help me.
many thanks to you!4 widgets???
maybe this is what you mean.
add this inside your actionPerformed method for the reset action
squareButton.setSelected(true);
colorComboBox.setSelectedIndex(0);
if not be more clear in your post. -
How to resize JPanel at Runtime ??
Hi,
Our Project me t a problem as below, we hope to resize JPanel at Runtime , not at design time, ie, when we first click the button called "Move JPanel" , then we click the JPanel, then we can drag it around within main panel, but we hope to resize the size of this JPanel when we point to the border of this JPanel then drag its border to zoom in or zoom out this JPanel.
Please advice how to do that??
Thanks in advance.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.event.*;
public class ResizeJPanels extends JPanel
protected JLabel label1, label2, label3, label4, labeltmp;
protected JLabel[] labels;
protected JPanel[] panels;
protected JPanel selectedJPanel;
protected JButton btn = new JButton("Move JPanel");
int cx, cy;
protected Vector order = new Vector();
public static void main(String[] args)
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new ResizeJPanels().GroupJLabels());
f.setSize(600,700);
f.setLocation(200,200);
f.setVisible(true);
private MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
JPanel jp = new JPanel();
jp.setLayout(null);
Component[] c = ((JPanel)e.getSource()).getComponents();
System.out.println("c.length = " + c.length);
for(int j = 0; j < c.length; j++) {
if(c[j].getBounds().contains(p)) {
if(selectedJPanel != null && selectedJPanel != (JPanel)c[j])
selectedJPanel.setBorder(BorderFactory.createEtchedBorder());
selectedJPanel = (JPanel)c[j];
selectedJPanel.setBorder(BorderFactory.createLineBorder(Color.green));
break;
add(jp);
revalidate();
public JPanel GroupJLabels ()
setLayout(null);
addLabels();
label1.setBounds( 125, 150, 125, 25);
label2.setBounds(425, 150, 125, 25);
label3.setBounds( 125, 575, 125, 25);
label4.setBounds(425, 575, 125, 25);
//add(btn);
btn.setBounds(10, 5, 205, 25);
add(btn);
determineCenterOfComponents();
ComponentMover mover = new ComponentMover();
ActionListener lst = new ActionListener() {
public void actionPerformed(ActionEvent e) {
ComponentMover mover = new ComponentMover();
addMouseListener(mover);
addMouseMotionListener(mover);
btn.addActionListener(lst);
addMouseListener(ml);
return this;
public void paintComponent(final Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Point[] p;
g2.setStroke(new BasicStroke(4f));
for(int i = 0 ; i < order.size()-1; i++) {
JPanel l1 = (JPanel)order.elementAt(i);
JPanel l2 = (JPanel)order.elementAt(i+1);
p = getCenterPoints(l1, l2);
g2.setColor(Color.black);
// g2.draw(new Line2D.Double(p[0], p[1]));
private Point[] getCenterPoints(Component c1, Component c2)
Point
p1 = new Point(),
p2 = new Point();
Rectangle
r1 = c1.getBounds(),
r2 = c2.getBounds();
p1.x = r1.x + r1.width/2;
p1.y = r1.y + r1.height/2;
p2.x = r2.x + r2.width/2;
p2.y = r2.y + r2.height/2;
return new Point[] {p1, p2};
private void determineCenterOfComponents()
int
xMin = Integer.MAX_VALUE,
yMin = Integer.MAX_VALUE,
xMax = 0,
yMax = 0;
for(int i = 0; i < labels.length; i++)
Rectangle r = labels.getBounds();
if(r.x < xMin)
xMin = r.x;
if(r.y < yMin)
yMin = r.y;
if(r.x + r.width > xMax)
xMax = r.x + r.width;
if(r.y + r.height > yMax)
yMax = r.y + r.height;
cx = xMin + (xMax - xMin)/2;
cy = yMin + (yMax - yMin)/2;
private class ComponentMover extends MouseInputAdapter
Point offsetP = new Point();
boolean dragging;
public void mousePressed(MouseEvent e)
Point p = e.getPoint();
for(int i = 0; i < panels.length; i++)
Rectangle r = panels[i].getBounds();
if(r.contains(p))
selectedJPanel = panels[i];
order.addElement(panels[i]);
offsetP.x = p.x - r.x;
offsetP.y = p.y - r.y;
dragging = true;
repaint(); //added
break;
public void mouseReleased(MouseEvent e)
dragging = false;
public void mouseDragged(MouseEvent e)
if(dragging)
Rectangle r = selectedJPanel.getBounds();
r.x = e.getX() - offsetP.x;
r.y = e.getY() - offsetP.y;
selectedJPanel.setBounds(r.x, r.y, r.width, r.height);
//determineCenterOfComponents();
repaint();
private void addLabels()
label1 = new JLabel("Label 1");
label2 = new JLabel("Label 2");
label3 = new JLabel("Label 3");
label4 = new JLabel("Label 4");
labels = new JLabel[] {
label1, label2, label3, label4
JLabel jl = new JLabel("This is resizeable JPanel at Runtime");
jl.setBackground(Color.green);
jl.setOpaque(true);
jl.setFont(new Font("Helvetica", Font.BOLD, 18));
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
panels = new JPanel[]{jp};
jp.setBorder(new LineBorder(Color.black, 3, false));
jp.setPreferredSize(new Dimension(400,200));
jp.add(jl, BorderLayout.NORTH);
for(int i = 0; i < labels.length; i++)
labels[i].setHorizontalAlignment(SwingConstants.CENTER);
labels[i].setBorder(BorderFactory.createEtchedBorder());
jp.add(labels[i], BorderLayout.CENTER);
jp.setBounds(100, 100, 400,200);
add(jp);import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.MouseInputAdapter;
public class Resizing extends JPanel {
public Resizing() {
super(null);
addPanel();
PanelControlAdapter control = new PanelControlAdapter(this);
addMouseListener(control);
addMouseMotionListener(control);
private void addPanel() {
JLabel jl = new JLabel("This is resizeable JPanel at Runtime");
jl.setBackground(Color.green);
jl.setOpaque(true);
jl.setFont(new Font("Helvetica", Font.BOLD, 18));
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
jp.setBorder(new LineBorder(Color.black, 3, false));
jp.add(jl, BorderLayout.NORTH);
jp.setBounds(50,50,400,200);
add(jp);
public static void main(String[] args) {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new Resizing());
f.setSize(500,400);
f.setLocation(100,100);
f.setVisible(true);
class PanelControlAdapter extends MouseInputAdapter {
Resizing host;
Component selectedComponent;
LineBorder black;
LineBorder green;
Point offset = new Point();
Point start = new Point();
boolean dragging = false;
boolean resizing = false;
public PanelControlAdapter(Resizing r) {
host = r;
black = new LineBorder(Color.black, 3, false);
green = new LineBorder(Color.green, 3, false);
public void mouseMoved(MouseEvent e) {
Point p = e.getPoint();
boolean hovering = false;
Component c = host.getComponent(0);
Rectangle r = c.getBounds();
if(r.contains(p)) {
hovering = true;
if(selectedComponent != c) {
if(selectedComponent != null) // reset
((JComponent)selectedComponent).setBorder(black);
selectedComponent = c;
((JComponent)selectedComponent).setBorder(green);
if(overBorder(p))
setCursor(p);
else if(selectedComponent.getCursor() != Cursor.getDefaultCursor())
selectedComponent.setCursor(Cursor.getDefaultCursor());
if(!hovering && selectedComponent != null) {
((JComponent)selectedComponent).setBorder(black);
selectedComponent = null;
private boolean overBorder(Point p) {
Rectangle r = selectedComponent.getBounds();
JComponent target = (JComponent)selectedComponent;
Insets insets = target.getBorder().getBorderInsets(target);
// Assume uniform border insets.
r.grow(-insets.left, -insets.top);
return !r.contains(p);
private void setCursor(Point p) {
JComponent target = (JComponent)selectedComponent;
AbstractBorder border = (AbstractBorder)target.getBorder();
Rectangle r = target.getBounds();
Rectangle ir = border.getInteriorRectangle(target, r.x, r.y, r.width, r.height);
int outcode = ir.outcode(p.x, p.y);
Cursor cursor;
switch(outcode) {
case Rectangle.OUT_TOP:
cursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
break;
case Rectangle.OUT_TOP + Rectangle.OUT_LEFT:
cursor = Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR);
break;
case Rectangle.OUT_LEFT:
cursor = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR);
break;
case Rectangle.OUT_LEFT + Rectangle.OUT_BOTTOM:
cursor = Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR);
break;
case Rectangle.OUT_BOTTOM:
cursor = Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR);
break;
case Rectangle.OUT_BOTTOM + Rectangle.OUT_RIGHT:
cursor = Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR);
break;
case Rectangle.OUT_RIGHT:
cursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
break;
case Rectangle.OUT_RIGHT + Rectangle.OUT_TOP:
cursor = Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR);
break;
default:
cursor = Cursor.getDefaultCursor();
selectedComponent.setCursor(cursor);
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
if(selectedComponent != null) {
Rectangle r = selectedComponent.getBounds();
if(selectedComponent.getCursor() == Cursor.getDefaultCursor()) {
offset.x = p.x - r.x;
offset.y = p.y - r.y;
dragging = true;
} else {
start = p;
resizing = true;
public void mouseReleased(MouseEvent e) {
dragging = false;
resizing = false;
public void mouseDragged(MouseEvent e) {
Point p = e.getPoint();
if(dragging || resizing) {
Rectangle r = selectedComponent.getBounds();
if(dragging) {
r.x = p.x - offset.x;
r.y = p.y - offset.y;
selectedComponent.setLocation(r.x, r.y);
} else if(resizing) {
int type = selectedComponent.getCursor().getType();
switch(type) {
case Cursor.N_RESIZE_CURSOR:
r.height -= p.y - start.y;
r.y = p.y;
break;
case Cursor.NW_RESIZE_CURSOR:
r.width -= p.x - start.x;
r.x = p.x;
r.height -= p.y - start.y;
r.y = p.y;
break;
case Cursor.W_RESIZE_CURSOR:
r.width -= p.x - start.x;
r.x = p.x;
break;
case Cursor.SW_RESIZE_CURSOR:
r.width -= p.x - start.x;
r.x = p.x;
r.height += p.y - start.y;
break;
case Cursor.S_RESIZE_CURSOR:
r.height += p.y - start.y;
break;
case Cursor.SE_RESIZE_CURSOR:
r.width += p.x - start.x;
r.height += p.y - start.y;
break;
case Cursor.E_RESIZE_CURSOR:
r.width += p.x - start.x;
break;
case Cursor.NE_RESIZE_CURSOR:
r.width += p.x - start.x;
r.height -= p.y - start.y;
r.y = p.y;
break;
default:
System.out.println("Unexpected resize type: " + type);
selectedComponent.setBounds(r.x, r.y, r.width, r.height);
start = p;
} -
After succesfully coding a couple of panels to show correctly in my frame, I continued to develop the menu until the formatting for one of my menus reset itself. I'm not sure what happened, and if I message out the things I've changed it still doesn't format correctly. Basically the menu consists of a frame, with each menu as a smaller sized panel in the middle of the frame. The EquipPanel now resizes itself to take over the entire frame, rather than just be a smaller box inside the frame. Any help would be great, if you can spot the code or even suggest another plan of attack to build the menu. Here's the code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class NecMenu implements ActionListener
Font f;
Font f2;
Dimension maxSize;
Container c;
JLabel title;
JLabel sign;
JPanel currentPanel;
JPanel mainPanel;
JPanel equipPanel;
JPanel gangPanel;
JButton viewGangs;
JButton viewEquip;
JButton viewMain;
JFrame frame;
int titwid;
public NecMenu()
mainPanel = new MainPanel();
equipPanel = new EquipPanel();
gangPanel = new GangPanel();
title = new JLabel( "Title", JLabel.CENTER );
f = new Font( "Lucida Sans", 1, 30 );
viewGangs = new JButton( "View Gangs" );
viewEquip = new JButton( "View Equipment" );
viewMain = new JButton( "Main Menu" );
sign = new JLabel( "Signature" );
f2 = new Font( "Lucida Sans", 2, 14 );
title.setFont( f );
sign.setFont( f2 );
runMenu();
void addComponentsToPane(Container pane)
Dimension size = title.getPreferredSize();
currentPanel = mainPanel;
pane.add( title );
pane.add( sign );
pane.add( viewMain );
mainPanel.setBorder( new LineBorder( Color.black, 3 ) );
mainPanel.setBounds( 10, 46, frame.getWidth() - 20 - 6, 490 );
equipPanel.setBorder( new LineBorder( Color.black, 3 ) );
equipPanel.setBounds( 10, 46, frame.getWidth() - 20 - 6, 490 );
gangPanel.setBorder( new LineBorder( Color.black, 3 ) );
gangPanel.setBounds( 10, 46, frame.getWidth() - 20 - 6, 490 );
pane.add( mainPanel );
pane.add( gangPanel );
pane.add( equipPanel );
gangPanel.setVisible( false );
equipPanel.setVisible( false );
title.setBounds( ( frame.getWidth() - size.width ) / 2, 5, size.width, size.height );
size = sign.getPreferredSize();
sign.setBounds( 780 - size.width, 540, size.width, size.height );
viewGangs.setBounds( 250, 200, 300, 30 );
viewEquip.setBounds( 250, 300, 300, 30 );
viewMain.setBounds( 250, 538, 300, 28 );
viewGangs.addActionListener( this );
viewEquip.addActionListener( this );
viewMain.addActionListener( this );
mainPanel.add( viewGangs );
mainPanel.add( viewEquip );
void createAndShowGUI()
frame = new JFrame( "Nec" );
frame.setSize( 800, 600 );
JFrame.setDefaultLookAndFeelDecorated( true );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
addComponentsToPane( frame.getContentPane() );
frame.setVisible( true );
void runMenu()
javax.swing.SwingUtilities.invokeLater( new Runnable()
public void run()
createAndShowGUI();
public void actionPerformed( ActionEvent a )
Object source = a.getSource();
if ( source == viewGangs )
changePanel( gangPanel );
else if ( source == viewEquip )
changePanel( equipPanel );
else if ( source == viewMain )
changePanel( mainPanel );
void changePanel( JPanel panel )
currentPanel.setVisible( false );
panel.setVisible( true );
currentPanel = panel;
}and EquipPanel
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JComponent.*;
public class EquipPanel extends JPanel implements ChangeListener, ActionListener
EquipPanel[] tabs;
String[] tabNames;
JTabbedPane pane;
Font f;
EquipPanel()
int i;
tabs = new EquipPanel[ Equipment.types.size() ];
tabNames = new String[ Equipment.types.size() ];
pane = new JTabbedPane( JTabbedPane.TOP );
f = new Font( "Lucida Sans", 0, 14 );
for ( i = 0; i < Equipment.types.size(); i++ )
tabNames[ i ] = Equipment.types.get( i ).toString();
tabs[ i ] = new EquipPanel( tabNames[ i ], this );
pane.add( tabNames[ i], tabs[ i ] );
pane.addChangeListener( tabs[ i ] );
this.add( pane );
this.setBounds( 400,200,500,300);
EquipPanel( String name, EquipPanel main )
ArrayList arr = Equipment.determineArray( name );
JButton[] buttons = new JButton[ arr.size() ];
for ( int i = 0; i < arr.size() - 1; i++ )
buttons[ i ] = new JButton( arr.get( i + 1 ).toString() );
add( buttons[ i ] );
buttons[ i ].addActionListener( main );
public void stateChanged( ChangeEvent ce )
public void actionPerformed( ActionEvent ae )
String source =( ( JButton ) ae.getSource() ).getText();
}and MainPanel if you wanted to see it in action
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class MainPanel extends JPanel
public MainPanel()
setName( "Main" );
}Thanks guysRead this section from the Swing tutorial on "Using Layout Managers":
http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html
Absolute Positioning is what you want. -
A problem with java program(reset problem in java GUY)
I do not know how to make the button reset,my program only could reset diagram but button.If any one who could help me to solve this problem.The problem is When the reset button is pressed, the image should immediately revert to the black square, and the 4 widgets listed above should show values that
correspond to the black square.
import java.awt.*;
import javax.swing.*;
public class DrawPanel extends JPanel {
public final static int CIRCLE = 1, SQUARE = 2;
private int shape;
private boolean fill;
private boolean showStatus;
private int shapeSize = 100;
private Color foreground;
// draw a specified shape
public void paintComponent (Graphics g){
super.paintComponent(g);
// find center
int x=(getSize().width-shapeSize)/2;
int y=(getSize().height-shapeSize)/2;
if (shape == CIRCLE) {
if (fill == true){
g.setColor(foreground);
g.fillOval(x, y, shapeSize, shapeSize);
else{
g.setColor(foreground);
g.drawOval(x, y, shapeSize, shapeSize);
else if (shape == SQUARE){
if (fill == true){
g.setColor(foreground);
g.fillRect(x, y, shapeSize, shapeSize);
else{
g.setColor(foreground);
g.drawRect(x, y, shapeSize, shapeSize);
// set showStatus value
public void setShowStatus (boolean s) {
showStatus = s;
// return showstatus value
public boolean getShowStatus () {
return showStatus;
// set fill value
public void setFill(boolean isFill) {
fill = isFill;
// set shape value
public void setShape(int shapeToDraw) {
shape = shapeToDraw;
// set shapeSize value
public void setShapeSize(int newShapeSize) {
shapeSize = newShapeSize;
// set foreground value
public void setForeground(Color newColor) {
foreground = newColor;
// repaint DrawPanel
public void draw (){
if(showStatus == true)
repaint();
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class shapes extends JFrame {
private JPanel buttonPanel; // panel for buttons
private DrawPanel myPanel; // panel for shapes
private JButton resetButton;
private JComboBox colorComboBox;
private JRadioButton circleButton, squareButton;
private ButtonGroup radioGroup;
private JCheckBox filledButton;
private JSlider sizeSlider;
private boolean isShow;
private int shape;
private boolean isFill=true;
private String colorNames[] = {"black", "blue", "cyan", "darkGray", "gray",
"green", "lightgray", "magenta", "orange",
"pink", "red", "white", "yellow"}; // color names list in ComboBox
private Color colors[] = {Color.black, Color.blue, Color.cyan, Color.darkGray,
Color.gray, Color.green, Color.lightGray, Color.magenta,
Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
public shapes() {
super("Draw Shapes");
// creat custom drawing panel
myPanel = new DrawPanel(); // instantiate a DrawPanel object
myPanel.setBackground(Color.white);
// set up resetButton
// register an event handler for resetButton's ActionEvent
resetButton = new JButton ("reset");
resetButton.addActionListener(
// anonymous inner class to handle resetButton events
new ActionListener() {
// draw a black filled square shape after clicking resetButton
public void actionPerformed (ActionEvent event) {
// call DrawPanel method setShowStatus and pass an parameter
// to decide if show the shape
myPanel.setShowStatus(true);
isShow = myPanel.getShowStatus();
shape = DrawPanel.SQUARE;
// call DrawPanel method setShape to indicate shape to draw
myPanel.setShape(shape);
// call DrawPanel method setFill to indicate to draw a filled shape
myPanel.setFill(true);
// call DrawPanel method draw
myPanel.draw();
myPanel.setFill(true);
myPanel.setForeground(Color.black);
}// end anonymous inner class
);// end call to addActionListener
// set up colorComboBox
// register event handlers for colorComboBox's ItemEvent
colorComboBox = new JComboBox(colorNames);
colorComboBox.setMaximumRowCount(5);
colorComboBox.addItemListener(
// anonymous inner class to handle colorComboBox events
new ItemListener() {
// select shape's color
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED)
// call DrawPanel method setForeground
// and pass an element value of colors array
myPanel.setForeground(colors[colorComboBox.getSelectedIndex()]);
myPanel.draw();
}// end anonymous inner class
); // end call to addItemListener
// set up a pair of RadioButtons
// register an event handler for RadioButtons' ItemEvent
squareButton = new JRadioButton ("Square", true);
circleButton = new JRadioButton ("Circle", false);
radioGroup = new ButtonGroup();
radioGroup.add(squareButton);
radioGroup.add(circleButton);
squareButton.addItemListener(
// anonymous inner class to handle squareButton events
new ItemListener() {
public void itemStateChanged (ItemEvent event) {
if (isShow==true) {
shape = DrawPanel.SQUARE;
myPanel.setShape(shape);
myPanel.draw();
}// end anonymous inner class
);// end call to addItemListener
circleButton.addItemListener(
// anonymous inner class to handle circleButton events
new ItemListener() {
public void itemStateChanged (ItemEvent event) {
if (isShow==true) {
shape = DrawPanel.CIRCLE;
myPanel.setShape(shape);
myPanel.draw();
else
System.out.println("Please click Reset button first");
}// end anonymous inner class
);// end call to addItemListener
// set up filledButton
// register an event handler for filledButton's ItemEvent
filledButton = new JCheckBox("Filled", true);
filledButton.addItemListener(
// anonymous inner class to handle filledButton events
new ItemListener() {
public void itemStateChanged (ItemEvent event) {
if (isShow==true) {
if (event.getStateChange() == ItemEvent.SELECTED) {
isFill=true;
myPanel.setFill(isFill);
myPanel.draw();
else {
isFill=false;
myPanel.setFill(isFill);
myPanel.draw();
else
System.out.println("Please click Reset button first");
}// end anonymous inner class
);// end call to addItemListener
// set up sizeSlider
// register an event handler for sizeSlider's ChangeEvent
sizeSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, 100);
sizeSlider.setMajorTickSpacing(10);
sizeSlider.setPaintTicks(true);
sizeSlider.addChangeListener(
// anonymous inner class to handle sizeSlider events
new ChangeListener() {
public void stateChanged(ChangeEvent event) {
myPanel.setShapeSize(sizeSlider.getValue());
myPanel.draw();
}// end anonymous inner class
);// end call to addChangeListener
// set up panel containing buttons
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 1, 0, 50));
buttonPanel.add(resetButton);
buttonPanel.add(filledButton);
buttonPanel.add(colorComboBox);
JPanel radioButtonPanel = new JPanel();
radioButtonPanel.setLayout(new GridLayout(2, 1, 0, 20));
radioButtonPanel.add(squareButton);
radioButtonPanel.add(circleButton);
buttonPanel.add(radioButtonPanel);
// attach button panel & draw panel to content panel
Container container = getContentPane();
container.setLayout(new BorderLayout(10,10));
container.add(myPanel, BorderLayout.CENTER);
container.add(buttonPanel, BorderLayout.EAST);
container.add(sizeSlider, BorderLayout.SOUTH);
setSize(500, 400);
setVisible(true);
public static void main(String args[]) {
shapes application = new shapes();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}Many thanksWho is this Java guy anyway?
-
Thin JPanel when used as TableCellRenderer
Hello,
I'm using JPanels as renderers for my single column JTable.
Even though im using FlowLayout( FlowLayout.LEFT ) and only adding JLabels, the height of each row is about 1.5 times that of a normal JTable row.
Is there anyway to slim it down? Decreasing the font or just using setRowHeight doesn't really work.
//JohnBy default a FlowLayout uses insets to position the components. Reset the insets to 0.
-
hi people
I have been trying to get a jpanel show when the main is initializes. I don't get any errors. I am using Netbeans as my IDE. The jpanel I want to show is timerPanel. I am very new to java so I am sure that it is something simple. does anyone know what I am going wrong?
public class Timer extends javax.swing.JPanel {
public static void main(String[] args){
new Timer().setVisible(true);
/** Creates new form timer */
public Timer() {
initComponents();
JPanel panel= new JPanel();
panel.setVisible(true);
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
timerPanel = new javax.swing.JPanel();
display = new javax.swing.JLabel();
start = new javax.swing.JButton();
pause = new javax.swing.JButton();
reset = new javax.swing.JButton();
save = new javax.swing.JButton();
exit = new javax.swing.JButton();
timerPanel.setBackground(new java.awt.Color(232, 227, 234));
display.setBackground(new java.awt.Color(217, 217, 62));
display.setText("wa");
display.setToolTipText("shows hr:mins:sec");
start.setText("Start");
start.setToolTipText("Starts Timer");
start.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startActionPerformed(evt);
pause.setText("Pause");
pause.setToolTipText("To Restart Press");
pause.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pauseActionPerformed(evt);
reset.setText("Reset");
reset.setToolTipText("Clears Timer");
reset.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resetActionPerformed(evt);
save.setText("Save");
save.setToolTipText("Saves Timer Amount");
save.setActionCommand("Save");
save.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveActionPerformed(evt);
exit.setText("Exit");
exit.setToolTipText("Exits without saving");
exit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitActionPerformed(evt);
javax.swing.GroupLayout timerPanelLayout = new javax.swing.GroupLayout(timerPanel);
timerPanel.setLayout(timerPanelLayout);
timerPanelLayout.setHorizontalGroup(
timerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(timerPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(timerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(display, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, timerPanelLayout.createSequentialGroup()
.addComponent(start)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pause)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(reset)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 94, Short.MAX_VALUE)
.addComponent(save)
.addGap(4, 4, 4)
.addComponent(exit)
.addContainerGap())
timerPanelLayout.setVerticalGroup(
timerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, timerPanelLayout.createSequentialGroup()
.addContainerGap(47, Short.MAX_VALUE)
.addComponent(display, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(timerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(start)
.addComponent(pause)
.addComponent(reset)
.addComponent(save)
.addComponent(exit))
.addContainerGap())
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(timerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(timerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(287, Short.MAX_VALUE))
}// </editor-fold>
private void startActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
private void pauseActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
private void resetActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
private void saveActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
private void exitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Variables declaration - do not modify
private javax.swing.JLabel display;
private javax.swing.JButton exit;
private javax.swing.JButton pause;
private javax.swing.JButton reset;
private javax.swing.JButton save;
private javax.swing.JButton start;
private javax.swing.JPanel timerPanel;
// End of variables declaration
}gishaust wrote:
Who would I ask?The compiler and JVM!
Change your code to include a JFrame, compile it, run it. You will soon find out.
Maybe you are looking for
-
after some screwing around (disable user access control, install tweak util to allow unsigned drivers) most features of my macbook are now working in windows 7. battery life looks abysmal as it was in vista, but i'll deal with that later. the major g
-
Evening to all. Purchased skype number yesterday, have gone through what I think is all of the replies, and tried them all, my skype number is still always busy..........please help. Thankyou
-
How am I supposed to choose between all these DE's?
For the purposes of my post: DE = WM Hey, It's hard enough for me to choose which distribution to use. I think the next biggest decision for me is which DE I am to use. It's most likely between: - KDE - XFCE4 - Fluxbox - Enlightenment KDE Why I shoul
-
Object type not maintained for message type
Hi, I am working on chnage pointers for Vendor classification data. when I execute the program RBDMIDOC (BD21) I get the error Object type LIFNR not maintained for Message type. If anyone has worked on change pointers, please guide me in solving this
-
Can anybody shed some more light on the following restore error output. I am trying to restore a ds backup form another server dsee6.3 sparc to a dsee6.3 x86 server. In the error it states that the backup set may not be valid although I know it is va