Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > How to implement Comparable with objects?

Reply
Thread Tools

How to implement Comparable with objects?

 
 
juliekcf@yahoo.com.hk
Guest
Posts: n/a
 
      10-27-2003
I am new to Java. Can anyone give me some help, please?

There are 2 classes: DisplayTile1 and TilingDemo1
How can I implement Comparable in DisplayTile1 so that I can sort
tiles by colour and then by number?
What should be done in TilingDemo1 accordingly?

Julie


import javax.swing.*;
import java.awt.*;

//**********************************DisplayTile1.jav a
public class DisplayTile1 extends JPanel{
private JTextArea tile;

public DisplayTile1() {
super(new FlowLayout());
tile = new JTextArea(3,5);
tile.setFont(new Font("Arial", Font.BOLD, 10));
tile.setEditable(false);
this.add(tile);
}

public void setTile(String tileString){
setBackgroundColor(tileString);
setText(tileString);
}

public void setText(String tileString){
FontMetrics f = tile.getFontMetrics(tile.getFont());
String display = ( (tileString.indexOf("-") != -1) ?
tileString.substring(0,
tileString.indexOf("-")).trim():
tileString);
int leftover = (tile.getWidth() - f.stringWidth(display)) /
f.stringWidth(" ");
for (int k = 0; k < leftover / 2; k++)
display = " " + display;
tile.setText("\n" + display);
}

public void setBackgroundColor(String colourString){
if (colourString.endsWith("Red")) tile.setBackground(Color.RED);
else if (colourString.endsWith("Blue"))
tile.setBackground(Color.BLUE);
else if (colourString.endsWith("Yellow"))
tile.setBackground(Color.YELLOW);
else if (colourString.endsWith("Orange"))
tile.setBackground(Color.ORANGE);
else tile.setBackground(Color.WHITE);
}
}



//*************************************TilingDemo1.j ava
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TilingDemo1 extends JFrame{
public final static int PLAYERS = 2;
public final static int TOTAL_TILES = 13;

private JButton dealTilesButton, mixUpTilesButton;
private DisplayTile1 displayTiles[][];
private JLabel status;
private TilePack myPack;
private JPanel buttonPanel;
private JPanel playerPanels[];
private JPanel playerHandPanels[];
private JPanel mainPlayPanel;
private JPanel statusPanel;

public TilingDemo1(){
super("Tiles");
myPack = new TilePack();
myPack.mixUpTiles();
buttonPanel = new JPanel(new FlowLayout());
mainPlayPanel = new JPanel(new GridLayout(PLAYERS,1,10,50));
playerPanels = new JPanel[PLAYERS];
playerHandPanels = new JPanel[PLAYERS];
for (int i = 0; i < PLAYERS; i++) {
playerPanels[i] = new JPanel(new BorderLayout(5,5));
playerHandPanels[i] = new JPanel(new GridLayout(1,0,10,10));
playerPanels[i].add(playerHandPanels[i], BorderLayout.CENTER);
playerPanels[i].add(new JLabel("Player "+(i+1)),
BorderLayout.NORTH);
mainPlayPanel.add(playerPanels[i]);
}
statusPanel = new JPanel(new FlowLayout());
Container c = getContentPane();
c.setLayout(new BorderLayout());
dealTilesButton = new JButton("Deal Tiles");
dealTilesButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < PLAYERS; i++) {
for (int j = 0; j < TOTAL_TILES; j++) {
Tile dealTilest = myPack.getNextTile();
if (dealTilest != null) {
displayTiles[i][j].setTile(dealTilest.toString());
status.setText("Tile #: " +
myPack.getCurrentTileNumber());
}
else {
displayTiles[i][j].setTile("");
status.setText("Press Mix Tiles Button to continue...");
dealTilesButton.setEnabled(false);
}
}
}
}
}
);
buttonPanel.add(dealTilesButton);

mixUpTilesButton = new JButton("Mix Tiles");
mixUpTilesButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
status.setText("MIXING.....");
myPack.mixUpTiles();
status.setText("MIXED");
dealTilesButton.setEnabled(true);
}
}
);
buttonPanel.add(mixUpTilesButton);

