Java Swing: JComboBox setEditable(true)
How to limit the length of the text in Jcombobox with seteditable true to 255 characters.So that user can't enter text more then 255 characters.
You can get editor from the JComboBox. In the editor get a text filed used for edit. You can cast it to JTextField in the simplest case. Then add a DocumentFilter to the JTextFiled's document. Override the methods to check existing Document's length and ignore edits when limit is achieved.
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
fb.insertString(offset, string, attr);
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
fb.replace(offset, length, text, attrs);
}
Similar Messages
-
JTable JComboBox setEditable(true) does what?
The JTable column uses JComboBox. What is expected of combo.setEditable(true)? Here is the relevant code.
Thanks
for (int k = 0; k < m_data.getColumnCount (); k++)
TableCellRenderer renderer = null;
TableCellEditor editor = null;
if (k==0) /* sysname column */
renderer=new DefaultTableCellRenderer();
JComboBox combo= new JComboBox(sys_names);
combo.setRequestFocusEnabled(false);
combo.setBackground(Color.yellow);
combo.setEditable(true);
combo.getEditor().getEditorComponent().setBackground(Color.blue)
editor=new DefaultCellEditor(combo);
[\code]That fits my limited experience. I'm currently only providing non-editable combos as the focus handling and traversal gets messy with editable ones. This may be due tosome other code I've put in to alter the default JTable behaviour, but I havn't had time to look into it yet.
-
How update or modified an Object within an jComboBox.setEditable(true)
Hello,
I would like to modified the name of an object which is displayed within a jComboBox which is setEditable(true). As we can do within a jTable with the setValueAt method.
Here is a sample of my code:
public class MyFrame extends JFrame {
Object[] listeVoiture = new Object[2];
listeVoiture [0] = new Voiture("Clio", "458 AVB 38");
listeVoiture [1] = new Voiture("Megane", "4567 ZE 69");
MyComboBoxModel voitureComboBoxModel = new MyComboBoxModel(listeVoiture);
JComboBox jComboBoxListeVoiture = new JComboBox(voitureComboBoxModel);
jComboBoxListeVoiture.setEditable(true);
public class Voiture {
Private String modele;
Private String numPlaque;
public Voiture(String mod, String plaq){
modele= mod;
numplaq=plaq;
public String toString(){
return modele;
public void setModele(String mod){
modele=mod;
public class MyComboBoxModel extends DefaultComboBoxModel {
public MyComboBoxModel(Object[] items) {
super(items);
public void setSelectedItem(Object anObject) {
Voiture voit = (Voiture)this.getSelectedItem();
voit .setModele(anObject.toString());
super.setSelectedItem(app);
Thank you for your advises, Romain.You can do a remove/insert... (why doesn't DefaultComboBoxModel have a set method?)
Kind regards,
Levi -
Location Manager - Java Swing / DB Related
OK the following code is part of my project. I have a Location manager which will manage the location of items within a warehouse. The panel itself contains a Combo box with Product ID's. What I want to do is when an item is selected from the combo box, the data associated with this selected item (product id and product location) is displayed in two textfields below the combo box. Here is my code:
package orderproc;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.net.URL;
import java.sql.*;
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Company: </p>
* @author unascribed
* @version 1.0
public class EditItemLoc extends JApplet implements ActionListener, ItemListener {
JPanel westPanel;
JPanel eastPanel;
JPanel editPanel;
GridBagLayout gbl;
GridBagConstraints gbc;
protected JLabel lblProductDescription, lblProductID, lblLocation, lblNewLoc;
protected JTextField txtProductID, txtLocation, txtNewLoc;
DefaultComboBoxModel model = new DefaultComboBoxModel();
JComboBox cmbProductDescription = new JComboBox(model);
String res;
JButton btnExit, btnCancel, btnSubmit;
public EditItemLoc() {
try
//connect to database
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Drivers loaded");
String url = "jdbc:odbc:wms";
Connection con = DriverManager.getConnection(url,"root","");
System.out.println("Connection established");
Statement stmt = con.createStatement();
System.out.println("Statement created");
ResultSet res = stmt.executeQuery("SELECT ProductDescription FROM productinfo");
while(res.next())
{// add the result set ProductDescription to the combobox
cmbProductDescription.addItem(res.getString("ProductDescription"));
catch(Exception e)
gbl = new GridBagLayout();
gbc = new GridBagConstraints();
westPanel = new JPanel();
westPanel.setLayout(gbl);
eastPanel = new JPanel();
getContentPane().setLayout(new BorderLayout());
getContentPane().add(westPanel, BorderLayout.CENTER);
getContentPane().add(eastPanel, BorderLayout.SOUTH);
lblProductDescription = new JLabel("ProductDescription: ");
lblProductID = new JLabel("Product ID: ");
lblLocation = new JLabel("Current Location: ");
lblNewLoc = new JLabel("New Location: ");
txtProductID = new JTextField(20);
txtLocation = new JTextField(10);
txtNewLoc= new JTextField(10);
btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(this);
eastPanel.add(btnSubmit);
btnExit = new JButton("<<<<Back");
btnExit.addActionListener(this);
eastPanel.add(btnExit);
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(this);
eastPanel.add(btnCancel);
gbc.anchor = GridBagConstraints.NORTHEAST; // Align labels
gbc.gridx = 1;
gbc.gridy = 1;
gbl.setConstraints(lblProductDescription, gbc);
westPanel.add(lblProductDescription);
gbc.gridx = 1;
gbc.gridy = 2;
gbl.setConstraints(lblProductID, gbc);
westPanel.add(lblProductID);
gbc.gridx = 1;
gbc.gridy = 3;
gbl.setConstraints(lblLocation, gbc);
westPanel.add(lblLocation);
gbc.gridx = 1;
gbc.gridy = 4;
gbl.setConstraints(lblNewLoc, gbc);
westPanel.add(lblNewLoc);
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.gridx = 2;
gbc.gridy = 1;
gbl.setConstraints(cmbProductDescription, gbc);
// Register item listener
westPanel.add(cmbProductDescription);
gbc.gridx = 2;
gbc.gridy = 2;
gbl.setConstraints(txtProductID, gbc);
txtProductID.setEditable(false);
txtProductID.setText("");
westPanel.add(txtProductID);
gbc.gridx = 2;
gbc.gridy = 3;
gbl.setConstraints(txtLocation, gbc);
txtLocation.setEditable(false);
txtLocation.setText("");
westPanel.add(txtLocation);
gbc.gridx = 2;
gbc.gridy = 4;
gbl.setConstraints(txtNewLoc, gbc);
txtNewLoc.setEditable(true);
txtNewLoc.setText("");
westPanel.add(txtNewLoc);
public void itemStateChanged(ItemEvent ie) // Item event handling
if(ie.getSource() == cmbProductDescription)
public void actionPerformed(ActionEvent ae) // Action event handling
if(ae.getSource() == btnExit)
setVisible(false);
public void init()
EditItemLoc myEditItemLoc = new EditItemLoc();Not sure. I am using a JList to do a very similar thing to you and it works for me. They share same datamodel so I thought it would work for you.
try passing it to a textfield & seeing if that gives you the correct database entry.
aName = new JTextField(20);
aName.addActionListener(new DetailListener());
String name = listModel.getElementAt(list.getSelectedIndex()).toString();
aName.setText(name);
class DetailListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try{
details();
} // end try
catch (Exception exc){}
public void details(){
//.... your resultset here
}That way, you are dealing with a string & not an index. I am a novice at this & this may not be the 'correct' way to do it but I find it easier to deal with a string than an index. woks for me at the moment :) -
Java 6 JComboBox Regression?
Today I decided to try out my application with the Java 6 JRE. I was quite impressed until I found that the JComboBox is no longer firing action events when the user selects the same item from the list. Action events are fired in JRE 1.4 and 1.5, but it breaks in 1.6.
Here is a simple test case:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class ActionTest extends JFrame {
public ActionTest() {
String[] items = { "item1", "item2", "item3"};
JComboBox jComboBox = new JComboBox(items);
jComboBox.addActionListener(new ActionHandler());
getContentPane().add(jComboBox);
pack();
setVisible(true);
public static void main(String[] args) {
ActionTest actionTest = new ActionTest();
class ActionHandler implements ActionListener {
public final void actionPerformed(final ActionEvent e) {
System.out.println("Action Event Fired");
When the above code is run under java 1.4 or 1.5, an action event is fired even when the user selects the same item from the list. According to the docs this is the correct behaviour. However, when the above code is run under 1.6, no action events are fired when the user selects the same item from the list. This seems like a rather serious regression. Has anyone else experienced this?
RobertAfter a long research and many many tries, if finallay found a workaround.
Below is a working demo.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.Vector;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.event.ListDataEvent;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class AlwaysSelectableComboBoxDemo extends JFrame {
public static void main(String[] args) {
AlwaysSelectableComboBoxDemo frame = new AlwaysSelectableComboBoxDemo();
frame.setMinimumSize(new Dimension(150,50));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
public AlwaysSelectableComboBoxDemo() {
final AlwaysSelectableComboBox combi = new AlwaysSelectableComboBox(
new Object[]{"Item 1","Item 2", "Item 3"});
combi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("Yeah");
combi.addPopupMenuListener(new PopupMenuListener(){
private boolean isCanceled = false;
private Object oldSelection = null;
public void popupMenuCanceled(PopupMenuEvent e) {
isCanceled = true;
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
JComboBox comboBox = ((JComboBox)e.getSource());
if(!isCanceled && comboBox.getSelectedItem() == oldSelection) {
comboBox.contentsChanged(new ListDataEvent(e.getSource(),ListDataEvent.CONTENTS_CHANGED,0,0));
isCanceled = false;
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
oldSelection = ((JComboBox)e.getSource()).getSelectedItem();
this.add(combi);
public class AlwaysSelectableComboBox extends JComboBox implements Serializable
public AlwaysSelectableComboBox(ComboBoxModel aModel){
super(aModel);
public AlwaysSelectableComboBox(final Object items[]) {
super(items);
public AlwaysSelectableComboBox(Vector items) {
super(items);
public AlwaysSelectableComboBox() {
super();
public void contentsChanged(ListDataEvent e) {
selectedItemReminder = null;
super.contentsChanged(e);
} -
PL/SQL and Java Swing interface
Everybody in this forum knows that Oracle is the best database around
with many functionalities, stability, performance, etc. We also know
that PL/SQL is a great language to manipulate information directly
in the database with many built in functions, OOP capability,
transaction control, among other features. Today an application that
manipulates information, which needs user interface, requires components
to be developed using different technologies and normally running in
different servers or machines. For example, the interface is done using
a dynamic HTML generator like JSP, PHP, PL/SQL Web Toolkit, etc.
This page is executed in an application server like Oracle iAS or
Tomcat, just to name two, which in turn access a database like Oracle to
build the HTML. Also rich clients like Java applets require an intermediate
server to access the database (through servlets for example) although
it is possible to access the database directly but with security issues.
Another problem with this is that complexity increases a lot, many
technologies, skills and places to maintain code which leads to a greater
failure probability. Also, an application is constantly evolving, new
calculations are added, new tables, changed columns. If you have an
application with product code for example and you need to increase its
size, you need to change it in the database, search for all occurrences
of it in the middle-tier code and perhaps adjust interfaces. Normally
there is no direct dependency among the tier components. On another
issue, many application interfaces today are based on HTML which doesn't
have interactive capabilities like rich-client interfaces. Although it
is possible to simulate many GUI widgets with JavaScript and DHTML, it is
far from the interactive level we can accomplish in rich clients like
Java Swing, Flash MX, Win32, etc. HTML is also a "tag-based" language
originally created to publish documents so even small pages require
many bytes to be transmitted, far beyond of what we see on the screen.
Even in fast networks you have a delay time to wait the page to be
loaded. Another issue, the database is in general the central location
for all kinds of data. Most applications relies on it for security,
transaction and availability. My proposal is to use Oracle as the
central location for interface, processing and data. With this approach
we can create not only the data manipulation procedures in the database,
but procedures that also control and manage user interfaces. Having
a Oracle database as the central location for all components has many
advantages:
- Unique point of maintenance, backup and restore
- Integrated database security
- One language for everything, PL/SQL or Java (even both if desired)
- Inherited database cache, transaction and processing optimizations
- Direct access to the database dictionary
- Application runs on Oracle which has support for many platforms.
- Transparent use of parallel processing, clusters and future
background technologies
Regarding the interface, I already created a Java applet renderer
which receives instructions from the database on how to create GUI
objects and how to respond to events. The applet is only 8kb and can
render any Swing or AWT object/event. The communication is done
through HTTP or HTTPS using Oracles's MOD_PLSQL included in the Apache
HTTP server which comes with the database or application server (iAS).
I am also creating a database framework and APIs in PL/SQL to
create and manipulate the client interface. The applet startup is
very fast because it is very small, you don't need to download large
classes with the client interface. Execution is done "on-demand"
according to instructions received from the database. The instructions
are very optimized in terms of network bandwidth and based on preliminary
tests it can be up to 1/10 of a similar HTML screen. Less network usage
means faster response and means that even low speed connections will
have a good performance (a future development can be to use this in
wireless devices like PDAs e even cell phones, just an idea for now).
The applet can also be executed standalone by using Java Web Start.
With this approach no business code, except the interface, is executed
on the client. This means that alterations in the application are
dynamically reflected in the client, no need to "re-download" the
application. Events are transmitted when required only so network
usage is minimized. It is also possible to establish triggering
events to further reduce network usage. Since the protocol used is
HTTP (which is stateless), the database framework I am creating will
be responsible to maintain the state of connections, variables, locks
and session information, so the developer don't need to worry about it.
The framework will have many layers, from communication up to
application so there will be pre-built functions to handle queries,
pagination, lock, mail, log, etc. The final objective is to have a
rich client application integrated into the database with minimum
programming and maintenance requirements, not forgetting customization
capabilities. Below is a very small example of what can de done. A
desktop with two windows, each window with two fields, a button with an
image to switch the values, and events to convert the typed text when
leaving the field or double-clicking it. The "leave" event also has an
optimization to only be triggered when the text changes. I am still
developing the framework and adjusting the renderer but I think that all
technical barriers were transposed by now. The framework is still in
the early stages, my guess is that only 5% is done so far. As a future
development even an IDE can be created so we have a graphical environment
do develop applications. I am willing to share this with the PL/SQL
community and listen to ideas and comments.
Example:
create or replace procedure demo1 (
jre_version in varchar2 := '1.4.2_01',
debug_info in varchar2 := 'false',
compress_buffer in varchar2 := 'false',
optimize_buffer in varchar2 := 'true'
) as
begin
interface.initialize('demo1_init','JGR Demo 1',jre_version,debug_info,compress_buffer,optimize_buffer);
end;
create or replace procedure demo1_init as
begin
toolkit.initialize;
toolkit.create_icon('icon',interface.global_root_url||'img/switch.gif');
toolkit.create_internal_frame('frame1','Frame 1',50,50,300,136);
toolkit.create_label('frame1label1','frame1',10,10,50,20,'Field 1');
toolkit.create_label('frame1label2','frame1',10,40,50,20,'Field 2');
toolkit.create_text_field('frame1field1','frame1',50,10,230,20,'Field 1','Field 1',focus_event=>true,mouse_event=>true);
toolkit.create_text_field('frame1field2','frame1',50,40,230,20,'Field 2','Field 2',focus_event=>true,mouse_event=>true);
toolkit.set_text_field_event('frame1field1',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 1','false');
toolkit.set_text_field_event('frame1field2',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 2','false');
toolkit.set_text_field_event('frame1field1',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 1','false');
toolkit.set_text_field_event('frame1field2',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 2','false');
toolkit.create_button('button1','frame1',10,70,100,25,'Switch','Switch the values of "Field 1" and "Field 2"','S','icon');
toolkit.set_button_event('button1',toolkit.action_performed_event,'demo1_switch_fields(''frame1field1'',''frame1field2'')','frame1field1:'||toolkit.get_text_method||',frame1field2:'||toolkit.get_text_method);
toolkit.create_internal_frame('frame2','Frame 2',100,100,300,136);
toolkit.create_label('frame2label1','frame2',10,10,50,20,'Field 1');
toolkit.create_label('frame2label2','frame2',10,40,50,20,'Field 2');
toolkit.create_text_field('frame2field1','frame2',50,10,230,20,'Field 1','Field 1',focus_event=>true,mouse_event=>true);
toolkit.create_text_field('frame2field2','frame2',50,40,230,20,'Field 2','Field 2',focus_event=>true,mouse_event=>true);
toolkit.set_text_field_event('frame2field1',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 1','false');
toolkit.set_text_field_event('frame2field2',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 2','false');
toolkit.set_text_field_event('frame2field1',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 1','false');
toolkit.set_text_field_event('frame2field2',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 2','false');
toolkit.create_button('button2','frame2',10,70,100,25,'Switch','Switch the values of "Field 1" and "Field 2"','S','icon');
toolkit.set_button_event('button2',toolkit.action_performed_event,'demo1_switch_fields(''frame2field1'',''frame2field2'')','frame2field1:'||toolkit.get_text_method||',frame2field2:'||toolkit.get_text_method);
end;
create or replace procedure demo1_set_upper as
begin
toolkit.set_string_method(interface.global_object_name,toolkit.set_text_method,upper(interface.array_event_value(1)));
toolkit.set_text_field_event(interface.global_object_name,toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,upper(interface.array_event_value(1)),'false');
end;
create or replace procedure demo1_set_lower as
begin
toolkit.set_string_method(interface.global_object_name,toolkit.set_text_method,lower(interface.array_event_value(1)));
toolkit.set_text_field_event(interface.global_object_name,toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,lower(interface.array_event_value(1)),'false');
end;
create or replace procedure demo1_switch_fields (
field1 in varchar2,
field2 in varchar2
) as
begin
toolkit.set_string_method(field1,toolkit.set_text_method,interface.array_event_value(2));
toolkit.set_string_method(field2,toolkit.set_text_method,interface.array_event_value(1));
toolkit.set_text_field_event(field1,toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,upper(interface.array_event_value(2)),'false');
toolkit.set_text_field_event(field2,toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,upper(interface.array_event_value(1)),'false');
toolkit.set_text_field_event(field1,toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,lower(interface.array_event_value(2)),'false');
toolkit.set_text_field_event(field2,toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,lower(interface.array_event_value(1)),'false');
end;Is it sound like Oracle Portal?
But you want to save a layer 9iAS.
Basically, that was the WebDB.(Oracle changed the name to Portal when version 3.0)
Over all, I agree with you.
>>Having a Oracle database as the central location for all components has many
>>advantages:
>>
>>- Unique point of maintenance, backup and restore
>>- Integrated database security
>>- One language for everything, PL/SQL or Java (even both if desired)
>>- Inherited database cache, transaction and processing optimizations
>>- Direct access to the database dictionary
>>- Application runs on Oracle which has support for many platforms.
>>- Transparent use of parallel processing, clusters and future
>>background technologies
I would like to build 'ZOPE' inside Oracle DB as a back-end
Using Flash MX as front-end.
Thomas Ku. -
Problem with java swing button and loop
Problem with java swing button and loop
I�m using VAJ 4.0. and I�m doing normal GUI application. I have next problem.
I have in the same class two jswing buttons named start (ivjGStart) and stop (ivjGStop) and private static int field named Status where initial value is 0. This buttons should work something like this:
When I click on start button it must do next:
Start button must set disenabled and Stop button must set enabled and selected. Field status is set to 1, because this is a condition in next procedure in some loop. And then procedure named IzvajajNeprekinjeno() is invoked.
And when I click on stop button it must do next:
Start button must set enabled and selected and Stop button must set disenabled.
Field status is set to 0.
This works everything fine without loop �do .. while� inside the procedure IzvajajNeprekinjeno(). But when used this loop the start button all the time stay (like) pressed. And this means that a can�t stop my loop.
There is java code, so you can get better picture:
/** start button */
public void gStart_ActionEvents() {
try {
ivjGStart.setEnabled(false);
ivjGStop.setEnabled(true);
ivjGStop.setSelected(true);
getJTextPane1().setText("Program is running ...");
Status = 1;
} catch (Exception e) {}
/** stop button */
public void gStop_ActionEvents() {
try {
ivjGStart.setEnabled(true);
ivjGStart.setSelected(true);
ivjGStop.setEnabled(false);
getJTextPane1().setText("Program is NOT running ...");
Status = 0;
} catch (Exception e) {
/** procedure IzvajajNeprekinjeno() */
public void IzvajajNeprekinjeno() { //RunLoop
try {
int zamik = 2000; //delay
do {
Thread.sleep(zamik);
PreberiDat(); //procedure
} while (Status == 1);
} catch (Exception e) {
So, I'm asking what I have to do, that start button will not all the time stay pressed? Or some other aspect of solving this problem.
Any help will be appreciated.
Best regards,
TomiThis is a multi thread problem. When you start the gui, it is running in one thread. Lets call that GUI_Thread so we know what we are talking about.
Since java is task-based this will happen if you do like this:
1. Button "Start" is pressed. Thread running: GUI_Thread
2. Event gStart_ActionEvents() called. Thread running: GUI_Thread
3. Method IzvajajNeprekinjeno() called. Thread running: GUI_Thread
4. Sleep in method IzvajajNeprekinjeno() on thread GUI_Thread
5. Call PreberiDat(). Thread running: GUI_Thread
6. Check status. If == 1, go tho 4. Thread running: GUI_Thread.
Since the method IzvajajNeprekinjeno() (what does that mean?) and the GUI is running in the same thread and the event that the Start button has thrown isn't done yet, the program will go on in the IzvajajNeprekinjeno() method forever and never let you press the Stop-button.
What you have to do is do put either the GUI in a thread of its own or start a new thread that will do the task of the IzvajajNeprekinjeno() method.
http://java.sun.com/docs/books/tutorial/uiswing/index.html
This tutorial explains how to build a multi threaded gui.
/Lime -
How to create the digital clock in java swing application ?
I want to create the running digital clock in my java swing application. Can someone throw some light on this how to do this ? Or If someone has done it then can someone pl. paste the code ?
Thanks.hi prah_Rich,
I have created a digital clock you can use. You will most likely have to change some things to use it in another app although that shouldn't be too hard. A least it can give you some ideas on how to create one of your own. There are three classes.One that creates the numbers. a gui class and frame class.
cheers:)
Hex45
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.geom.*;
public class DigitalClock extends Panel{
BasicStroke stroke = new BasicStroke(4,BasicStroke.CAP_ROUND,
BasicStroke.JOIN_BEVEL);
String hour1, hour2;
String minute1, minute2;
String second1, second2;
String mill1, mill2, mill3;
int hr1, hr2;
int min1, min2;
int sec1, sec2;
int mll1, mll2,mll3;
public void update(Graphics g){
paint(g);
public void paint(Graphics g){
Graphics2D g2D = (Graphics2D)g;
DigitalNumber num = new DigitalNumber(10,10,20,Color.cyan,Color.black);
GregorianCalendar c = new GregorianCalendar();
String hour = String.valueOf(c.get(Calendar.HOUR));
String minute = String.valueOf(c.get(Calendar.MINUTE));
String second = String.valueOf(c.get(Calendar.SECOND));
String milliSecond = String.valueOf(c.get(Calendar.MILLISECOND));
if(hour.length()==2){
hour1 = hour.substring(0,1);
hour2 = hour.substring(1,2);
}else{
hour1 = "0";
hour2 = hour.substring(0,1);
if(minute.length()==2){
minute1 = minute.substring(0,1);
minute2 = minute.substring(1,2);
}else{
minute1 = "0";
minute2 = minute.substring(0,1);
if(second.length()==2){
second1 = second.substring(0,1);
second2 = second.substring(1,2);
}else{
second1 = "0";
second2 = second.substring(0,1);
if(milliSecond.length()==3){
mill1 = milliSecond.substring(0,1);
mill2 = milliSecond.substring(1,2);
mill3 = milliSecond.substring(2,3);
}else if(milliSecond.length()==2){
mill1 = "0";
mill2 = milliSecond.substring(0,1);
mill3 = milliSecond.substring(1,2);
}else{
mill1 = "0";
mill2 = "0";
mill3 = milliSecond.substring(0,1);
hr1 = Integer.parseInt(hour1);
hr2 = Integer.parseInt(hour2);
min1 = Integer.parseInt(minute1);
min2 = Integer.parseInt(minute2);
sec1 = Integer.parseInt(second1);
sec2 = Integer.parseInt(second2);
mll1 = Integer.parseInt(mill1);
mll2 = Integer.parseInt(mill2);
g2D.setStroke(stroke);
g2D.setPaint(Color.cyan);
num.setSpacing(true,8);
num.setSpacing(true,8);
if(hr1==0&hr2==0){
num.drawNumber(1,g2D);
num.setLocation(40,10);
num.drawNumber(2,g2D);
else{
if(!(hr1 == 0)){
num.drawNumber(hr1,g2D);
num.setLocation(40,10);
num.drawNumber(hr2,g2D);
num.setLocation(70,10);
num.drawNumber(DigitalNumber.DOTS,g2D);
num.setLocation(100,10);
num.drawNumber(min1,g2D);
num.setLocation(130,10);
num.drawNumber(min2,g2D);
num.setLocation(160,10);
num.drawNumber(DigitalNumber.DOTS,g2D);
num.setLocation(190,10);
num.drawNumber(sec1,g2D);
num.setLocation(220,10);
num.drawNumber(sec2,g2D);
/*num.setLocation(250,10);
num.drawNumber(DigitalNumber.DOTS,g2D);
num.setLocation(280,10);
num.drawNumber(mll1,g2D);
num.setLocation(310,10);
num.drawNumber(mll2,g2D);
g2D.setPaint(Color.cyan);
if((c.get(Calendar.AM_PM))==Calendar.AM){
g2D.drawString("AM",260,20);
}else{
g2D.drawString("PM",260,20);
String dayOfweek = "";
switch(c.get(Calendar.DAY_OF_WEEK)){
case(Calendar.SUNDAY):
dayOfweek = "Sunday, ";
break;
case(Calendar.MONDAY):
dayOfweek = "Monday, ";
break;
case(Calendar.TUESDAY):
dayOfweek = "Tuesday, ";
break;
case(Calendar.WEDNESDAY):
dayOfweek = "Wednesday, ";
break;
case(Calendar.THURSDAY):
dayOfweek = "Thursday, ";
break;
case(Calendar.FRIDAY):
dayOfweek = "Friday, ";
break;
case(Calendar.SATURDAY):
dayOfweek = "Saturday, ";
break;
String month = "";
switch(c.get(Calendar.MONTH)){
case(Calendar.JANUARY):
month = "January ";
break;
case(Calendar.FEBRUARY):
month = "February ";
break;
case(Calendar.MARCH):
month = "March ";
break;
case(Calendar.APRIL):
month = "April ";
break;
case(Calendar.MAY):
month = "May ";
break;
case(Calendar.JUNE):
month = "June ";
break;
case(Calendar.JULY):
month = "July ";
break;
case(Calendar.AUGUST):
month = "August ";
break;
case(Calendar.SEPTEMBER):
month = "September ";
break;
case(Calendar.OCTOBER):
month = "October ";
break;
case(Calendar.NOVEMBER):
month = "November ";
break;
case(Calendar.DECEMBER):
month = "December ";
break;
int day = c.get(Calendar.DAY_OF_MONTH);
int year = c.get(Calendar.YEAR);
Font font = new Font("serif",Font.PLAIN,24);
g2D.setFont(font);
g2D.drawString(dayOfweek+month+day+", "+year,10,80);
public static void main(String args[]){
AppFrame aframe = new AppFrame("Digital Clock");
Container cpane = aframe.getContentPane();
final DigitalClock dc = new DigitalClock();
dc.setBackground(Color.black);
cpane.add(dc,BorderLayout.CENTER);
aframe.setSize(310,120);
aframe.setVisible(true);
class Task extends TimerTask {
public void run() {
dc.repaint();
java.util.Timer timer = new java.util.Timer();
timer.schedule(new Task(),0L,250L);
class DigitalNumber {
private float x=0;
private float y=0;
private float size=5;
private int number;
private Shape s;
private float space = 0;
public static final int DOTS = 10;
private Color on,off;
DigitalNumber(){
this(0f,0f,5f,Color.cyan,Color.black);
DigitalNumber(float x,float y, float size,Color on,Color off){
this.x = x;
this.y = y;
this.size = size;
this.on = on;
this.off = off;
public void drawNumber(int number,Graphics2D g){
int flag = 0;
switch(number){
case(0):
flag = 125;
break;
case(1):
flag = 96;
break;
case(2):
flag = 55;
break;
case(3):
flag = 103;
break;
case(4):
flag = 106;
break;
case(5):
flag = 79;
break;
case(6):
flag = 94;
break;
case(7):
flag = 97;
break;
case(8):
flag = 127;
break;
case(9):
flag = 107;
break;
case(DOTS):
GeneralPath path = new GeneralPath();
path.moveTo(x+(size/2),y+(size/2)-1);
path.lineTo(x+(size/2),y+(size/2)+1);
path.moveTo(x+(size/2),y+(size/2)+size-1);
path.lineTo(x+(size/2),y+(size/2)+size+1);
g.setPaint(on);
g.draw(path);
return;
//Top
if((flag & 1) == 1){
g.setPaint(on);
}else{
g.setPaint(off);
GeneralPath Top = new GeneralPath();
Top.moveTo(x + space, y);
Top.lineTo(x + size - space, y);
g.draw(Top);
//Middle
if((flag & 2) == 2){
g.setPaint(on);
}else{
g.setPaint(off);
GeneralPath Middle = new GeneralPath();
Middle.moveTo(x + space, y + size);
Middle.lineTo(x + size - space,y + size);
g.draw(Middle);
//Bottom
if((flag & 4) == 4){
g.setPaint(on);
}else{
g.setPaint(off);
GeneralPath Bottom = new GeneralPath();
Bottom.moveTo(x + space, y + (size * 2));
Bottom.lineTo(x + size - space, y + (size * 2));
g.draw(Bottom);
//TopLeft
if((flag & 8) == 8){
g.setPaint(on);
}else{
g.setPaint(off);
GeneralPath TopLeft = new GeneralPath();
TopLeft.moveTo(x, y + space);
TopLeft.lineTo(x, y + size - space);
g.draw(TopLeft);
//BottomLeft
if((flag & 16) == 16){
g.setPaint(on);
}else{
g.setPaint(off);
GeneralPath BottomLeft = new GeneralPath();
BottomLeft.moveTo(x, y + size + space);
BottomLeft.lineTo(x, y + (size * 2) - space);
g.draw(BottomLeft);
//TopRight
if((flag & 32) == 32){
g.setPaint(on);
}else{
g.setPaint(off);
GeneralPath TopRight = new GeneralPath();
TopRight.moveTo(x + size, y + space);
TopRight.lineTo(x + size, y + size - space);
g.draw(TopRight);
//BottomRight
if((flag & 64) == 64){
g.setPaint(on);
}else{
g.setPaint(off);
GeneralPath BottomRight = new GeneralPath();
BottomRight.moveTo(x + size, y + size + space);
BottomRight.lineTo(x + size, y + (size * 2) - space);
g.draw(BottomRight);
public void setSpacing(boolean spacingOn){
if(spacingOn == false){
space = 0;
else{
this.setSpacing(spacingOn,5f);
public void setSpacing(boolean spacingOn,float gap){
if(gap<2){
gap = 2;
if(spacingOn == true){
space = size/gap;
public void setLocation(float x,float y){
this.x = x;
this.y = y;
public void setSize(float size){
this.size = size;
class AppFrame extends JFrame{
AppFrame(){
this("Demo Frame");
AppFrame(String title){
super(title);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} -
Session in java swing??
Hi friends,
I need to create session in java swing...
I have a client running in swing and can access resources in multi-threaded server. I need to validate user using session. But i don't know how to use session.
User has to login with username & password (authentication verified at server using socket communication).
If successful the login frame vanishes and other options are displayed. user has a feature that he can send files to other
user. so i need to use session for security purpose.
Anyone help me with code
Edited by: sathya_vn on Apr 20, 2008 5:41 PMAnyone help me with the code-----> u got tat wrong..
I need to know how to use session with java swing. I requested if anyone has such code....
This is a part of my project .
Am using MySQL Database to store username and password.
Cleint side interface has a frame (first frame--frame1) requesting client to provide login information. The login details <username and password> are sent to server. server validates whether the login info are correct or not and return true or false .
If false the frame1 will show a JOptionPane ... message stating that wrong username or password specified.
If true i need to create a session and other operations are done after session validation. I am using ssl socket.
If u want the code then i have post around 300 or more lines.. -
Problem in compiling JAVA SWING
Dear frens,
I'm new in java swing. I have some knowledge in developing java in DOS, but dont have any knowledge in developing java in gui. I have write a program but it is unable to compile.
I compile like this ----> javac HelloWorldSwing.java
please help me to provide a guide.
thank you
regards
Singaravelanimport javax.swing.*;
import java.lang.*;
public class HelloWorldSwing {
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add the ubiquitous "Hello World" label
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
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();
This is my program, i can compile but cannot run the program -
FirstGUI.java:7: Package java.swing not found in import.
Hi,
I am currently taking JAVA at UGA and am trying to learn the GUI part on my own, since our professor is not going to cover this. This is the first error I get when I compile the program. Any help is greatly appreciated...
Thanks,
Joe
Below is the program...
/* A first GUI. This class creates a label and a button. The count in the label is incremented each
time that the button is pressed.
import java.awt.*;
import java.awt.event.*;
import java.swing.*;
public class FirstGUI extends JPanel {
// Instance variables
private int count = 0; // Number of pushes
private JButton pushButton; // Push button
private JLabel label; // Label
// Initialization method
public void init() {
// Set the layout manager
setLayout( new BorderLayout() );
// Create a label to hold the push count
label = new JLabel("Push Count: 0");
add( label, BorderLayout.NORTH );
label.setHorizontalAlignment( label.CENTER );
// Create a button
pushButton = new JButton("Test Button");
pushButton.addActionListener( new ButtonHandler (this) );
add( pushButton, BorderLayout.SOUTH );
// Method to update push count
public void updateLabel() {
label.setText( "Push Count: " + (++count) );
// Main method to create frame
public static void main(String a[]) {
// Create a frame to hold the application
JFrame fr = new JFrame("FirstGUI ...");
fr.setSize(200,100);
// Create a Window Listener to handle "close" events
WindowHandler 1 = new WindowHandler();
fr.addWindowListener(1);
// Create and initialize a FirstGUI object
FirstGUI fg = new FirstGUI();
fg.init();
// Add the object to the center of the frame
fr.getContentPane().add(fg, BorderLayout.CENTER);
// Display the frame
fr,setVisible( true );
class ButtonHandler implements ActionListener {
private FirstGUI fg;
// Constructor
public ButtonHandler ( FirstGUI fg1 ) {
fg = fg1;
// Execute when an event occurs
public void actionPerformed( ActionEvent e ) {
fg.updateLabel();
}The error is below...
A:\ENGR1140>javac FirstGUI.java
FirstGUI.java:39: Identifier expected.
public static void main(String s[]) {
^
FirstGUI.java:39: 'class' or 'interface' keyword expected.
public static void main(String s[]) {
^
I don't think the actual error is on line 39, I looked in the book that has the code and line 39 is typed just as it is shown in the book.
Below is the program...
/* A first GUI. This class creates a label and a button. The count in the label is incremented each
time that the button is pressed.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FirstGUI extends JPanel {
// Instance variables
private int count = 0; // Number of pushes
private JButton pushButton; // Push button
private JLabel label; // Label
// Initialization method
public void init() {
// Set the layout manager
setLayout( new BorderLayout() );
// Create a label to hold the push count
label = new JLabel("Push Count: 0");
add( label, BorderLayout.NORTH );
label.setHorizontalAlignment( label.CENTER );
// Create a button
pushButton = new JButton("Test Button");
pushButton.addActionListener( new ButtonHandler (this) );
add( pushButton, BorderLayout.SOUTH );
// Method to update push count
public void updateLabel() {
label.setText( "Push Count: " + (++count) );
// Main method to create frame
public static void main(String s[]) {
// Create a frame to hold the application
JFrame fr = new JFrame("FirstGUI ...");
fr.setSize(200,100);
// Create a Window Listener to handle "close" events
WindowHandler 1 = new WindowHandler();
fr.addWindowListener(1);
// Create and initialize a FirstGUI object
FirstGUI fg = new FirstGUI();
fg.init();
// Add the object to the center of the frame
fr.getContentPane().add(fg, BorderLayout.CENTER);
// Display the frame
fr,setVisible( true );
class ButtonHandler implements ActionListener {
private FirstGUI fg;
// Constructor
public ButtonHandler ( FirstGUI fg1 ) {
fg = fg1;
// Execute when an event occurs
public void actionPerformed( ActionEvent e ) {
fg.updateLabel(); -
How to do a dropdownlist in java Swing much like a JMenuBar items
Hi sir,
Here i want to know how to do a dropdownlist in java swing much like a JMenuBar items falling from the top to bottom .Here i should not use JMenuBar in any way.
So that i need to do the dropdownlist by using other feature only.Since i am new to this.I need ur help urgently.Pls do provide the code for this so that i will be so gratefull to u.It is very Urgent.Since i have involved in a project which involves this feature.Pls. do provide the answer as well as the code quickly as possible.
Thanx
m.ananthuuse JComboBox
http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html -
Accelarate the Linux ATI Graphics card for java Swing application
Hi All,
I am using a ATI Radeon 9550 Graphic card in LFS (Linux from the scratch) environment. I want to enable the OpenGL-based pipeline for Java Swing application. I tried the -Dsun.java2d.opengl=true . But the Java swing application getting very slow.
How to overcome this problem?
Any one give the procedure to Accelerate ATI graphics card for Java Swing Application
How to verify Java swing use ATI graphics card ?
Thanks in advance..
Prabhu.SHi All,
I am using a ATI Radeon 9550 Graphic card in LFS (Linux from the scratch) environment. I want to enable the OpenGL-based pipeline for Java Swing application. I tried the -Dsun.java2d.opengl=true . But the Java swing application getting very slow.
How to overcome this problem?
Any one give the procedure to Accelerate ATI graphics card for Java Swing Application
How to verify Java swing use ATI graphics card ?
Thanks in advance..
Prabhu.S -
How to use a DropDownList in Java Swing.Its very very Urgent
Hi Sir,
Here i need to know how to do (or) create a dropdownlist by using Java Swing.I know that there is JMenuBar & JMenuItems without using that when i click a JButton for example the dropdownlist should come from the top to bottom.I have already posted this quesion once.And i found that it has been removed.So i hope that this time i will get a better answer.Pls.do provide the code as well sir.So that i will be very thankful to u.Since i am involved in a project which contains this
feature.It is very very Urgent.So pls.do provide the code i will be waiting for the reply.
Thanx,
m.ananthuuse JComboBox
JComboBox liste = new JComboBox(new Object[]{"azerty","qwerty});the api documentation :
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComboBox.html
the turotial on combobox :
http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html -
Chess: java swing help need
Hi, I have just learn java swing and now creating a chess game. I have sucessfully create a board and able to display chess pieces on the board. By using JLayeredPane, I am able to use drag and drop for the piece. However, there is a problem which is that I can drop the chess piece off the board and the piece would disappear. I have try to solve this problem by trying to find the location that the chess piece is on, store it somewhere and check if the chess piece have been drop off bound. However, I could not manage to solve it. Also, I am very confuse with all these layer thing.
Any suggestion would be very helpful. Thanks in advance
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ChessBoard extends JFrame implements MouseListener, MouseMotionListener
Object currentPosition;
Color currentColor;
Dimension boardSize = new Dimension(600, 600);
JLayeredPane layeredPane;
JPanel board;
JPanel box;
JLabel chessPiece;
int xAdjustment;
int yAdjustment;
public ChessBoard()
// Use a Layered Pane for this this application
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize( boardSize );
layeredPane.addMouseListener( this );
layeredPane.addMouseMotionListener( this );
// Add a chess board to the Layered Pane
board = new JPanel();
// set "board" to the lowest layer (default_layer)
layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
board.setLayout( new GridLayout(8, 8) );
board.setPreferredSize( boardSize );
board.setBounds(0, 0, boardSize.width, boardSize.height);
addShade();
addPiece();
public void addShade()
for (int i = 0; i < 64; i++)
box = new JPanel( new BorderLayout() );
board.add( box, BorderLayout.CENTER );
if( ((i / 8) % 2) == 0)
if( (i % 2) ==0)
box.setBackground(Color.lightGray);
} else {
box.setBackground( Color.white);
} else {
if( (i % 2) ==0)
box.setBackground(Color.white);
} else {
box.setBackground(Color.lightGray);
//Method for adding chess pieces to the board
public void addPiece()
// Add a few pieces to the board
//black pieces
for (int i = 0; i < 64; i++)
//adding black pieces
if (i < 8)
String fileName = i + ".gif";
JLabel blackPieces = new JLabel( new ImageIcon( fileName ) );
JPanel panel = (JPanel)board.getComponent( i );
panel.add( blackPieces );
//adding black pones
if ((i > 7) && (i < 16))
String fileName = "8.gif";
JLabel blackPones = new JLabel( new ImageIcon( fileName ) );
JPanel panel = (JPanel)board.getComponent( i );
panel.add( blackPones );
//jump to white position (Component 48)
if (i == 16) i = 48;
//adding white pones
if(( i > 47 ) && (i < 56))
JLabel whitePones = new JLabel( new ImageIcon("48.gif") );
JPanel panel = (JPanel)board.getComponent( i );
panel.add( whitePones );
//adding white pieces
if (i > 55)
String fileName = i + ".gif";
JLabel whitePieces = new JLabel( new ImageIcon( fileName ) );
JPanel panel = (JPanel)board.getComponent( i);
panel.add( whitePieces );
** Add the selected chess piece to the dragging layer so it can be moved
public void mousePressed(MouseEvent e)
chessPiece = null;
Component c = board.findComponentAt(e.getX(), e.getY());
c.setBackground(Color.red);
if (c instanceof JPanel) return;
Point parentLocation = c.getParent().getLocation();
xAdjustment = parentLocation.x - e.getX();
yAdjustment = parentLocation.y - e.getY();
chessPiece = (JLabel)c;
chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
** Move the chess piece around
public void mouseDragged(MouseEvent me)
if (chessPiece == null) return;
chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);
** Drop the chess piece back onto the chess board
public void mouseReleased(MouseEvent e)
Component c = board.findComponentAt(e.getX(), e.getY());
int x = (int)c.getBounds().getX();
int y = (int)c.getBounds().getY();
System.out.println(c.getLocation());
System.out.println(x + " "+ y);
c.setBackground(currentColor);
if (chessPiece == null) return;
chessPiece.setVisible(false);
if (c instanceof JLabel)
Container parent = c.getParent();
//remove the piece that is capture
parent.remove(0);
parent.add( chessPiece );
else
Container parent = (Container)c;
parent.add( chessPiece );
chessPiece.setVisible(true);
public void mouseClicked(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
private static void createAndShowGUI()
//Make sure we have nice window decorations
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new ChessBoard();
frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
//Display the window
frame.pack();
frame.setResizable( false );
frame.setLocationRelativeTo( null );
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();
}import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ChessBoardRx extends JFrame implements MouseListener, MouseMotionListener
Object currentPosition;
Color currentColor;
Dimension boardSize = new Dimension(600, 600);
JLayeredPane layeredPane;
JPanel board;
JPanel box;
JLabel chessPiece;
int xAdjustment;
int yAdjustment;
Container lastParent;
public ChessBoardRx()
// Use a Layered Pane for this this application
layeredPane = new JLayeredPane();
getContentPane().add(layeredPane);
layeredPane.setPreferredSize( boardSize );
layeredPane.addMouseListener( this );
layeredPane.addMouseMotionListener( this );
// Add a chess board to the Layered Pane
board = new JPanel();
// set "board" to the lowest layer (default_layer)
layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);
board.setLayout( new GridLayout(8, 8) );
board.setPreferredSize( boardSize );
board.setBounds(0, 0, boardSize.width, boardSize.height);
addShade();
addPiece();
// populateBoard();
public void addShade()
for (int i = 0; i < 64; i++)
box = new JPanel( new BorderLayout() );
board.add( box, BorderLayout.CENTER );
if( ((i / 8) % 2) == 0)
if( (i % 2) ==0)
box.setBackground(Color.lightGray);
} else {
box.setBackground( Color.white);
} else {
if( (i % 2) ==0)
box.setBackground(Color.white);
} else {
box.setBackground(Color.lightGray);
//Method for adding chess pieces to the board
public void addPiece()
// Add a few pieces to the board
//black pieces
for (int i = 0; i < 64; i++)
//adding black pieces
if (i < 8)
String fileName = i + ".gif";
JLabel blackPieces = new JLabel( new ImageIcon( fileName ) );
JPanel panel = (JPanel)board.getComponent( i );
panel.add( blackPieces );
//adding black pones
if ((i > 7) && (i < 16))
String fileName = "8.gif";
JLabel blackPones = new JLabel( new ImageIcon( fileName ) );
JPanel panel = (JPanel)board.getComponent( i );
panel.add( blackPones );
//jump to white position (Component 48)
if (i == 16) i = 48;
//adding white pones
if(( i > 47 ) && (i < 56))
JLabel whitePones = new JLabel( new ImageIcon("48.gif") );
JPanel panel = (JPanel)board.getComponent( i );
panel.add( whitePones );
//adding white pieces
if (i > 55)
String fileName = i + ".gif";
JLabel whitePieces = new JLabel( new ImageIcon( fileName ) );
JPanel panel = (JPanel)board.getComponent( i);
panel.add( whitePieces );
private void populateBoard() {
int[][] pos = {
{ 9, 7, 5, 1, 3, 5, 7, 9 },
{ 8, 6, 4, 0, 2, 4, 6, 8 }
for(int j = 0; j < 8; j++) {
String fileName = "chessImages/" + pos[0][j] + ".jpg";
JLabel label = new JLabel( new ImageIcon( fileName ) );
JPanel panel = (JPanel)board.getComponent( j );
panel.add( label );
for(int j = 8; j < 16; j++) {
String fileName = "chessImages/" + 11 + ".jpg";
JLabel label = new JLabel( new ImageIcon( fileName ) );
JPanel panel = (JPanel)board.getComponent( j );
panel.add( label );
for(int j = 56, k = 0; j < 64; j++, k++) {
String fileName = "chessImages/" + pos[1][k] + ".jpg";
JLabel label = new JLabel( new ImageIcon( fileName ) );
JPanel panel = (JPanel)board.getComponent( j );
panel.add( label );
for(int j = 48; j < 56; j++) {
String fileName = "chessImages/" + 10 + ".jpg";
JLabel label = new JLabel( new ImageIcon( fileName ) );
JPanel panel = (JPanel)board.getComponent( j );
panel.add( label );
** Add the selected chess piece to the dragging layer so it can be moved
public void mousePressed(MouseEvent e)
chessPiece = null;
Component c = board.findComponentAt(e.getX(), e.getY());
c.setBackground(Color.red);
if (c instanceof JPanel) return;
lastParent = c.getParent();
Point parentLocation = c.getParent().getLocation();
xAdjustment = parentLocation.x - e.getX();
yAdjustment = parentLocation.y - e.getY();
chessPiece = (JLabel)c;
chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment);
chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight());
layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER);
** Move the chess piece around
public void mouseDragged(MouseEvent me)
if (chessPiece == null) return;
chessPiece.setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment);
** Drop the chess piece back onto the chess board
public void mouseReleased(MouseEvent e)
Component c = board.findComponentAt(e.getX(), e.getY());
if(c == null) {
layeredPane.remove(chessPiece);
lastParent.add(chessPiece);
Rectangle r = lastParent.getBounds();
chessPiece.setLocation(r.x+xAdjustment, r.y+yAdjustment);
lastParent.validate();
lastParent.repaint();
return;
int x = (int)c.getBounds().getX();
int y = (int)c.getBounds().getY();
System.out.println(c.getLocation());
System.out.println(x + " "+ y);
c.setBackground(currentColor);
if (chessPiece == null) return;
chessPiece.setVisible(false);
if (c instanceof JLabel)
Container parent = c.getParent();
//remove the piece that is capture
parent.remove(0);
parent.add( chessPiece );
else
Container parent = (Container)c;
parent.add( chessPiece );
chessPiece.setVisible(true);
public void mouseClicked(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
private static void createAndShowGUI()
//Make sure we have nice window decorations
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new ChessBoardRx();
frame.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
//Display the window
frame.pack();
frame.setResizable( false );
frame.setLocationRelativeTo( null );
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();
}
Maybe you are looking for
-
Mid-2013 Macbook Air: question about the battery life
First of all, I'm sorry if these questions have been already asked, I've looked around and I've seen some answers, but none that fit my specific case. I have had this computer since December (Macbook Air, 13'', Mid-2013), I've been using it for a mon
-
How do I save an image in Photoshop
Format menu is not in my program!!!!!!
-
CALL_FUNCTION_RECIEVE_ ERROR ISSUE
Dear All, In Transaction code st22 i m getting dump error from past 2 days..CALL_FUNCTION_RECIEVE_ERROR.. user name :-ddic client:000 Details are:- Error when receiving answer to a Remote Function Call. What happened? Error in the SAP kernel. The cur
-
My phone out speaker is stopped, ring tones stopped , how can I solve that?
-
Oracle newbie : where to start?
Hi all Im based in East London, UK. My background is Medical I.T I have been working in 1st\2nd line technical support for abt 2 yrs and would like to move into a unsaturated part of I.T like oracle databases. The cost of Oracle courses are so expens