How to implement Comparable with objects?

J

juliekcf

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.java
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.java
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 = new JPanel(new BorderLayout(5,5));
playerHandPanels = new JPanel(new GridLayout(1,0,10,10));
playerPanels.add(playerHandPanels, BorderLayout.CENTER);
playerPanels.add(new JLabel("Player "+(i+1)),
BorderLayout.NORTH);
mainPlayPanel.add(playerPanels);
}
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[j].setTile(dealTilest.toString());
status.setText("Tile #: " +
myPack.getCurrentTileNumber());
}
else {
displayTiles[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[j] = new DisplayTile1();
playerHandPanels.add(displayTiles[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);
}
}
);
}
}
 
V

VisionSet

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?
 
J

John C. Bollinger

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
(e-mail address removed)
 
J

juliekcf

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
 
J

juliekcf

VisionSet said:
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);

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top