displayTiles = new DisplayTile1[PLAYERS][TOTAL_TILES];
for (int i = 0; i < PLAYERS; i++){
for (int j = 0; j < TOTAL_TILES; j++) {
displayTiles[i][j] = new DisplayTile1();
playerHandPanels[i].add(displayTiles[i][j]);
}
}
status = new JLabel("Hit a button to begin");
statusPanel.add(status);

c.add(buttonPanel, BorderLayout.NORTH);
c.add(mainPlayPanel, BorderLayout.CENTER);
c.add(statusPanel, BorderLayout.SOUTH);

pack();
show(); // show the window

}

public static void main(String[] args) {
TilingDemo1 td1 = new TilingDemo1();

td1.addWindowListener(
new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
);
}
}
 
Reply With Quote
 
 
 
 
VisionSet
Guest
Posts: n/a
 
      10-27-2003
<> wrote in message
news: m...
> I am new to Java. Can anyone give me some help, please?
>
> There are 2 classes: DisplayTile1 and TilingDemo1
> How can I implement Comparable in DisplayTile1 so that I can sort
> tiles by colour and then by number?
> What should be done in TilingDemo1 accordingly?



Make DisplayTile1 implement Comparable and implement its one method
something like this.

Very pseudo code!

public int compareTo(Object obj) {

DisplayTile1 that = (DisplayTile1)obj;
this.getBackground();
that.getBackground(); // compare them with eaxh other by scalar
attribute (eg getRed())

if(this < that) return -1;
if(this > that) return +1;

assert this = that; // since they must

// must be equal so can sort on number

do a similar thing with the number (whatever that is!)

}

To sort your arrays use java.util.Arrays.sort(Object[] objs)

You must be clear on what you expect the sorted order to be.
When you say sort by colour what do you mean? alphabetically, by the red
component, by the alpha?

--
Mike W


 
Reply With Quote
 
 
 
 
Roedy Green
Guest
Posts: n/a
 
      10-27-2003
On 27 Oct 2003 08:14:16 -0800,
() wrote or quoted :

>There are 2 classes: DisplayTile1 and TilingDemo1
>How can I implement Comparable in DisplayTile1 so that I can sort
>tiles by colour and then by number?

http://mindprod.com/jgloss/comparable.html

--
Canadian Mind Products, Roedy Green.
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.
 
Reply With Quote
 
John C. Bollinger
Guest
Posts: n/a
 
      10-27-2003
wrote:

> I am new to Java. Can anyone give me some help, please?
>
> There are 2 classes: DisplayTile1 and TilingDemo1
> How can I implement Comparable in DisplayTile1 so that I can sort
> tiles by colour and then by number?


To implement an interface you add an implements clause to the class
declaration and write appropriate implementation methods. In this case
that would mean adding "implements Comparable" after "extends JPanel" in
the declaration of DisplayTile1, and then writing a compareTo(Object)
method, returning int, that implements the sort order you want. Read
the API docs for Comparable for the details of the method contract.

> What should be done in TilingDemo1 accordingly?


I couldn't say, exactly, because it's not clear which group of tiles you
want to sort. You can sort an array of mutually Comparable objects by
use of the sort(Object[]) method of class java.util.Arrays; perhaps
that's what you need.

[code snipped]


John Bollinger


 
Reply With Quote
 
juliekcf@yahoo.com.hk
Guest
Posts: n/a
 
      10-28-2003
>
> Make DisplayTile1 implement Comparable and implement its one method
> something like this.
>
> Very pseudo code!
>
> public int compareTo(Object obj) {
>
> DisplayTile1 that = (DisplayTile1)obj;
> this.getBackground();
> that.getBackground(); // compare them with eaxh other by scalar
> attribute (eg getRed())
>
> if(this < that) return -1;
> if(this > that) return +1;
>
> assert this = that; // since they must
>
> // must be equal so can sort on number
>
> do a similar thing with the number (whatever that is!)
>
> }
>
> To sort your arrays use java.util.Arrays.sort(Object[] objs)
>
> You must be clear on what you expect the sorted order to be.
> When you say sort by colour what do you mean? alphabetically, by the red
> component, by the alpha?


Thanks for your help!

