The BoxLayout respects the components' requested maximum sizes and also lets you align components.
For many cases flexible Layout:
- GridBagLayout
- SpringLayout
- BoxLayout
The BoxLayout respects the components' requested maximum sizes and also lets you align components.
For many cases flexible Layout:
JPanelTest.java
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class JPanelTest extends JPanel {
private static final long serialVersionUID = 1L;
/**
* Create the panel.
*/
public JPanelTest(int x, int y, int width, int height) {
setBorder(new LineBorder(Color.BLACK));
setBounds(x, y, width, height);
JLabel lbl = new JLabel("Test");
add(lbl);
addMouseListener(ma);
}
MouseAdapter ma = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX()+" "+e.getY()); // relatif to JPanel (0,0)
}
};
}
UISusah.java
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import javax.swing.border.LineBorder;
import java.awt.Color;
public class UISusah extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UISusah frame = new UISusah();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private int width = 530 ; // 85+350+85 = 520 -> 530
private int height = 495 ; // 85+290+85 = 460 -> 495
/**
* Create the frame.
*/
public UISusah() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(width, height);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
/*
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
flowLayout.setVgap(0);
flowLayout.setHgap(0);
panel.setBounds(0, 0, 85, 85);
contentPane.add(panel);
*/
// 1
JPanelTest panel = new JPanelTest(0, 0, 85, 85);
contentPane.add(panel);
// 2
JPanel panel1 = new JPanel();
panel1.setBorder(new LineBorder(Color.BLACK));
FlowLayout flowLayout_1 = (FlowLayout) panel1.getLayout();
flowLayout_1.setVgap(0);
flowLayout_1.setHgap(0);
panel1.setBounds(85-1, 0, 350, 85);
contentPane.add(panel1);
/*
JPanel panel2 = new JPanel();
panel2.setBorder(new LineBorder(Color.BLACK));
FlowLayout flowLayout_2 = (FlowLayout) panel2.getLayout();
flowLayout_2.setVgap(0);
flowLayout_2.setHgap(0);
panel2.setBounds(350+85-2, 0, 85, 85);
contentPane.add(panel2);
*/
// 3
JPanelTest panel2 = new JPanelTest(350+85-2, 0, 85, 85);
contentPane.add(panel2);
// 4
JPanel panel3 = new JPanel();
panel3.setBorder(new LineBorder(Color.BLACK));
FlowLayout flowLayout_3 = (FlowLayout) panel3.getLayout();
flowLayout_3.setVgap(0);
flowLayout_3.setHgap(0);
panel3.setBounds(0, 85-1, 85, 290);
contentPane.add(panel3);
// 5
JPanel panel4 = new JPanel();
panel4.setBorder(new LineBorder(Color.BLACK));
FlowLayout flowLayout_4 = (FlowLayout) panel4.getLayout();
flowLayout_4.setVgap(0);
flowLayout_4.setHgap(0);
panel4.setBounds(85-1, 85-1, 350, 290);
contentPane.add(panel4);
// 6
JPanel panel5 = new JPanel();
panel5.setBorder(new LineBorder(Color.BLACK));
FlowLayout flowLayout_5 = (FlowLayout) panel5.getLayout();
flowLayout_5.setVgap(0);
flowLayout_5.setHgap(0);
panel5.setBounds(350+85-2, 85-1, 85, 290);
contentPane.add(panel5);
// 7
JPanel panel6 = new JPanel();
panel6.setBorder(new LineBorder(Color.BLACK));
FlowLayout flowLayout_6 = (FlowLayout) panel6.getLayout();
flowLayout_6.setVgap(0);
flowLayout_6.setHgap(0);
panel6.setBounds(0, 290+85-2, 85, 85);
contentPane.add(panel6);
// 8
JPanel panel7 = new JPanel();
panel7.setBorder(new LineBorder(Color.BLACK));
FlowLayout flowLayout_7 = (FlowLayout) panel7.getLayout();
flowLayout_7.setVgap(0);
flowLayout_7.setHgap(0);
panel7.setBounds(85-1, 290+85-2, 350, 85);
contentPane.add(panel7);
// 9
JPanel panel8 = new JPanel();
panel8.setBorder(new LineBorder(Color.BLACK));
FlowLayout flowLayout_8 = (FlowLayout) panel8.getLayout();
flowLayout_8.setVgap(0);
flowLayout_8.setHgap(0);
panel8.setBounds(350+85-2, 290+85-2, 85, 85);
contentPane.add(panel8);
}
}
BidImage.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class BidImage extends JComponent {
private static final long serialVersionUID = 5119262068248858764L;
public String bidName=null;
public Dimension dimBidBox=new Dimension(40,20); // width 40 height 20
// PASS width 60 height 20
public int mPadding = 3;
int xP=0,yP=0; // position of screen
public int fontSize=18;
boolean isEnable = true;
String club = String.valueOf('\u2663'); // black 2663 white 2667
String diamond = String.valueOf('\u2666'); // black 2666 white 2662
String hearth = String.valueOf('\u2665'); // black 2665 white 2661
String spade = String.valueOf('\u2660'); // black 2660 white 2664
/*
* bidName
* dimBidBox dimension contains width and height
*/
public BidImage(String bidName) {
this.bidName = bidName;
if (bidName.equals("PASS") || bidName.equals("X") || bidName.equals("XX") ) {
dimBidBox = new Dimension(60,20);
}
}
public void setEnable(boolean isEnable) {
this.isEnable = isEnable;
}
public void setPosition(int x, int y) {
xP=x;
yP=y;
}
public boolean isSelected(int x, int y) {
return (x>=xP && x<=xP+dimBidBox.width
&& y>=yP && y<=yP+dimBidBox.height
&& isEnable);
}
public void drawMe(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
// draw rectangle first
if (isEnable) {
// fill color red
g2d.setColor(Color.GREEN);
g2d.fillRect(xP, yP, dimBidBox.width, dimBidBox.height);
g2d.setColor(Color.BLACK);
g2d.drawRect(xP, yP, dimBidBox.width, dimBidBox.height);
} else {
// fill color gray
g2d.setColor(Color.GRAY);
g2d.fillRect(xP, yP, dimBidBox.width, dimBidBox.height);
g2d.setColor(Color.BLACK);
g2d.drawRect(xP, yP, dimBidBox.width, dimBidBox.height);
}
// draw string
Font font = new Font("Courier", Font.PLAIN, fontSize);
g2d.setFont(font);
g2d.setColor(Color.BLACK);
if (!bidName.endsWith("T")
&& !bidName.equals("PASS")
&& !bidName.equals("X")
&& !bidName.equals("XX") ) {
char lastChar = bidName.charAt(1);
char firstChar = bidName.charAt(0);
String s2Show="";
switch (lastChar) {
case 'C':
s2Show = firstChar+club;
break;
case 'D':
s2Show = firstChar+diamond;
break;
case 'H':
s2Show = firstChar+hearth;
break;
case 'S':
s2Show = firstChar+spade;
break;
}
g2d.drawString(s2Show, xP+mPadding, yP+dimBidBox.height-mPadding);
} else {
g2d.drawString(bidName, xP+mPadding, yP+dimBidBox.height-mPadding);
}
}
}
CardImage.java
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
public class CardImage extends JComponent {
private static final long serialVersionUID = -8665119518202165791L;
BufferedImage bImg;
String cardName;
int strokeImg=1; // card separator
int widthImg=100, heightImg=150; // card dimension
public CardImage(String cardName) {
this.cardName = cardName;
// Load image and add stroke as separator
bImg = new BufferedImage(widthImg,
heightImg, BufferedImage.TYPE_INT_BGR);
Graphics2D g2d = bImg.createGraphics();
g2d.setStroke(new BasicStroke(1)); // 1 pixel
// https://stackoverflow.com/questions/31152233/opening-image-asset-java-jdk-8
String sFName = "/images/"+cardName+".png";
//System.out.println(sFName); // debug
BufferedImage img;
try {
img = ImageIO.read(getClass().getResource(sFName));
g2d.drawImage(img, strokeImg, strokeImg, widthImg-(2*strokeImg),
heightImg-(2*strokeImg), null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int x0=0, x1=0, y0=0, y1=0;
private void setClickArea(int x, int y) {
x0=x;
y0=y;
x1=x0+widthImg;
y1=y0+heightImg;
//System.out.println(x0+","+y0+" "+x1+","+y1); // debug
}
public boolean isSelected(int x, int y) {
return x>=x0 && x<=x1 && y>=y0 && y<=y1;
}
/*
* x position horizontal relatif to panel
* y position vertical to panel
*/
public void drawMe(Graphics g, int x, int y, ImageObserver o) {
setClickArea(x,y);
//System.out.println(x0+","+y0+","+x1+","+y1);
g.drawImage(bImg, x, y, o);
}
/*
* 90 degree only, keep on position top left
*/
public void drawMe90(Graphics g, int x, int y, ImageObserver o) {
double rotationAngle=90*Math.PI/180;
AffineTransform transform = new AffineTransform();
transform.rotate(rotationAngle, x, y);
// yCenter-heightImg = horizontal position
// xCenter: vertical position
transform.translate(x, y-heightImg);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(bImg, transform, o);
}
}
JPanelCenter.java
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JPanelCenter extends JPanel {
private static final long serialVersionUID = 1L;
BidImage bI;
public final static String[] S_BIDS = {
"1C", // 0
"1D", // 1
"1H", // 2
"1S", // 3
"1NT", // 4
"2C", // 5
"2D", // 6
"2H", // 7
"2S", // 8
"2NT", // 9
"3C", // 10
"3D", // 11
"3H", // 12
"3S", // 13
"3NT", // 14
"4C", // 15
"4D", // 16
"4H", // 17
"4S", // 18
"4NT", // 19
"5C", // 20
"5D", // 21
"5H", // 22
"5S", // 23
"5NT", // 24
"6C", // 25
"6D", // 26
"6H", // 27
"6S", // 28
"6NT", // 29
"7C", // 30
"7D", // 31
"7H", // 32
"7S", // 33
"7NT" // 34
};
ArrayList<BidImage> bids = new ArrayList<>();
/**
* Create the panel.
*/
public JPanelCenter() {
setPreferredSize(new Dimension(350,290));
JLabel lblNewLabel = new JLabel("Center");
add(lblNewLabel);
bI = new BidImage("7NT");
//bI = new BidImage("1S");
int x=30;
int y=30;
for (int i=0;i<7;i++) {
for (int j=0;j<5;j++) {
int pos=i*5+j;
BidImage tmp = new BidImage(S_BIDS[pos]);
tmp.setPosition(x+(i*tmp.dimBidBox.width), y+(j*tmp.dimBidBox.height));
//tmp.setEnable(false);
bids.add(tmp);
}
}
BidImage pass = new BidImage("PASS");
pass.setPosition(100, 140);
bids.add(pass);
pass = new BidImage("X");
pass.setPosition(100+pass.dimBidBox.width, 140);
bids.add(pass);
pass = new BidImage("XX");
pass.setPosition(100+(2*pass.dimBidBox.width), 140);
bids.add(pass);
addMouseListener(mListener);
}
@Override
protected void paintComponent(Graphics g) {
//bI.setPosition(30, 30);
//bI.drawMe(g);
for (int i=0;i<bids.size();i++) {
BidImage tmp = bids.get(i);
tmp.drawMe(g);
}
}
/*
* position x,y relatif to JPanel
*/
MouseAdapter mListener = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX()+" "+e.getY());
for (int i=0;i<bids.size();i++) {
BidImage cI = bids.get(i);
if (cI.isSelected(e.getX(), e.getY())) {
System.out.println(cI.bidName);
break;
}
}
}
};
}
JPanelEast.java
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JLabel;
public class JPanelEast extends JPanel {
private static final long serialVersionUID = 1L;
int panelWidth=85, panelHeight=290;
ArrayList<CardImage> cards = new ArrayList<>();
/**
* Create the panel.
*/
public JPanelEast() {
setPreferredSize(new Dimension(panelWidth,panelHeight));
JLabel lblNewLabel = new JLabel("East");
add(lblNewLabel);
initCards();
}
private void initCards() {
for (int i=0;i<13;i++) {
CardImage cI = new CardImage("RED");
cards.add(cI);
}
}
@Override
protected void paintComponent(Graphics g) {
int x = 0;
int y = 0;
for (int i=0;i<13;i++) {
CardImage cI=cards.get(i);
cI.drawMe90(g, x, y+(i*10), this);
}
}
}
JPanelNorth.java
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JLabel;
public class JPanelNorth extends JPanel {
private static final long serialVersionUID = 1L;
int panelWidth=520, panelHeight=85;
ArrayList<CardImage> cards;
/**
* Create the panel.
*/
public JPanelNorth() {
setPreferredSize(new Dimension(panelWidth,panelHeight));
JLabel lblNewLabel = new JLabel("North");
add(lblNewLabel);
addMouseListener(mListener);
initCards();
}
private void initCards() {
String[] S_CLUB = {
"2C",
"3C",
"4C",
"5C",
"6C",
"7C",
"8C",
"9C",
"10C",
"JC",
"QC",
"KC",
"AC"
};
cards= new ArrayList<>();
for (int i=0;i<S_CLUB.length;i++) {
CardImage cI = new CardImage(S_CLUB[i]);
cards.add(cI);
}
}
@Override
protected void paintComponent(Graphics g) {
/*
int x=0,y=-70;
for (int i=0;i<cards.size();i++) {
CardImage cI=cards.get(i);
cI.drawMe(g, x+((i-1)*15), y, this);
}
*/
int x=300,y=-70;
for (int i=0;i<cards.size();i++) {
CardImage cI=cards.get(i);
cI.drawMe(g, x-((i-1)*15), y, this); // 15 gap between cards
}
}
/*
* position x,y relatif to JPanel
*/
MouseAdapter mListener = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX()+" "+e.getY());
// reverse from last draw
for (int i=cards.size()-1;i>=0;i--) {
CardImage cI = cards.get(i);
if (cI.isSelected(e.getX(), e.getY())) {
System.out.println(cI.cardName);
break;
}
}
}
};
}
JPanelSouth.java
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JLabel;
public class JPanelSouth extends JPanel {
private static final long serialVersionUID = 1L;
int panelWidth=520, panelHeight=85;
ArrayList<CardImage> cards;
/**
* Create the panel.
*/
public JPanelSouth() {
setPreferredSize(new Dimension(panelWidth,panelHeight));
JLabel lblNewLabel = new JLabel("South");
add(lblNewLabel);
addMouseListener(mListener);
initCards();
}
private void initCards() {
String[] S_DIAMOND = {
"2D",
"3D",
"4D",
"5D",
"6D",
"7D",
"8D",
"9D",
"10D",
"JD",
"QD",
"KD",
"AD"
};
cards= new ArrayList<>();
for (int i=0;i<S_DIAMOND.length;i++) {
CardImage cI = new CardImage(S_DIAMOND[i]);
cards.add(cI);
}
}
@Override
protected void paintComponent(Graphics g) {
/*
int x=0,y=-70;
for (int i=0;i<cards.size();i++) {
CardImage cI=cards.get(i);
cI.drawMe(g, x+((i-1)*15), y, this);
}
*/
int x=100,y=5;
for (int i=0;i<cards.size();i++) {
CardImage cI=cards.get(i);
cI.drawMe(g, x+((i-1)*15), y, this);
}
/*
* test ok
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLACK);
g2d.drawRect(100, 50, 30, 30);
g2d.drawString("TEST", 100, 50);
*/
}
/*
* position x,y relatif to JPanel
*/
MouseAdapter mListener = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX()+" "+e.getY());
// reverse from last draw
for (int i=cards.size()-1;i>=0;i--) {
CardImage cI = cards.get(i);
if (cI.isSelected(e.getX(), e.getY())) {
System.out.println(cI.cardName);
break;
}
}
}
};
}
JPanelWest.java
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JLabel;
public class JPanelWest extends JPanel {
private static final long serialVersionUID = 1L;
int panelWidth=85, panelHeight=290;
ArrayList<CardImage> cards = new ArrayList<>();
/**
* Create the panel.
*/
public JPanelWest() {
setPreferredSize(new Dimension(panelWidth,panelHeight));
JLabel lblNewLabel = new JLabel("West");
add(lblNewLabel);
initCards();
}
private void initCards() {
for (int i=0;i<13;i++) {
CardImage cI = new CardImage("BLUE");
cards.add(cI);
}
}
@Override
protected void paintComponent(Graphics g) {
int x = -70;
int y = 0;
for (int i=0;i<13;i++) {
CardImage cI=cards.get(i);
cI.drawMe90(g, x, y+(i*10), this);
}
}
}
BridgeUI.java
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
public class BridgeUI extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private int width = 520 ; // 85+350+85
private int height = 460 ; // 85+290+85
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BridgeUI frame = new BridgeUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public BridgeUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(width, height);
setResizable(false);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
JPanelWest pWest = new JPanelWest();
contentPane.add(pWest,BorderLayout.WEST);
JPanelNorth pNorth = new JPanelNorth();
contentPane.add(pNorth,BorderLayout.NORTH);
JPanelEast pEast = new JPanelEast();
contentPane.add(pEast,BorderLayout.EAST);
JPanelCenter pCenter = new JPanelCenter();
contentPane.add(pCenter,BorderLayout.CENTER);
JPanelSouth pSouth = new JPanelSouth();
contentPane.add(pSouth,BorderLayout.SOUTH);
setContentPane(contentPane);
}
}
Note:
import java.awt.BasicStroke;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class JFrameRotate extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFrameRotate frame = new JFrameRotate();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
int panelWidth=600, panelHeight=600;
/**
* Create the frame.
*/
public JFrameRotate() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0, 0, panelWidth, panelHeight);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
loadCard();
}
// JFrame: public void paint(Graphics g)
// JPanel: protected void paintComponent(Graphics g)
@Override
public void paint(Graphics g) {
if (bImg!=null) {
//g.drawImage(bImg, xCenter, yCenter, this);
// draw the image
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(bImg, rotate(10), contentPane);
g2d.drawImage(bImg, rotate(45), contentPane);
g2d.drawImage(bImg, rotate(90), contentPane);
g2d.drawImage(bImg, rotate90(), contentPane);
}
}
int strokeImg =1, widthImg=100, heightImg=150;
int xCenter=200, yCenter=300;
BufferedImage bImg;
private void loadCard() {
bImg = new BufferedImage(widthImg,
heightImg, BufferedImage.TYPE_INT_BGR);
Graphics2D g2d = bImg.createGraphics();
g2d.setStroke(new BasicStroke(1)); // 1 pixel
// https://stackoverflow.com/questions/31152233/opening-image-asset-java-jdk-8
String sFName = "/images/KC.png"; // See here to setup image resources
BufferedImage img;
try {
img = ImageIO.read(getClass().getResource(sFName));
g2d.drawImage(img, strokeImg, strokeImg, widthImg-(2*strokeImg),
heightImg-(2*strokeImg), this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private AffineTransform rotate(int degree) {
double rotationAngle=degree*Math.PI/180;
AffineTransform transform = new AffineTransform();
transform.rotate(rotationAngle, xCenter, yCenter);
//transform.rotate(rotationAngle);
transform.translate(xCenter, yCenter);
return transform;
}
/*
* 90 degree only, keep on position top left
*/
private AffineTransform rotate90() {
double rotationAngle=90*Math.PI/180;
AffineTransform transform = new AffineTransform();
transform.rotate(rotationAngle, xCenter, yCenter);
// yCenter-heightImg = horizontal position
// xCenter: vertical position
transform.translate(xCenter, yCenter-heightImg);
return transform;
}
}
Create resources folder
Accessing images from the "images" folder, use this piece of code into your java source code:
String cName = "example.jpg";
String sFName = "/images/"+cName;
BufferedImage img = ImageIO.read(this.getClass().getResource(sFName));
References:
https://stackoverflow.com/questions/31152233/opening-image-asset-java-jdk-8
This code will sort string array and return a new arraylist with order word (ascending), but ordered done from end of each word. This code work like sorting file name in file manager.
Source code:
public class WordC {
// sort from end to begin
public static void main(String[] args) {
String[] sTest = {"4H", "5H", "8C", "8D", "9H", "9D", "AC", "6S", "5D", "6D", "KD", "10C", "AD" };
for (int i=0;i<13;i++) {
System.out.print(sTest[i]+" ");
}
System.out.println();
System.out.println("Sorting");
ArrayList<String> tmp = sortEnd2Begin(sTest);
tmp.forEach((String myCard) ->{
System.out.print(myCard+" ");
});
System.out.println();
}
private static ArrayList<String> sortEnd2Begin(String[] myCards) {
ArrayList<String> myNewCards = new ArrayList<>();
myNewCards.add(myCards[0]);
for (int i=1;i<myCards.length;i++) {
// loop for unordered myCards
String card2Sort = myCards[i];
for (int j=0;j<myNewCards.size();j++) {
// loop for ordered myNewCards
// find until card2Sort equal or bigger then existing list
String cardIterate = myNewCards.get(j);
int iterMax = card2Sort.length();
if (card2Sort.length() > cardIterate.length()) {
iterMax = cardIterate.length();
}
int posCard = beforeOrAfter(card2Sort, cardIterate, 0, iterMax);
if (posCard==0 || posCard<0) {
myNewCards.add(j, card2Sort);
break;
} else {
// TODO
//System.out.println(j); // debug
if (j+1==myNewCards.size()) {
// end of list
myNewCards.add(card2Sort);
break;
}
}
}
}
return myNewCards;
}
// -1 wordA before wordB
// 0 wordA equal wordB
// 1 wordA after wordB
private static int beforeOrAfter(String wordA, String wordB, int iterX, int iterMax) {
//System.out.println(wordA+" "+wordB+" "+iterX+" "+iterMax);
int inA = wordA.length()-1-iterX;
int inB = wordB.length()-1-iterX;
char cA = wordA.charAt(inA);
char cB = wordB.charAt(inB);
int retValue = 0;
if (iterX+1==iterMax) {
// we reach max recursive {
//System.out.println(iterX+" "+iterMax+" "+cA+" "+cB); // debug
if (cA==cB) {
//System.out.println("Debug"); // debug
if (wordA.length()<wordB.length()) {
retValue = -1;
} else if (wordA.length()>wordB.length()) {
retValue = 1;
} else {
retValue = 0; // equal letters and length
}
} else if (cA<cB) {
//retValue = -1; // ori
} else if (cA>cB) {
retValue = 1; // ori
}
} else {
if (cA<cB) {
//System.out.println(cA+" < "+cB+" "+(cA < cB)); // debug
retValue = -1; // ori
} else if (cA>cB) {
//System.out.println(cA+" > "+cB+" "+(cA > cB)); // debug
retValue = 1; // ori
} else {
//System.out.println(cA+" = "+cB+" "+(cA == cB)); // debug
retValue = beforeOrAfter(wordA, wordB, iterX+1, iterMax);
}
}
return retValue;
}
}
NOTE for socket:
Swing JFrame to start server and client
package com.dedetok;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;
import javax.swing.JButton;
public class Test extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
MyServerThread myServerThread;
ExecutorService executor;
MyClient myClient=null;
/**
* Create the frame.
*/
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
JButton btnStartServer = new JButton("Start Server");
contentPane.add(btnStartServer);
btnStartServer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
//System.out.println("Test"); // debug
// TODO Auto-generated method stub
if (executor==null) {
executor = Executors.newSingleThreadExecutor();
try {
if (myServerThread==null) {
System.out.println("Server null, create new"); // debug
myServerThread = new MyServerThread();
executor.submit(myServerThread);
}
//System.out.println("create thread"); // debug
//System.out.println("run thread"); // debug
if (executor.isTerminated()) {
System.out.println("is terminated"); // debug
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
JButton btnStartClient = new JButton("Start Client");
contentPane.add(btnStartClient);
btnStartClient.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try {
/*
if (myClient== null) {
myClient = new MyClient();
}
myClient.sendCommand();
*/
myClient = new MyClient();
myClient.sendCommand();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
}
Server part
package com.dedetok;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServerThread implements Runnable {
ServerSocket myServerSocket;
//InetAddress myServerInetAddress;
int myServerPort = 54321;
public MyServerThread() throws IOException {
myServerSocket = new ServerSocket(myServerPort);
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
Socket myClientSocket;
try {
myClientSocket = myServerSocket.accept();
/*
InetAddress inetAddress = myClientSocket.getInetAddress();
System.out.println("receive from client: "+inetAddress.toString()); // debug
InputStream myInputStream = myClientSocket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(myInputStream);
String sClient;
sClient = (String) ois.readObject();
System.out.println("From Client: "+sClient); // debug
sClient = "Echo: "+sClient;
OutputStream myOutputStream = myClientSocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(myOutputStream);
oos.writeObject(sClient);
oos.flush();
//ois.close();
//oos.close();
myClientSocket.close();
*/
ClientHandler clientHandler = new ClientHandler(myClientSocket);
clientHandler.run();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandler implements Runnable {
Socket socket;
ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
// TODO Auto-generated method stub
InetAddress inetAddress = socket.getInetAddress();
System.out.println("receive from client: "+inetAddress.toString()); // debug
InputStream myInputStream;
try {
myInputStream = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(myInputStream);
OutputStream myOutputStream = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(myOutputStream);
boolean loopMsg = true;
while (loopMsg) {
String sClient = (String) ois.readObject();
if (sClient.equals("END")) {
loopMsg = false;
}
System.out.println("From Client: "+sClient); // debug
sClient = "Echo: "+sClient;
oos.writeObject(sClient);
oos.flush();
}
//ois.close();
//oos.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Client part
package com.dedetok;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyClient {
ExecutorService executor;
boolean isRun = false;
public MyClient() throws IOException {
executor = Executors.newSingleThreadExecutor();
}
public void sendCommand() {
if (!isRun) {
executor.submit(myRun);
isRun = true;
}
}
int i=0;
String str = "Hello ";
Runnable myRun = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//System.out.println("Running thread client"); // debug
try {
/*
System.out.println("create socket"); // debug
Socket mySocket = new Socket("127.0.0.1", 54321);
OutputStream myOutputStream = mySocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(myOutputStream);
System.out.println("send "+i); // debug
oos.writeObject("END");
oos.writeObject(str+1);
oos.flush();
InputStream myInputStream = mySocket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(myInputStream);
System.out.println("receive "+i); // debug
String rStr = (String) ois.readObject();
System.out.println(rStr); // debug
System.out.println("end client"); // debug
//mySocket.close();
//ois.close();
//oos.close();
mySocket.close();
i++;
*/
System.out.println("create socket"); // debug
Socket mySocket = new Socket("127.0.0.1", 54321);
OutputStream myOutputStream = mySocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(myOutputStream);
InputStream myInputStream = mySocket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(myInputStream);
while (i<10) {
String str = "send "+i;
System.out.println(str); // debug
if (i==9)
str="END";
oos.writeObject(str);
oos.flush();
System.out.println("receive "+i); // debug
String rStr = (String) ois.readObject();
System.out.println(rStr); // debug
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//mySocket.close();
//ois.close();
//oos.close();
i++;
}
mySocket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
isRun = false;
}
};
}