I need to group the colours and then sort the numbers inside each
group of colour. I think the order of the colour is not important.

Julie
 
Reply With Quote
 
juliekcf@yahoo.com.hk
Guest
Posts: n/a
 
      10-29-2003
"VisionSet" <> wrote in message news:<G6cnb.2405$>...
> <> wrote in message
> news: m...
> > I am new to Java. Can anyone give me some help, please?
> >
> > There are 2 classes: DisplayTile1 and TilingDemo1
> > How can I implement Comparable in DisplayTile1 so that I can sort
> > tiles by colour and then by number?
> > What should be done in TilingDemo1 accordingly?

>
>
> Make DisplayTile1 implement Comparable and implement its one method
> something like this.
>
> Very pseudo code!
>
> public int compareTo(Object obj) {
>
> DisplayTile1 that = (DisplayTile1)obj;
> this.getBackground();
> that.getBackground(); // compare them with eaxh other by scalar
> attribute (eg getRed())
>
> if(this < that) return -1;
> if(this > that) return +1;
>
> assert this = that; // since they must
>
> // must be equal so can sort on number
>
> do a similar thing with the number (whatever that is!)
>
> }
>


I tried to implement Comparable like this in DisplayTile1.java:

import javax.swing.*;
import java.awt.*;

public class DisplayTile1 extends JPanel implements Comparable {
private JTextArea tile;
private String tileColor;
private String tileNum;

public DisplayTile1() {
super(new FlowLayout());
tile = new JTextArea(3,5);
tile.setFont(new Font("Arial", Font.BOLD, 10));
tile.setEditable(false);
this.add(tile);
}

public void setTile(String tileString){
setBackgroundColor(tileString);
setText(tileString);
}

public void setText(String tileString){
FontMetrics f = tile.getFontMetrics(tile.getFont());
String display = ( (tileString.indexOf("-") != -1) ?
tileString.substring(0,
tileString.indexOf("-")).trim():
tileString);
int leftover = (tile.getWidth() - f.stringWidth(display)) /
f.stringWidth(" ");
for (int k = 0; k < leftover / 2; k++)
display = " " + display;
tile.setText("\n" + display);
}

public void setBackgroundColor(String colourString){
if (colourString.endsWith("Red")) {
tile.setBackground(Color.RED);
tileColor="Red";
}
else if (colourString.endsWith("Blue")) {
tile.setBackground(Color.BLUE);
tileColor="Blue";
}
else if (colourString.endsWith("Yellow")) {
tile.setBackground(Color.YELLOW);
tileColor="Yellow";
}
else if (colourString.endsWith("Orange")) {
tile.setBackground(Color.ORANGE);
tileColor="Orange";
}
else {
tile.setBackground(Color.WHITE);
tileColor="White";
}
}

public int compareTo(Object handTiles) {
DisplayTile1 hTiles = (DisplayTile1) handTiles;
String hTilesColor = hTiles.getBackground().toString();

int diff=0;
int comp=0;

diff = this.tileColor.compareTo(hTilesColor);
if (diff==0)
comp = 0;
else if (diff<0)
comp = -1;
else if (diff>0)
comp = 1;

return comp;
}

}


.... and I added the following lines in TilingDemo1.java:


// add a button for player 2 to sort his hand of tiles
sortTilesButton = new JButton("Sort Tiles");
sortTilesButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
status.setText("SORTING.....");
Arrays.sort(displayTiles[1]);
status.setText("SORTED");
}
}
);
buttonPanel.add(sortTilesButton);


>>>>>>>>>> However, nothing happens on the screen when the "sort

tiles" button is pressed. What is wrong with my code? Should the
screen refresh automatically when the Arrays.sort(displayTiles[1]) is
called?

Please help me. I am really very puzzled.

Thanks.

Julie
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
difference between comparator and comparable interface gaurav Java 4 04-14-2009 12:18 PM
Discussion of why java.lang.Number does not implement Comparable Sideswipe Java 42 08-02-2007 02:24 AM
Design Question re Comparable Rhino Java 3 02-23-2005 06:10 PM
Generics and Comparable Bergholt Java 3 11-30-2004 03:31 AM
implementing comparable steve Java 2 11-18-2004 10:03 PM



Advertisments