Im working on a program, pretty simple. You simple enter a person's name into the field provided. click search and it searches a database and retrieves information. Including the picture. this works fine but i have one problem. If i do a search using peter and there are two 'peters' in the database. When i scroll. the picture does not change unless i click the picture field. I believe i posted the relavant code. Any help will be appreciated. Thank you
public class DriverSearchResultScreen extends MainScreen implements FieldChangeListener{
LabelField header,title;
LabelField lblLicenseNumber,lblFirstName,lblLastName,lblBirthDate,lblLicenseExpiry,lblLicenseType,lblLicenseStatus;
ColoredMultiLineLabelField clblLicenseNumber,clblFirstName,clblLastName,clblBirthDate,clblLicenseExpiry,clblLicenseType,clblLicenseStatus;
CustomButtonField btnSearch;
CustomImageButton btnLeft,btnRight;
CustomImageButton bmpfDriverPhoto;
Vector licenseInfoData;
int currentIndex = 0;
public DriverSearchResultScreen(Vector licenseInfoData ) {
this.licenseInfoData = licenseInfoData;
// TODO Auto-generated constructor stub
title = new LabelField("License",LabelField.USE_ALL_WIDTH);
/*header.setBackground(bg);*/
setTitle(title);
bmpfDriverPhoto = new CustomImageButton(Bitmap.getBitmapResource("default-profile.png")){
public boolean isFocusable() { return true; };
};
bmpfDriverPhoto.setChangeListener(this);
add(bmpfDriverPhoto);
header = new LabelField("",LabelField.FIELD_HCENTER|LabelField.USE_ALL_WIDTH){
public void paint(Graphics g){
int col = g.getColor();
g.setColor(Color.YELLOW);
super.paint(g);
g.setColor(col);
}
public int getPreferredWidth(){
return net.rim.device.api.system.Display.getWidth();
}
};
this.getMainManager().setBackground(BackgroundFactory.createBitmapBackground(Bitmap.getBitmapResource("background.png")));
header.setFont(Font.getDefault().derive(Font.SANS_SERIF_STYLE|Font.BOLD,25));
add(header);
add(new SeparatorField());
Bitmap vfmBackground = Bitmap.getBitmapResource("rounded-border.png");
VerticalFieldManager vfm = new VerticalFieldManager();
vfm.setBorder(BorderFactory.createBitmapBorder(new XYEdges(12,12,12,12),vfmBackground));
BHorizontalFieldManager hfm = new BHorizontalFieldManager();
lblFirstName= new LabelField("First Name :");
hfm.add(lblFirstName);
clblFirstName = new ColoredMultiLineLabelField("Jhon",Color.GRAY);
hfm.add(clblFirstName);
vfm.add(hfm);
vfm.add(new SeparatorField());
BHorizontalFieldManager hfm1 = new BHorizontalFieldManager();
lblLastName= new LabelField("Last Name :");
hfm1.add(lblLastName);
clblLastName = new ColoredMultiLineLabelField("Doe",Color.GRAY);
hfm1.add(clblLastName);
vfm.add(hfm1);
vfm.add(new SeparatorField());
BHorizontalFieldManager hfm2 = new BHorizontalFieldManager();
lblBirthDate = new LabelField("Date Of Birth:");
hfm2.add(lblBirthDate);
clblBirthDate = new ColoredMultiLineLabelField("11-June-1982",Color.GRAY);
hfm2.add(clblBirthDate);
vfm.add(hfm2);
vfm.add(new SeparatorField());
BHorizontalFieldManager hfm3 = new BHorizontalFieldManager();
lblLicenseNumber = new LabelField("License Number :");
hfm3.add(lblLicenseNumber);
clblLicenseNumber = new ColoredMultiLineLabelField("999999",Color.GRAY);
hfm3.add(clblLicenseNumber);
vfm.add(hfm3);
vfm.add(new SeparatorField());
BHorizontalFieldManager hfm4 = new BHorizontalFieldManager();
lblLicenseType = new LabelField("License Type :");
hfm4.add(lblLicenseType);
clblLicenseType = new ColoredMultiLineLabelField("B",Color.GRAY);
hfm4.add(clblLicenseType);
vfm.add(hfm4);
vfm.add(new SeparatorField());
BHorizontalFieldManager hfm5 = new BHorizontalFieldManager();
lblLicenseExpiry = new LabelField("Expiry Date:");
hfm5.add(lblLicenseExpiry);
clblLicenseExpiry = new ColoredMultiLineLabelField("25-Aug-2012",Color.GRAY);
hfm5.add(clblLicenseExpiry);
vfm.add(hfm5);
vfm.add(new SeparatorField());
BHorizontalFieldManager hfm6 = new BHorizontalFieldManager();
lblLicenseStatus = new LabelField("Licenes Status:");
hfm6.add(lblLicenseStatus);
clblLicenseStatus = new ColoredMultiLineLabelField("Expired",Color.GRAY);
hfm6.add(clblLicenseStatus);
vfm.add(hfm6);
vfm.add(new SeparatorField());
add(vfm);
btnLeft = new CustomImageButton(Bitmap.getBitmapResource("left-arrow-enable.png"),Bitmap.getBitmapResource("left-arrow-disable.png"));
btnRight= new CustomImageButton(Bitmap.getBitmapResource("right-arrow-enable.png"),Bitmap.getBitmapResource("right-arrow-disable.png"));;
HorizontalFieldManager arrowButtonHfm = new HorizontalFieldManager(){
public int getPreferredHeight() {
// TODO Auto-generated method stub
return btnLeft.getPreferredHeight()*2;
}
public int getPreferredWidth() {
// TODO Auto-generated method stub
return Display.getWidth();
}
protected void sublayout(int maxWidth, int maxHeight) {
// TODO Auto-generated method stub
int count = getFieldCount();
for(int i = 0 ; i < count ; i++ ){
Field f = getField(i);
if(f == btnLeft ){
setPositionChild(f, (getPreferredWidth() >> 1) - f.getPreferredWidth() - 30, getPreferredHeight()>>1);
}else if (f == btnRight ){
setPositionChild(f, (getPreferredWidth() >> 1) + 30, getPreferredHeight()>>1);
}
layoutChild(f, getPreferredWidth(), getPreferredHeight());
}
setExtent(getPreferredWidth(),getPreferredHeight());
}
public void subpaint(Graphics graphics){
int count = getFieldCount();
for(int i = 0 ; i < count ; i++ ){
net.rim.device.api.ui.Field f = getField(i);
paintChild(graphics,f);
}
}
};
/*add(new LabelField(){
public int getPreferredHeight() {
return 10;
}
});*/
btnLeft.setChangeListener(this);
btnRight.setChangeListener(this);
btnLeft.setEnabled(false);
arrowButtonHfm.add(btnLeft);
arrowButtonHfm.add(btnRight);
add(arrowButtonHfm);
fillLicenseHolderInfoToField((LicenseObject)licenseInfoData.elementAt(currentIndex));
setHeaderText();
enableDisableButtons();
}
private void setHeaderText(){
header.setText("Search Results. ( "+(currentIndex+1)+ " of "+ (licenseInfoData.size())+" )");
}
private void fillLicenseHolderInfoToField(LicenseObject licenseObject){
bmpfDriverPhoto.setImage(licenseObject.getBmpImage());
clblLicenseNumber.setText(licenseObject.getLicenseNum());
clblFirstName.setText(licenseObject.getFirstName());
clblLastName.setText(licenseObject.getLastName());
clblBirthDate.setText(licenseObject.getDateOfBirth());
clblLicenseExpiry.setText(licenseObject.getDateOfExpiry());
clblLicenseType.setText(licenseObject.getLicenseType());
clblLicenseStatus.setText(licenseObject.getLicenseStatus());
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
if(field == btnRight){
if( currentIndex < (licenseInfoData.size() - 1)){
currentIndex++;
fillLicenseHolderInfoToField((LicenseObject)licenseInfoData.elementAt(currentIndex));
}
}else if(field == btnLeft){
if( currentIndex > 0 ){
currentIndex--;
fillLicenseHolderInfoToField((LicenseObject)licenseInfoData.elementAt(currentIndex));
}
}else if( field == bmpfDriverPhoto ){
ImagePopDialog dialog = new ImagePopDialog("loader-image-box.png");
Bitmap scaledBitmap = new Bitmap(300, 300);
Bitmap btnBitmap = bmpfDriverPhoto.getImage();
btnBitmap.scaleInto(0, 0, btnBitmap.getWidth(), btnBitmap.getHeight(),
scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), 1);
dialog.add(scaledBitmap);
UiApplication.getUiApplication().pushScreen(dialog);
}
enableDisableButtons();
setHeaderText();
}
private void enableDisableButtons(){
btnLeft.setEnabled((currentIndex > 0)?true:false);
btnRight.setEnabled((currentIndex < (licenseInfoData.size() - 1))?true:false);
}
protected boolean onSavePrompt() {
// TODO Auto-generated method stub
return true;
}
}
//Custom Image Button
package com.app.ui.component;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.TouchEvent;
/**
* *
* Class to Draw an Image Button
*/
public class CustomImageButton extends Field {
/** Bitmap for enabled image */
private Bitmap bmpEnabled;
/** Bitmap for disabled image */
private Bitmap bmpDisabled;
/** Label for Button*/
private String label;
private boolean mEnabled=true;
private int mCurrentTouchX = 0;
private int mCurrentTouchY = 0;
/**
* Constructor with
* #param image
*/
public CustomImageButton(Bitmap image) {
super(Field.FOCUSABLE);
this.bmpEnabled = image;
}
/**
* Constructor with
* #param enabled
* #param disabled
*/
public CustomImageButton(Bitmap enabled,Bitmap disabled) {
this(enabled);
this.bmpDisabled = disabled;
}
public CustomImageButton(Bitmap enabled, Bitmap disabled, String label) {
this(enabled);
this.bmpDisabled = disabled;
this.label = label;
}
protected void layout(int height, int width) {
height = getPreferredHeight();
width = getPreferredWidth();
setExtent(width,height);
}
protected void paint(Graphics graphics) {
if( isEnabled() ){
if(isFocus()){
int col = graphics.getColor();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, getPreferredHeight(), getPreferredHeight());
graphics.setColor(col);
}
graphics.drawBitmap(5, 5, bmpEnabled.getWidth(), bmpEnabled.getHeight(), bmpEnabled,
0, 0);
if(label != null && !label.equals("")) {
graphics.setColor(Color.BLACK);
graphics.drawText(label, bmpEnabled.getWidth()+5, (getPreferredHeight() - getFont().getHeight())/2);
}
}else{
if( bmpDisabled != null )
graphics.drawBitmap(5, 5, bmpDisabled.getWidth(), bmpDisabled.getHeight(), bmpDisabled,
0, 0);
if(label != null && !label.equals("")) {
graphics.setColor(Color.LIGHTGRAY);
graphics.drawText(label, bmpEnabled.getWidth()+5, (getPreferredHeight() - getFont().getHeight())/2);
}
}
}
public int getPreferredWidth() {
int prefwidth = 0;
if(bmpEnabled != null) {
prefwidth = bmpEnabled.getWidth();
}
if(label != null && !label.equals("")) {
prefwidth = Display.getWidth()+10;
}
return (prefwidth+10);
}
public int getPreferredHeight() {
if(bmpEnabled != null) {
return bmpEnabled.getHeight()+10;
}
return 0;
}
/*protected boolean navigationClick(int status, int time) {
fieldChangeNotify(0);
return true;
}*/
/**
* To set the focused background color and invalidating the entire screen
*/
protected void onFocus(int direction) {
invalidate();
}
/**
* To set the unfocused background color and invalidating the entire screen
*/
protected void onUnfocus() {
invalidate();
}
/**
* Draws the focus indicator for this field.
* #param graphics
* #param on
*/
protected void drawFocus(Graphics graphics, boolean on) {
super.drawFocus(graphics, on);
}
protected boolean navigationClick(int status, int time){
if( mEnabled ){
if (mCurrentTouchX >= 0 && mCurrentTouchX <= getPreferredWidth()
&& mCurrentTouchY >= 0
&& mCurrentTouchY <= getPreferredHeight())
fieldChangeNotify(1);
mCurrentTouchX = 0;
mCurrentTouchY = 0;
return true;
}else{
return false;
}
}
protected boolean touchEvent(TouchEvent message) {
if (mEnabled) {
if (message.getEvent() == TouchEvent.CLICK) {
mCurrentTouchX = message.getX(1);
mCurrentTouchY = message.getY(1);
}
}
return super.touchEvent(message);
}
public void setEnabled(boolean enabled) {
// TODO Auto-generated method stub
super.setEnabled(enabled);
if(!enabled)
this.focusRemove();
}
public void setImage(Bitmap image){
this.bmpEnabled = image;
}
public Bitmap getImage(){
return this.bmpEnabled;
}
}
In your CustomImageButton class you should change your setImage method:
public void setImage(Bitmap image){
this.bmpEnabled = image;
}
by adding an invalidate to cause a redraw:
public void setImage(Bitmap image){
this.bmpEnabled = image;
invalidate();
}
The problem is that when your image is replaced, the change isn't seen on screen until the screen has been refreshed. invalidate() triggers a refresh of the screen(or layout), allowing any updates to be seen.
When you scroll or select the image, the invalidate() method is getting called so as the screen refreshes, which is why it isn't updating until then. A manual trigger of invalidate() solves this problem.
Make sure you are doing it on the Event Thread.
Related
Hi I've implemented a toggle button for sound on my SettingsMenu, it works within this screen however when I go back to my main menu the functionality is lost and it resets back to its initial state. Any ideas how I can make it so that once it is clicked, it keeps this selection throughout every screen. I will show you the toggle button class and the settings class in which it is implemented. Thanks.
package uk.ac.qub.eeecs.game.cardDemo;
public class ToggleButtonSound extends GameObject {
protected enum ButtonState {
ON, OFF
}
private ButtonState mButtonState = ButtonState.OFF;
private SoundManager sm;
protected Bitmap mOffBitmap;
protected Bitmap mOnBitmap;
protected Bitmap mOnHoverBitmap;
protected Bitmap mOffHoverBitmap;
private Game mGame;
public boolean mMusicMuted = false;
public boolean mSoundMuted = false;
private MusicManager mMusicManager;
public ToggleButtonSound(float x, float y, float width, float height,
String offBitmap,
String onBitmap,
// String OffHoverBitmap,
//String OnHoverBitmap,
GameScreen gameScreen,
Game game) {
super(x, y, width, height,
gameScreen.getGame().getAssetManager().getBitmap(offBitmap), gameScreen);
mGame = game;
AssetStore assetStore = gameScreen.getGame().getAssetManager();
mOffBitmap = assetStore.getBitmap(offBitmap);
// mOffHoverBitmap = assetStore.getBitmap(offBitmap);
mOnBitmap = assetStore.getBitmap(onBitmap);
//mOnHoverBitmap = assetStore.getBitmap(onBitmap);
sm = new SoundManager(mGame);
mMusicManager = new MusicManager(mGame);
}
private boolean mPushTriggered;
private boolean mIsPushed;
/**
* Update the button
*
* #param elapsedTime Elapsed time information
*/
public void update(ElapsedTime elapsedTime) {
// Consider any touch events occurring in this update
Input input = mGame.getInput();
BoundingBox bound = getBound();
// Check for a press release on this button
for (TouchEvent touchEvent : input.getTouchEvents()) {
if (touchEvent.type == TouchEvent.TOUCH_UP
&& bound.contains(touchEvent.x, touchEvent.y)) {
// A touch up has occured in this control
if (mButtonState == ButtonState.OFF) {
setToggled(true);
} else {
setToggled(false);
}
return;
}
}
for (int idx = 0; idx < TouchHandler.MAX_TOUCHPOINTS; idx++) {
if (input.existsTouch(idx)) {
if (bound.contains(input.getTouchX(idx), input.getTouchY(idx))) {
if (!mIsPushed) {
mPushTriggered = true;
if (mOnHoverBitmap != null && mOffHoverBitmap != null)
mBitmap = mButtonState == ButtonState.ON ? mOnHoverBitmap : mOffHoverBitmap;
mIsPushed = true;
}
return;
}
}
}
if (mIsPushed) {
mBitmap = mButtonState == ButtonState.ON ? mOnBitmap : mOffBitmap;
mIsPushed = false;
mPushTriggered = false;
}
}
public boolean isToggledOn() {
return mButtonState == ButtonState.ON;
}
public void setToggled(boolean on) {
if (on) {
mButtonState = ButtonState.ON;
mBitmap = mOnBitmap;
} else {
mButtonState = ButtonState.OFF;
mBitmap = mOffBitmap;
}
}
#Override
public void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D,
LayerViewport layerViewport, ScreenViewport screenViewport) {
// Assumed to be in screen space so just draw the whole thing
drawScreenRect.set((int) (position.x - mBound.halfWidth),
(int) (position.y - mBound.halfWidth),
(int) (position.x + mBound.halfWidth),
(int) (position.y + mBound.halfHeight));
graphics2D.drawBitmap(mBitmap, null, drawScreenRect, null);
}
}
Settings menu
public class SettingsMenu extends GameScreen {
private ToggleButtonSound mToggleButtonSound;
public SettingsMenu(Game game) {
super("Settings Menu", game);
mSoundManager = new SoundManager(game);
mMenuScreen = new MenuScreen(game);
music = new MusicManager(game);
AssetStore assetManager = mGame.getAssetManager();
assetManager.loadAndAddBitmap("offswitch", "img/offswitch.png");
assetManager.loadAndAddBitmap("onswitch", "img/onswitch.png");
assetManager.loadAndAddBitmap("SoundOn", "img/Soundon.png");
assetManager.loadAndAddBitmap("SoundOff", "img/Soundoff.png");
assetManager.loadAndAddBitmap("SettingsBackground", "img/settingsbackground.png");
//Load in sound
assetManager.loadAndAddSound("mouseClick", "Sounds/clicksound.wav");
assetManager.loadAndAddMusic("BackgroundMusic", "Sounds/MenuScreenBackgroundMusic.mp3");
//initialise sound
int spacingX = mGame.getScreenWidth() / 3;
int spacingY = mGame.getScreenHeight() / 9;
mPlayButtonBound = new Rect(spacingX, 3 * spacingY, 2 * spacingX, 4 * spacingY);
mInventoryButtonBound = new Rect(spacingX, 5 * spacingY, 2 * spacingX, 6 * spacingY);
soundButtonBound = new Rect(game.getScreenWidth() / 100, game.getScreenWidth() / 100, game.getScreenWidth() / 10, game.getScreenWidth() / 10);
mSettingsBackground = new Rect(1, 1, game.getScreenWidth(), game.getScreenHeight());
mLayerViewport = new LayerViewport(0, 0, game.getScreenWidth(), game.getScreenHeight());
mScreenViewport = new ScreenViewport(0, 0, game.getScreenWidth(), game.getScreenHeight());
int toggleHeight = mGame.getScreenHeight()/3;
mToggleButtonMusic = new ToggleButtonMusic(game.getScreenWidth() / 100, game.getScreenWidth() / 200, game.getScreenWidth() / 10, game.getScreenWidth() / 20, "onswitch","offswitch","onswitch","offswitch", this, mGame);
mToggleButtonSound = new ToggleButtonSound(game.getScreenWidth() / 100, game.getScreenWidth() / 200, game.getScreenWidth() / 10, game.getScreenWidth() / 20, "onswitch","offswitch", this, mGame);
mToggleButtonMusic.setPosition(game.getScreenWidth()/2,game.getScreenHeight()/3);
mToggleButtonSound.setPosition(game.getScreenWidth()/2, toggleHeight*2);
//toggleB.getBitmap();
//toggleB.getBound();
}
private boolean mIsPushed;
#Override
public void update(ElapsedTime elapsedTime) {
music.isPlaying1();
//mToggleButtonSound.setToggled(soundMuted);
mToggleButtonMusic.update(elapsedTime);
mToggleButtonSound.update(elapsedTime);
Input input = mGame.getInput();
List<TouchEvent> touchEvents = input.getTouchEvents();
if (touchEvents.size() > 0) {
TouchEvent touchEvent = touchEvents.get(0);
if (touchEvent.type == TouchEvent.TOUCH_UP) {
if ((soundButtonBound.contains((int) touchEvent.x, (int) touchEvent.y))) {
mGame.getScreenManager().removeScreen("Settings Menu");
mMenuScreen = new MenuScreen(mGame);
mGame.getScreenManager().addScreen(mMenuScreen);
}
}
}
}
#Override
public void draw(ElapsedTime elapsedTime, IGraphics2D graphics2D) {
graphics2D.drawBitmap(mGame.getAssetManager().getBitmap("SettingsBackground"), null, mSettingsBackground, null);
mToggleButtonMusic.draw(elapsedTime,graphics2D,mLayerViewport, mScreenViewport);
mToggleButtonSound.draw(elapsedTime,graphics2D,mLayerViewport, mScreenViewport);
graphics2D.drawBitmap(mGame.getAssetManager().getBitmap("SoundOn"), null, soundButtonBound, null);
}
#Override
public boolean onBackPressed() {
return true;
}
}
I saw this library :
https://github.com/bluejamesbond/TextJustify-Android
but it's so complicated and don't know how to use it. I have a TextView that fill it programmatically from database in java. how can I use a simple library to justify it?!
UPDATE
I found this class in Github and it's perfect but I don't remember the link...!
public class JustifiedTextView extends View {
private Context mContext;
private XmlToClassAttribHandler mXmlParser;
private TextPaint textPaint;
private int lineSpace = 0;
private int lineHeight;
private int textAreaWidth;
private int measuredViewHeight, measuredViewWidth;
private String text;
private List<String> lineList = new ArrayList<String>();
/**
* when we want to draw text after view created to avoid loop in drawing we use this boolean
*/
boolean hasTextBeenDrown = false;
public JustifiedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
constructor(context, attrs);
}
public JustifiedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
constructor(context, attrs);
}
public JustifiedTextView(Context context) {
super(context);
constructor(context, null);
}
private void constructor(Context context, AttributeSet attrs) {
mContext = context;
mXmlParser = new XmlToClassAttribHandler(mContext, attrs);
initTextPaint();
if (attrs != null) {
String text;
int textColor;
int textSize;
int textSizeUnit;
text = mXmlParser.getTextValue();
textColor = mXmlParser.getColorValue();
textSize = mXmlParser.getTextSize();
textSizeUnit = mXmlParser.gettextSizeUnit();
setText(text);
setTextColor(textColor);
if (textSizeUnit == -1)
setTextSize(textSize);
else
setTextSize(textSizeUnit, textSize);
}
ViewTreeObserver observer = getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (hasTextBeenDrown)
return;
hasTextBeenDrown = true;
setTextAreaWidth(getWidth() - (getPaddingLeft() + getPaddingRight()));
calculate();
}
});
}
private void calculate() {
setLineHeight(getTextPaint());
lineList.clear();
lineList = divideOriginalTextToStringLineList(getText());
setMeasuredDimentions(lineList.size(), getLineHeight(), getLineSpace());
measure(getMeasuredViewWidth(), getMeasuredViewHeight());
}
private void initTextPaint() {
textPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
textPaint.setTextAlign( Paint.Align.RIGHT);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (getMeasuredViewWidth() > 0) {
requestLayout();
setMeasuredDimension(getMeasuredViewWidth(), getMeasuredViewHeight());
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
invalidate();
}
private int rowIndex = 0, colIndex = 0;
#Override
protected void onDraw(Canvas canvas) {
rowIndex = getPaddingTop();
if (getAlignment() == Paint.Align.RIGHT)
colIndex = getPaddingLeft() + getTextAreaWidth();
else
colIndex = getPaddingLeft();
for (int i = 0; i < lineList.size(); i++) {
rowIndex += getLineHeight() + getLineSpace();
canvas.drawText(lineList.get(i), colIndex, rowIndex, getTextPaint());
}
}
/**
* this method get the string and divide it to a list of StringLines according to textAreaWidth
*
* #param originalText
* #return
*/
private List<String> divideOriginalTextToStringLineList(String originalText) {
List<String> listStringLine = new ArrayList<String>();
String line = "";
float textWidth;
String[] listParageraphes = originalText.split("\n");
for (int j = 0; j < listParageraphes.length; j++) {
String[] arrayWords = listParageraphes[j].split(" ");
for (int i = 0; i < arrayWords.length; i++) {
line += arrayWords[i] + " ";
textWidth = getTextPaint().measureText(line);
//if text width is equal to textAreaWidth then just add it to ListStringLine
if (getTextAreaWidth() == textWidth) {
listStringLine.add(line);
line = "";//make line clear
continue;
}
//else if text width excite textAreaWidth then remove last word and justify the StringLine
else if (getTextAreaWidth() < textWidth) {
int lastWordCount = arrayWords[i].length();
//remove last word that cause line width to excite textAreaWidth
line = line.substring(0, line.length() - lastWordCount - 1);
// if line is empty then should be skipped
if (line.trim().length() == 0)
continue;
//and then we need to justify line
line = justifyTextLine(textPaint, line.trim(), getTextAreaWidth());
listStringLine.add(line);
line = "";
i--;
continue;
}
//if we are now at last line of paragraph then just add it
if (i == arrayWords.length - 1) {
listStringLine.add(line);
line = "";
}
}
}
return listStringLine;
}
/**
* this method add space in line until line width become equal to textAreaWidth
*
* #param lineString
* #param lineWidth
* #param textAreaWidth
* #return
*/
private String justifyTextLine(TextPaint textPaint, String lineString, int textAreaWidth) {
int gapIndex = 0;
float lineWidth = textPaint.measureText(lineString);
while (lineWidth < textAreaWidth && lineWidth > 0) {
gapIndex = lineString.indexOf(" ", gapIndex + 2);
if (gapIndex == -1) {
gapIndex = 0;
gapIndex = lineString.indexOf(" ", gapIndex + 1);
if (gapIndex == -1)
return lineString;
}
lineString = lineString.substring(0, gapIndex) + " " + lineString.substring(gapIndex + 1, lineString.length());
lineWidth = textPaint.measureText(lineString);
}
return lineString;
}
/**
* this method calculate height for a line of text according to defined TextPaint
*
* #param textPaint
*/
private void setLineHeight(TextPaint textPaint) {
Rect bounds = new Rect();
String sampleStr = "این حسین کیست که عالم همه دیوانه اوست";
textPaint.getTextBounds(sampleStr, 0, sampleStr.length(), bounds);
setLineHeight(bounds.height());
}
/**
* this method calculate view's height according to line count and line height and view's width
*
* #param lineListSize
* #param lineHeigth
* #param lineSpace
*/
public void setMeasuredDimentions(int lineListSize, int lineHeigth, int lineSpace) {
int mHeight = lineListSize * (lineHeigth + lineSpace) + lineSpace;
mHeight += getPaddingRight() + getPaddingLeft();
setMeasuredViewHeight(mHeight);
setMeasuredViewWidth(getWidth());
}
private int getTextAreaWidth() {
return textAreaWidth;
}
private void setTextAreaWidth(int textAreaWidth) {
this.textAreaWidth = textAreaWidth;
}
private int getLineHeight() {
return lineHeight;
}
private int getMeasuredViewHeight() {
return measuredViewHeight;
}
private void setMeasuredViewHeight(int measuredViewHeight) {
this.measuredViewHeight = measuredViewHeight;
}
private int getMeasuredViewWidth() {
return measuredViewWidth;
}
private void setMeasuredViewWidth(int measuredViewWidth) {
this.measuredViewWidth = measuredViewWidth;
}
private void setLineHeight(int lineHeight) {
this.lineHeight = lineHeight;
}
public String getText() {
return text;
}
/**
* Sets the string value of the JustifiedTextView. JustifiedTextView does not accept HTML-like formatting.
* Related XML Attributes
* -noghteh:text
*
* #param text
*/
public void setText(String text) {
this.text = text;
calculate();
invalidate();
}
public void setText(int resid) {
setText(mContext.getResources().getString(resid));
}
public Typeface getTypeFace() {
return getTextPaint().getTypeface();
}
public void setTypeFace(Typeface typeFace) {
getTextPaint().setTypeface(typeFace);
}
public float getTextSize() {
return getTextPaint().getTextSize();
}
public void setTextSize(int unit, float textSize) {
textSize = TypedValue.applyDimension(unit, textSize, mContext.getResources().getDisplayMetrics());
setTextSize(textSize);
}
private void setTextSize(float textSize) {
getTextPaint().setTextSize(textSize);
calculate();
invalidate();
}
public TextPaint getTextPaint() {
return textPaint;
}
public void setTextPaint(TextPaint textPaint) {
this.textPaint = textPaint;
}
/**
* set text color
*
* #param textColor
*/
public void setTextColor(int textColor) {
getTextPaint().setColor(textColor);
invalidate();
}
/**
* define space between lines
*
* #param lineSpace
*/
public void setLineSpacing(int lineSpace) {
this.lineSpace = lineSpace;
invalidate();
}
/**
* #return text color
*/
public int getTextColor() {
return getTextPaint().getColor();
}
/**
* space between lines - default is 0
*
* #return
*/
public int getLineSpace() {
return lineSpace;
}
/**
* get text alignment
*
* #return
*/
public Paint.Align getAlignment() {
return getTextPaint().getTextAlign();
}
/**
* Align text according to your language
*
* #param align
*/
public void setAlignment(Paint.Align align) {
getTextPaint().setTextAlign(align);
invalidate();
}}
And this class :
public class XmlToClassAttribHandler {
private Resources mRes;
private Context mContext;
private AttributeSet mAttributeSet;
private String namespace="http://noghteh.ir";
private final String KEY_TEXT="text";
private final String KEY_TEXT_SIZE="textSize";
private final String KEY_TEXT_COLOR="textColor";
public XmlToClassAttribHandler(Context context,AttributeSet attributeSet){
mContext=context;
mRes=mContext.getResources();
mAttributeSet=attributeSet;
}
public String getTextValue(){
String value=mAttributeSet.getAttributeValue(namespace, KEY_TEXT);
if (value==null)
return "";
if (value.length()>1 &&
value.charAt(0)=='#' &&
value.contains("#string/")){
int resId=mRes.getIdentifier(mContext.getPackageName()+":"+value.substring(1), null,null);
value=mRes.getString(resId);
}
return value;
}
public int getColorValue(){
String value=mAttributeSet.getAttributeValue(namespace, KEY_TEXT_COLOR);
int color= Color.BLACK;
if (value==null)
return color;
if (value.length()>1 &&
value.charAt(0)=='#' &&
value.contains("#color/")){
int resId=mRes.getIdentifier(mContext.getPackageName()+":"+value.substring(1), null,null);
color=mRes.getColor(resId);
return color;
}
try{
color=Color.parseColor(value);
}
catch(Exception e){
return Color.BLACK;
}
return color;
}
public int getTextSize() {
int textSize=12;
String value=mAttributeSet.getAttributeValue(namespace, KEY_TEXT_SIZE );
if (value==null)
return textSize;
if (value.length()>1 &&
value.charAt(0)=='#' &&
value.contains("#dimen/")){
int resId=mRes.getIdentifier(mContext.getPackageName()+":"+value.substring(1), null,null);
textSize=mRes.getDimensionPixelSize(resId);
return textSize;
}
try{
textSize=Integer.parseInt(value.substring(0, value.length()-2));
}
catch(Exception e){
return 12;
}
return textSize;
}
public int gettextSizeUnit() {
String value=mAttributeSet.getAttributeValue(namespace, KEY_TEXT_SIZE );
if (value==null)
return TypedValue.COMPLEX_UNIT_SP;
try{
String type=value.substring(value.length()-2, value.length());
if (type.equals("dp"))
return TypedValue.COMPLEX_UNIT_DIP;
else if (type.equals("sp"))
return TypedValue.COMPLEX_UNIT_SP;
else if (type.equals("pt"))
return TypedValue.COMPLEX_UNIT_PT;
else if (type.equals("mm"))
return TypedValue.COMPLEX_UNIT_MM;
else if (type.equals("in"))
return TypedValue.COMPLEX_UNIT_IN;
else if (type.equals("px"))
return TypedValue.COMPLEX_UNIT_PX;
}
catch(Exception e){
return -1;
}
return -1;
}}
and then define a JustifiedTextView instead of simple TextView in your XML file...!!
Follow the instructions in the readme.
Add to your build.gradle
dependencies {
compile 'com.github.bluejamesbond:textjustify-android:2.1.1'
}
Then you define a DocumentView instead of a TextView:
<com.bluejamesbond.text.DocumentView
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
You could also use https://github.com/merterhk/JustifiedTextView which is just a single class to avoid having to incorporate a new library.
I have 3 classes. One class is my mainframe, another class is my JInternalFrame and also my Observer and the third class does a simulation with a field ob buttons and that one is also my observable class.
Basically I made a button in my observer that copies itself. That includes the add to the desktoppane and the addObserver function of my observable class.
The clone of my observer should also observer the very same observable. So if I interact with the one JInternalFrame, it also changes stuff for the other InternalFrame. It should act like a mirror. (Actually the copy should have like diffrent color buttons and a diffrent orientation but I think that should not be a problem to implement, as soon as I successfully could mirror my Observer)
So since I am using the Observable pattern, I also have to implement the "update" function in my Observer class. I did that and I works like a charm. But when I copy my JInternalFrame, the new InternalFrame observes the Observable(Simulation), but my original JInternalFrame loses the observable connection. It does not show buttons anymore etc.
What I tried: I created a second Observer/JInternalFrame class that extends my first Observer class. That did not work as well. I don't know if thats even a possibility to achieve what I want to.
Sorry for my non perfect english. Sorry for some german words that you might find in the code and sorry that I post so much code. But I am really uncertain right now where my mistake is since I tried to find the error for ours so far.
So here are 2 pictures for you:
First picture shows how my JInternalFrame looks like when I create it. Here everything works perfectly.
Second picture shows what it looks like when I click on the New View button. As already described. The original JInternalFrame does not show the simulation anymore. Although they are both observing the same Observable.
And here are my 3 imporant classes:
MainFrame:
public class LangtonsAmeise extends JFrame implements ActionListener {
JDesktopPane desk;
JPanel panelButtons;
JMenuBar jmb;
JMenu file, modus;
JMenuItem load, save, exit, mSetzen, mMalen, mLaufen;
JSlider slider;
static int xInt, yInt, xKindFrame = 450, yKindFrame = 450, xLocation,
yLocation, xMainFrame = 1000, yMainFrame = 900;
static boolean bSetzen = false, bMalen = false, running = true;
static JFileChooser fc;
Random randomGenerator = new Random();
JLabel xLabel, yLabel, speed, statusText, status;
JButton start, stop, addAnt;
JTextField xField, yField;
public LangtonsAmeise() {
// Desktop
desk = new JDesktopPane();
getContentPane().add(desk, BorderLayout.CENTER);
// File Chooser
fc = new JFileChooser(System.getProperty("user.dir"));
speed = new JLabel("Geschwindigkeit");
xLabel = new JLabel("x:");
yLabel = new JLabel("y:");
xLabel.setHorizontalAlignment(JLabel.RIGHT);
yLabel.setHorizontalAlignment(JLabel.RIGHT);
xLabel.setOpaque(true);
yLabel.setOpaque(true);
xField = new JTextField();
yField = new JTextField();
start = new JButton("Fenster erstellen");
stop = new JButton("Pause/Fortsetzen");
start.setMargin(new Insets(0, 0, 0, 0));
stop.setMargin(new Insets(0, 0, 0, 0));
// Buttons
panelButtons = new JPanel();
panelButtons.setLayout(new GridLayout());
panelButtons.add(start);
panelButtons.add(xLabel);
panelButtons.add(xField);
panelButtons.add(yLabel);
panelButtons.add(yField);
panelButtons.add(speed);
panelButtons.add(new Panel());
panelButtons.add(stop);
start.addActionListener(this);
stop.addActionListener(this);
add(panelButtons, BorderLayout.NORTH);
statusText = new JLabel("Status:");
status = new JLabel("Stopp");
// JMenuBar
jmb = new JMenuBar();
setJMenuBar(jmb);
file = new JMenu("File");
modus = new JMenu("Mode");
mLaufen = new JMenuItem("Laufen");
mMalen = new JMenuItem("Malen");
mSetzen = new JMenuItem("Setzen");
load = new JMenuItem("Simulation laden");
//save = new JMenuItem("Simulation speichern");
mSetzen.addActionListener(this);
mMalen.addActionListener(this);
mLaufen.addActionListener(this);
exit = new JMenuItem("Exit");
file.add(load);
file.addSeparator();
file.add(exit);
load.addActionListener(this);
modus.add(mLaufen);
modus.add(mSetzen);
modus.add(mMalen);
jmb.add(file);
jmb.add(modus);
for (int i = 0; i < 20; i++) {
jmb.add(new JLabel(" "));
}
jmb.add(statusText);
jmb.add(status);
setSize(new Dimension(xMainFrame, yMainFrame));
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height
/ 2 - this.getSize().height / 2);
xField.setText("5");
yField.setText("5");
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Fenster erstellen")) {
if (xField.getText().equals("") || yField.getText().equals("")) {
} else {
xInt = Integer.parseInt(xField.getText());
yInt = Integer.parseInt(yField.getText());
state s = new state();
kindFenster k = new kindFenster(s, this);
s.addObserver(k);
addChild(k);
s.startSimulation();
}
}
if (e.getActionCommand().equals("Pause/Fortsetzen")) {
running = !running;
System.out.println(running);
status.setText("Stopp");
}
if (e.getActionCommand().equals("Setzen")) {
status.setText("Setzen");
running = false;
bSetzen = true;
bMalen = false;
}
if (e.getActionCommand().equals("Laufen")) {
status.setText("Laufen");
running = true;
bSetzen = false;
bMalen = false;
}
if (e.getActionCommand().equals("Malen")) {
status.setText("Malen");
running = false;
bSetzen = false;
bMalen = true;
}
if (e.getActionCommand().equals("Simulation laden")) {
LangtonsAmeise.running = false;
InputStream fis = null;
try {
fc.showOpenDialog(null);
fis = new FileInputStream(fc.getSelectedFile().getPath());
ObjectInputStream ois = new ObjectInputStream(fis);
state s = (state) ois.readObject();
kindFenster k = new kindFenster(s, this);
s.addObserver(k);
addChild(k);
s.startSimulation();
} catch (IOException | ClassNotFoundException
| NullPointerException e1) {
LangtonsAmeise.running = true;
} finally {
try {
fis.close();
} catch (NullPointerException | IOException e1) {
LangtonsAmeise.running = true;
}
}
LangtonsAmeise.running = true;
}
}
public void addChild(JInternalFrame kind) {
xLocation = randomGenerator.nextInt(xMainFrame - xKindFrame);
yLocation = randomGenerator.nextInt(yMainFrame - yKindFrame - 100);
kind.setSize(370, 370);
kind.setLocation(xLocation, yLocation);
desk.add(kind);
kind.setVisible(true);
}
public static void main(String[] args) {
LangtonsAmeise hauptFenster = new LangtonsAmeise();
}
}
JInternalFrame:
public class kindFenster extends JInternalFrame implements ActionListener,
Serializable,Observer,Cloneable {
/**
*
*/
private static final long serialVersionUID = 8939449766068226519L;
static int nr = 0;
static int x,y,xScale,yScale,xFrame,yFrame;
state s;
ArrayList<ImageIcon> ameisen = new ArrayList<ImageIcon>();
JFileChooser fc;
LangtonsAmeise la;
Color alteFarbe, neueFarbe;
JButton save, addAnt, newView;
JPanel panelButtonsKind;
JSlider sliderKind;
public JPanel panelSpielfeld,panelSpielfeldKopie;
JButton[] jbArrayy;
static SetzenActionListener sal = new SetzenActionListener();
static MouseMotionActionListener mmal = new MouseMotionActionListener();
public kindFenster(state s,LangtonsAmeise la) {
super("Kind " + (++nr), true, true, true, true);
setLayout(new BorderLayout());
this.s=s;
jbArrayy=new JButton[s.jbArrayy.length];
for (int b = 1; b<s.jbArrayy.length;b++) {
this.jbArrayy[b] = s.jbArrayy[b];
}
this.la=la;
setSize(new Dimension(xFrame, yFrame));
this.addInternalFrameListener(listener);
this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
panelSpielfeld = new JPanel();
panelSpielfeld.setLayout(new GridLayout(s.y, s.x));
panelButtonsKind = new JPanel();
panelButtonsKind.setLayout(new GridLayout(1, 3));
save = new JButton("<html>Save<br>simulation</html>");
addAnt = new JButton("<html>Add<br>ant</html>");
newView = new JButton("<html>New<br>View</html>");
save.setActionCommand("save");
addAnt.setActionCommand("addAnt");
newView.setActionCommand("newView");
save.setMargin(new Insets(0, 0, 0, 0));
addAnt.setMargin(new Insets(0, 0, 0, 0));
addAnt.addActionListener(this);
save.addActionListener(this);
newView.addActionListener(this);
sliderKind = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);
sliderKind.setSnapToTicks(true);
sliderKind.setPaintTicks(true);
sliderKind.setPaintTrack(true);
sliderKind.setMajorTickSpacing(1);
sliderKind.setPaintLabels(true);
sliderKind.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
if (!source.getValueIsAdjusting()) {
int speed = source.getValue();
state.sleeptime = 1000 / speed;
}
}
});
panelButtonsKind.add(save);
panelButtonsKind.add(newView);
panelButtonsKind.add(sliderKind);
panelButtonsKind.add(addAnt);
add(panelButtonsKind, BorderLayout.NORTH);
add(panelSpielfeld, BorderLayout.CENTER);
this.addComponentListener(new MyComponentAdapter());
for (int i = 1 ; i<jbArrayy.length;i++) {
panelSpielfeld.add(jbArrayy[i]);
}
}
// I have been trying around to change the orientation of the buttons in the copy of the frame
public void secondViewFrameSettings() {
int temp;
for (int i = 1; i<=x;i++) {
for (int k = 0; k<y;k++) {
temp = i+(k*x);
panelSpielfeldKopie.add(s.jbArrayy[temp]);
}
}
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("addAnt")) {
s.addAnt();
}
if (e.getActionCommand().equals("newView")){
kindFenster kk = new kindFenster(s,la);
s.addObserver(kk);
la.addChild(kk);
}
if (e.getActionCommand().equals("save")) {
OutputStream fos = null;
try {
LangtonsAmeise.running=false;
try {
fc = new JFileChooser(System.getProperty("user.dir"));
fc.showSaveDialog(null);
LangtonsAmeise.fc.setCurrentDirectory(fc.getSelectedFile());
fos = new FileOutputStream(fc.getSelectedFile());
ObjectOutputStream o = new ObjectOutputStream(fos);
o.writeObject(s);
} catch (NullPointerException e2) {
System.out.println("Fehler beim Auswählen der Datei. Wenden Sie sich an den Entwickler.");
}
} catch (IOException e1) {
LangtonsAmeise.running=true;
System.err.println(e1);
} finally {
try {
fos.close();
} catch (NullPointerException | IOException e1) {
LangtonsAmeise.running=true;
}
LangtonsAmeise.running=true;
}
LangtonsAmeise.running=true;
}
}
InternalFrameListener listener = new InternalFrameAdapter() {
public void internalFrameClosing(InternalFrameEvent e) {
e.getInternalFrame().dispose();
s.simulation.suspend();
}
};
class MyComponentAdapter extends ComponentAdapter {
public void componentResized(ComponentEvent e) {
//Ameisenbilder an die Buttongrößen anpassen
xScale=s.jbArrayy[1].getSize().width;
yScale=s.jbArrayy[1].getSize().height;
s.ameisen.clear();
s.ameisen.add(new ImageIcon(new ImageIcon("ameise.gif")
.getImage().getScaledInstance(xScale, yScale,
Image.SCALE_SMOOTH)));
s.ameisen.add(new ImageIcon(new ImageIcon("ameise90.gif")
.getImage().getScaledInstance(xScale, yScale,
Image.SCALE_SMOOTH)));
s.ameisen.add(new ImageIcon(new ImageIcon("ameise180.gif")
.getImage().getScaledInstance(xScale, yScale,
Image.SCALE_SMOOTH)));
s.ameisen.add(new ImageIcon(new ImageIcon("ameise270.gif")
.getImage().getScaledInstance(xScale, yScale,
Image.SCALE_SMOOTH)));
}
}
public void update(Observable o, Object arg) {
if (o == s) {
for (int i = 1;i<s.jbArrayy.length;i++) {
jbArrayy[i].setBackground(s.jbArrayy[i].getBackground());
}
}
}
}
class SetzenActionListener implements ActionListener,Serializable {
JButton source;
#Override
public void actionPerformed(ActionEvent e) {
source = (JButton) e.getSource();
if (LangtonsAmeise.bSetzen == true) {
if (source.getBackground().equals(Color.GREEN)) {
source.setBackground(Color.WHITE);
} else {
source.setBackground(Color.GREEN);
}
}
}
}
class MouseMotionActionListener extends MouseInputAdapter implements Serializable {
boolean dragged = false;
JButton tempJButton = new JButton();
public void mouseEntered(MouseEvent e) {
if (LangtonsAmeise.bMalen == true && dragged == true) {
((JButton) e.getSource()).setBackground(Color.GREEN);
}
}
public void mouseDragged(MouseEvent e) {
dragged = true;
}
public void mouseReleased(MouseEvent e) {
dragged = false;
}
}
Observable class:
public class state extends Observable implements Serializable {
/**
*
*/
private static final long serialVersionUID = 450773214079105589L;
int[] obRand, reRand, unRand, liRand;
int x, y, temp;
static int sleeptime = 200;
Color background;
int posAmeise, aktuellesIcon = 1, altePosAmeise, xScale, yScale;
Color alteFarbe, neueFarbe, color1, color2;
ArrayList<JButton> jbSer = new ArrayList<JButton>();
private List<Ant> ants = new ArrayList<Ant>();
ArrayList<ImageIcon> ameisen = new ArrayList<>();
JButton[] jbArrayy;
transient Thread simulation;
public state() {
this.x = LangtonsAmeise.xInt;
this.y = LangtonsAmeise.yInt;
color1 = Color.WHITE;
color2 = Color.GREEN;
jbArrayy = new JButton[x * y + 1];
initializeBorders();
initializeAntsImages();
initializeSimulationButtons();
xScale = jbArrayy[1].getSize().width;
yScale = jbArrayy[1].getSize().height;
// Startpunkt für die Ameise festlegen
posAmeise = (((x / 2) * y) - y / 2);
background = jbArrayy[posAmeise].getBackground();
ants.add(new Ant(this));
}
public void initializeAntsImages() {
ameisen.add(new ImageIcon(new ImageIcon("ameise.gif").getImage()
.getScaledInstance(LangtonsAmeise.xKindFrame / x,
LangtonsAmeise.yKindFrame / y, Image.SCALE_SMOOTH)));
ameisen.add(new ImageIcon(new ImageIcon("ameise90.gif").getImage()
.getScaledInstance(LangtonsAmeise.xKindFrame / x,
LangtonsAmeise.yKindFrame / y, Image.SCALE_SMOOTH)));
ameisen.add(new ImageIcon(new ImageIcon("ameise180.gif").getImage()
.getScaledInstance(LangtonsAmeise.xKindFrame / x,
LangtonsAmeise.yKindFrame / y, Image.SCALE_SMOOTH)));
ameisen.add(new ImageIcon(new ImageIcon("ameise270.gif").getImage()
.getScaledInstance(LangtonsAmeise.xKindFrame / x,
LangtonsAmeise.yKindFrame / y, Image.SCALE_SMOOTH)));
}
// Alle Buttons für das Simulationsfeld werden erstellt
public void initializeSimulationButtons() {
jbArrayy[0] = new JButton();
for (int i = 1; i < jbArrayy.length; i++) {
jbArrayy[i] = new JButton();
jbArrayy[i].setBackground(color1);
jbArrayy[i].addActionListener(kindFenster.sal);
jbArrayy[i].addMouseListener(kindFenster.mmal);
jbArrayy[i].addMouseMotionListener(kindFenster.mmal);
}
}
// Ränderindex in Array schreiben
public void initializeBorders() {
reRand = new int[y];
liRand = new int[y];
obRand = new int[x];
unRand = new int[x];
for (int i = 0; i < x; i++) {
obRand[i] = i + 1;
unRand[i] = (x * y - x) + i + 1;
}
for (int i = 1; i <= y; i++) {
reRand[i - 1] = i * x;
liRand[i - 1] = i * x - (x - 1);
}
}
public void initializeSimulation() {
if (simulation != null && simulation.isAlive()) {
simulation.stop();
}
simulation = new Thread() {
#Override
public void run() {
super.run();
while (true) {
try {
sleep(300);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
while (LangtonsAmeise.running && countObservers() > 0) {
try {
Thread.sleep(sleeptime);
for (Ant a : ants) {
move(a);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
}
public void startSimulation() {
initializeSimulation();
simulation.start();
}
public void changeColor(int altePos, Color c) {
jbArrayy[altePos].setBackground(c);
}
public void addAnt() {
ants.add(new Ant(this));
}
public void changeIcon(boolean k, Ant a) {
int g = (k == true) ? 1 : -1;
if (a.aktuellesIcon + g < 0) {
a.aktuellesIcon = 3;
} else if (a.aktuellesIcon + g > 3) {
a.aktuellesIcon = 0;
} else {
a.aktuellesIcon += g;
}
jbArrayy[a.posAmeise].setIcon(ameisen.get(a.aktuellesIcon));
setChanged();
notifyObservers();
}
public void rightCheck(Ant a) {
if (checkInArray(a.posAmeise, reRand)) {
a.posAmeise -= x - 1;
} else {
a.posAmeise += 1;
}
}
public void leftCheck(Ant a) {
if (checkInArray(a.posAmeise, liRand)) {
a.posAmeise += x - 1;
} else {
a.posAmeise -= 1;
}
}
public void upCheck(Ant a) {
if (checkInArray(a.posAmeise, obRand)) {
a.posAmeise += (y - 1) * x;
} else {
a.posAmeise -= x;
}
}
public void downCheck(Ant a) {
if (checkInArray(a.posAmeise, unRand)) {
a.posAmeise -= (y - 1) * x;
} else {
a.posAmeise += x;
}
}
public void checkAmeisenSize(Ant a) {
while (!(ameisen.size() == 4)) {
}
;
}
public static boolean checkInArray(int currentState, int[] myArray) {
int i = 0;
for (; i < myArray.length; i++) {
if (myArray[i] == currentState)
break;
}
return i != myArray.length;
}
public ImageIcon getAntImage() {
return ameisen.get(aktuellesIcon);
}
public void move(Ant a) throws InterruptedException {
try {
a.altePosAmeise = a.posAmeise;
a.alteFarbe = jbArrayy[a.posAmeise].getBackground();
if (a.alteFarbe.equals(Color.GREEN) && ameisen.size() == 4) {
if (a.aktuellesIcon == 0) {
checkAmeisenSize(a);
rightCheck(a);
} else if (a.aktuellesIcon == 1) {
checkAmeisenSize(a);
downCheck(a);
} else if (a.aktuellesIcon == 2) {
checkAmeisenSize(a);
leftCheck(a);
} else if (a.aktuellesIcon == 3) {
checkAmeisenSize(a);
upCheck(a);
}
changeIcon(true, a);
changeColor(a.altePosAmeise, Color.WHITE);
} else if (a.alteFarbe.equals(Color.WHITE) && ameisen.size() == 4) {
if (a.aktuellesIcon == 0) {
checkAmeisenSize(a);
leftCheck(a);
} else if (a.aktuellesIcon == 1) {
checkAmeisenSize(a);
upCheck(a);
} else if (a.aktuellesIcon == 2) {
checkAmeisenSize(a);
rightCheck(a);
} else if (a.aktuellesIcon == 3) {
checkAmeisenSize(a);
downCheck(a);
}
changeIcon(false, a);
changeColor(a.altePosAmeise, Color.GREEN);
setChanged();
notifyObservers();
}
jbArrayy[a.altePosAmeise].setIcon(new ImageIcon());
} catch (IndexOutOfBoundsException e) {
move(a);
}
}
}
Edit: Ant Class
import java.awt.Color;
import java.awt.Image;
import java.io.Serializable;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public class Ant implements Serializable {
int posAmeise, aktuellesIcon = 1, altePosAmeise;
Color alteFarbe, neueFarbe;
ArrayList<ImageIcon> ameisen = new ArrayList<>();
public Ant(state s) {
this.posAmeise = s.posAmeise;
s.jbArrayy[posAmeise].setIcon(s.ameisen.get(aktuellesIcon));
}
}
I have a game that displays circles randomly on the screen. The circles can be green or red at random. If you touch a red circle something happens; if you touch a green circle something happens; but what if you wanted to check if the green circle was displayed and a user did not click it? Here is my code:
public class DrawingView extends View{
public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
RectF rectf = new RectF(0, 0, 200, 0);
private static final int w = 100;
public static int lastColor = Color.BLACK;
private final Random random = new Random();
private final Paint paint = new Paint();
private final int radius = 230;
private final Handler handler = new Handler();
public static int redColor = Color.RED;
public static int greenColor = Color.GREEN;
int randomWidth = 0;
int randomHeight = 0;
public static int addPoints = 0;
public static int savedScore;
public static List<String> a = new ArrayList<String>();
public static String[] savedScores = new String[a.size()];
Paint red;
public static int howManyPoints;
public static int highestScore = 0;
boolean isTouched;
Thread newThread = new Thread();
private final Runnable updateCircle = new Runnable() {
#Override
public void run() {
lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
paint.setColor(lastColor);
if(lastColor == greenColor){
isTouched = false;
}
if(addPoints < 10){
handler.postDelayed(this, 850);
}
if(addPoints > 9 && addPoints < 30){
handler.postDelayed(this,700);
}
if(addPoints > 29){
handler.postDelayed(this, 600);
}
if(addPoints > 50){
handler.postDelayed(this, 450);
}
if(addPoints > 100){
handler.postDelayed(this, 400);
}
postInvalidate();
}
};
public void what(){
try {
newThread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(isTouched == false){
howManyPoints = addPoints;
handler.removeCallbacks(updateCircle);
lastColor = redColor;
addPoints = 0;
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
}
}
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
handler.post(updateCircle);
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
handler.removeCallbacks(updateCircle);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// your other stuff here
Paint back = new Paint();
back.setColor(Color.BLACK);
Rect background = new Rect();
background.set(0, 0, canvas.getWidth(),canvas.getHeight() );
canvas.drawRect(background, back);
Paint newPaint = new Paint();
newPaint.setColor(Color.BLUE);
newPaint.setTextSize(60);
canvas.drawText("Beta v2", 10, 60, newPaint);
if(random == null){
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}else {
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}
canvas.drawCircle(randomWidth, randomHeight, radius, paint);
what();
red = new Paint();
red.setColor(Color.BLUE);
red.setTextSize(150);
canvas.drawText("" + addPoints, 500, 1350, red);
}
#SuppressWarnings("deprecation")
#Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX();
int y = (int) event.getY();
if(isInsideCircle(x, y) == true){
//Do your things here
if(lastColor == redColor){
//saveScore();
howManyPoints = addPoints;
if(howManyPoints > highestScore){
highestScore = howManyPoints;
}
handler.removeCallbacks(updateCircle);
lastColor = redColor;
addPoints = 0;
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
}
if(lastColor == greenColor){
addPoints++;
isTouched = true;
}
}else {
}
}
return false;
}
public void saveScore() {
a.add("" + addPoints);
//if(Integer.parseInt(savedScores[1]) < addPoints){
//savedScores[2] = savedScores[1];
//int x = Integer.parseInt(savedScores[1]);
//x = addPoints;
//}
}
public boolean isInsideCircle(int x, int y){
if ((((x - randomWidth)*(x - randomWidth)) + ((y - randomHeight)*(y - randomHeight))) < ((radius)*(radius))){
return true;
}
return false;
}
}
Just add a boolean hasBeenClicked that is false and becomes true when the user touches it
Good morning,
First my mission is want to make my JTabbedPane Drag-out to window and create new JFrame. Illustration is like NetBeans / SublimeText,
I Found reference for drag & drop JTabbedPane in https://stackoverflow.com/a/61982 , It is success to drag and drop Tab from 1 JTabbedPane or 2/many JTabbedPane
now what i want is whenever drag-out tab the document, it automatic create new Frame and insert tab to new jtabbedPane. And If the jtabbedpane is empty / no-component, the jframe is automatic closed.
--
"Shorted Question"
Can i have, when I drag tab (from jtabbedpane) to desktop/outside JFrame and automatic create JFrame & Tabbedpane inside then placed the tab there ?
Also When the tab drag&drop and there is none component in jtabbedpane, it's can automatic dispose the JFrame/JTabbedPane.
"Very Shorted Question"
How can i get my JTabbedPane like Netbeans TabbedPane Document Editor ?
--
I Include the file my latest Modified Drag & Drop JTabbedPane with Close Button.
Thank you very much. R.
public class DnDCloseButtonTabbedPane extends JTabbedPane {
public static final long serialVersionUID = 1L;
private static final int LINEWIDTH = 3;
private static final String NAME = "TabTransferData";
private final DataFlavor FLAVOR = new DataFlavor(
DataFlavor.javaJVMLocalObjectMimeType, NAME);
private static GhostGlassPane s_glassPane = new GhostGlassPane();
private boolean m_isDrawRect = false;
private final Rectangle2D m_lineRect = new Rectangle2D.Double();
private final Color m_lineColor = new Color(0, 100, 255);
private TabAcceptor m_acceptor = null;
private final DropTarget dropTarget;
private final ImageIcon icon;
private final Dimension buttonSize;
public DnDCloseButtonTabbedPane() {
super();
final DragSourceListener dsl = new DragSourceListener() {
#Override
public void dragEnter(DragSourceDragEvent e) {
e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
}
#Override
public void dragExit(DragSourceEvent e) {
e.getDragSourceContext()
.setCursor(DragSource.DefaultMoveNoDrop);
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
s_glassPane.setPoint(new Point(-1000, -1000));
s_glassPane.repaint();
// System.out.println(e);
}
#Override
public void dragOver(DragSourceDragEvent e) {
//e.getLocation()
//This method returns a Point indicating the cursor location in screen coordinates at the moment
TabTransferData data = getTabTransferData(e);
if (data == null) {
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveNoDrop);
return;
} // if
/*
Point tabPt = e.getLocation();
SwingUtilities.convertPointFromScreen(tabPt, DnDTabbedPane.this);
if (DnDTabbedPane.this.contains(tabPt)) {
int targetIdx = getTargetTabIndex(tabPt);
int sourceIndex = data.getTabIndex();
if (getTabAreaBound().contains(tabPt)
&& (targetIdx >= 0)
&& (targetIdx != sourceIndex)
&& (targetIdx != sourceIndex + 1)) {
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveDrop);
return;
} // if
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveNoDrop);
return;
} // if
*/
e.getDragSourceContext().setCursor(
DragSource.DefaultMoveDrop);
}
public void dragDropEnd(DragSourceDropEvent e) {
m_isDrawRect = false;
m_lineRect.setRect(0, 0, 0, 0);
// m_dragTabIndex = -1;
if (hasGhost()) {
s_glassPane.setVisible(false);
s_glassPane.setImage(null);
}
}
#Override
public void dropActionChanged(DragSourceDragEvent e) {
}
};
final DragGestureListener dgl = new DragGestureListener() {
#Override
public void dragGestureRecognized(DragGestureEvent e) {
// System.out.println("dragGestureRecognized");
Point tabPt = e.getDragOrigin();
int dragTabIndex = indexAtLocation(tabPt.x, tabPt.y);
if (dragTabIndex < 0) {
return;
} // if
initGlassPane(e.getComponent(), e.getDragOrigin(), dragTabIndex);
try {
e.startDrag(DragSource.DefaultMoveDrop,
new TabTransferable(DnDCloseButtonTabbedPane.this, dragTabIndex), dsl);
} catch (InvalidDnDOperationException idoe) {
idoe.printStackTrace();
}
}
};
//dropTarget =
dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE,
new CDropTargetListener(), true);
new DragSource().createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY_OR_MOVE, dgl);
m_acceptor = new TabAcceptor() {
#Override
public boolean isDropAcceptable(DnDCloseButtonTabbedPane a_component, int a_index) {
return true;
}
};
icon = new ImageIcon(getClass().getResource(Resource.ICON_16X16 + "delete.png"));
buttonSize = new Dimension(icon.getIconWidth(), icon.getIconHeight());
}
#Override
public void addTab(String title, final Component component) {
JPanel tab = new JPanel(new BorderLayout());
tab.setOpaque(false);
JLabel label = new JLabel(title);
label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 4));
JButton button = new JButton(icon);
button.setPreferredSize(buttonSize);
button.setUI(new BasicButtonUI());
button.setContentAreaFilled(false);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
((DnDCloseButtonTabbedPane) component.getParent()).remove(component);
}
});
tab.add(label, BorderLayout.WEST);
tab.add(button, BorderLayout.EAST);
tab.setBorder(BorderFactory.createEmptyBorder(2, 1, 1, 1));
super.addTab(title, component);
setTabComponentAt(indexOfComponent(component), tab);
}
public TabAcceptor getAcceptor() {
return m_acceptor;
}
public void setAcceptor(TabAcceptor a_value) {
m_acceptor = a_value;
}
private TabTransferData getTabTransferData(DropTargetDropEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private TabTransferData getTabTransferData(DropTargetDragEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private TabTransferData getTabTransferData(DragSourceDragEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getDragSourceContext()
.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private TabTransferData getTabTransferData(DragSourceDropEvent a_event) {
try {
TabTransferData data = (TabTransferData) a_event.getDragSourceContext()
.getTransferable().getTransferData(FLAVOR);
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
class TabTransferable implements Transferable {
private TabTransferData m_data = null;
public TabTransferable(DnDCloseButtonTabbedPane a_tabbedPane, int a_tabIndex) {
m_data = new TabTransferData(DnDCloseButtonTabbedPane.this, a_tabIndex);
}
public Object getTransferData(DataFlavor flavor) {
return m_data;
// return DnDTabbedPane.this;
}
public DataFlavor[] getTransferDataFlavors() {
DataFlavor[] f = new DataFlavor[1];
f[0] = FLAVOR;
return f;
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.getHumanPresentableName().equals(NAME);
}
}
class TabTransferData {
private DnDCloseButtonTabbedPane m_tabbedPane = null;
private int m_tabIndex = -1;
public TabTransferData() {
}
public TabTransferData(DnDCloseButtonTabbedPane a_tabbedPane, int a_tabIndex) {
m_tabbedPane = a_tabbedPane;
m_tabIndex = a_tabIndex;
}
public DnDCloseButtonTabbedPane getTabbedPane() {
return m_tabbedPane;
}
public void setTabbedPane(DnDCloseButtonTabbedPane pane) {
m_tabbedPane = pane;
}
public int getTabIndex() {
return m_tabIndex;
}
public void setTabIndex(int index) {
m_tabIndex = index;
}
}
private Point buildGhostLocation(Point a_location) {
Point retval = new Point(a_location);
// switch (getTabPlacement()) {
// case JTabbedPane.TOP: {
// retval.y = 1;
// retval.x -= s_glassPane.getGhostWidth() / 2;
// }
// break;
//
// case JTabbedPane.BOTTOM: {
// retval.y = getHeight() - 1 - s_glassPane.getGhostHeight();
// retval.x -= s_glassPane.getGhostWidth() / 2;
// }
// break;
//
// case JTabbedPane.LEFT: {
// retval.x = 1;
// retval.y -= s_glassPane.getGhostHeight() / 2;
// }
// break;
//
// case JTabbedPane.RIGHT: {
// retval.x = getWidth() - 1 - s_glassPane.getGhostWidth();
// retval.y -= s_glassPane.getGhostHeight() / 2;
// }
// break;
// } // switch
retval = SwingUtilities.convertPoint(DnDCloseButtonTabbedPane.this,
retval, s_glassPane);
return retval;
}
class CDropTargetListener implements DropTargetListener {
public void dragEnter(DropTargetDragEvent e) {
// System.out.println("DropTarget.dragEnter: " + DnDCloseButtonTabbedPane.this);
if (isDragAcceptable(e)) {
e.acceptDrag(e.getDropAction());
} else {
e.rejectDrag();
} // if
}
public void dragExit(DropTargetEvent e) {
// System.out.println("DropTarget.dragExit: " + DnDCloseButtonTabbedPane.this);
m_isDrawRect = false;
}
public void dropActionChanged(DropTargetDragEvent e) {
}
public void dragOver(final DropTargetDragEvent e) {
TabTransferData data = getTabTransferData(e);
if (getTabPlacement() == JTabbedPane.TOP
|| getTabPlacement() == JTabbedPane.BOTTOM) {
initTargetLeftRightLine(getTargetTabIndex(e.getLocation()), data);
} else {
initTargetTopBottomLine(getTargetTabIndex(e.getLocation()), data);
} // if-else
repaint();
if (hasGhost()) {
s_glassPane.setPoint(buildGhostLocation(e.getLocation()));
s_glassPane.repaint();
}
}
#Override
public void drop(DropTargetDropEvent a_event) {
// System.out.println("DropTarget.drop: " + DnDTabbedPane.this);
if (isDropAcceptable(a_event)) {
convertTab(getTabTransferData(a_event),
getTargetTabIndex(a_event.getLocation()));
a_event.dropComplete(true);
} else {
a_event.dropComplete(false);
} // if-else
m_isDrawRect = false;
repaint();
}
public boolean isDragAcceptable(DropTargetDragEvent e) {
Transferable t = e.getTransferable();
if (t == null) {
return false;
} // if
DataFlavor[] flavor = e.getCurrentDataFlavors();
if (!t.isDataFlavorSupported(flavor[0])) {
return false;
} // if
TabTransferData data = getTabTransferData(e);
if (DnDCloseButtonTabbedPane.this == data.getTabbedPane()
&& data.getTabIndex() >= 0) {
return true;
} // if
if (DnDCloseButtonTabbedPane.this != data.getTabbedPane()) {
if (m_acceptor != null) {
return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());
} // if
} // if
boolean transferDataFlavorFound = false;
for (DataFlavor transferDataFlavor : t.getTransferDataFlavors()) {
if (FLAVOR.equals(transferDataFlavor)) {
transferDataFlavorFound = true;
break;
}
}
if (transferDataFlavorFound == false) {
return false;
}
return false;
}
public boolean isDropAcceptable(DropTargetDropEvent e) {
Transferable t = e.getTransferable();
if (t == null) {
return false;
} // if
DataFlavor[] flavor = e.getCurrentDataFlavors();
if (!t.isDataFlavorSupported(flavor[0])) {
return false;
} // if
TabTransferData data = getTabTransferData(e);
if (DnDCloseButtonTabbedPane.this == data.getTabbedPane()
&& data.getTabIndex() >= 0) {
return true;
} // if
if (DnDCloseButtonTabbedPane.this != data.getTabbedPane()) {
if (m_acceptor != null) {
return m_acceptor.isDropAcceptable(data.getTabbedPane(), data.getTabIndex());
} // if
} // if
return false;
}
}
private boolean m_hasGhost = true;
public void setPaintGhost(boolean flag) {
m_hasGhost = flag;
}
public boolean hasGhost() {
return m_hasGhost;
}
/**
* returns potential index for drop.
*
* #param a_point point given in the drop site component's coordinate
* #return returns potential index for drop.
*/
private int getTargetTabIndex(Point a_point) {
boolean isTopOrBottom = getTabPlacement() == JTabbedPane.TOP
|| getTabPlacement() == JTabbedPane.BOTTOM;
// if the pane is empty, the target index is always zero.
if (getTabCount() == 0) {
return 0;
} // if
for (int i = 0; i < getTabCount(); i++) {
Rectangle r = getBoundsAt(i);
if (isTopOrBottom) {
r.setRect(r.x - r.width / 2, r.y, r.width, r.height);
} else {
r.setRect(r.x, r.y - r.height / 2, r.width, r.height);
} // if-else
if (r.contains(a_point)) {
return i;
} // if
} // for
Rectangle r = getBoundsAt(getTabCount() - 1);
if (isTopOrBottom) {
int x = r.x + r.width / 2;
r.setRect(x, r.y, getWidth() - x, r.height);
} else {
int y = r.y + r.height / 2;
r.setRect(r.x, y, r.width, getHeight() - y);
} // if-else
return r.contains(a_point) ? getTabCount() : -1;
}
private void convertTab(TabTransferData a_data, int a_targetIndex) {
DnDCloseButtonTabbedPane source = a_data.getTabbedPane();
// System.out.println("this=source? " + (this == source));
int sourceIndex = a_data.getTabIndex();
if (sourceIndex < 0) {
return;
} // if
//Save the tab's component, title, and TabComponent.
Component cmp = source.getComponentAt(sourceIndex);
String str = source.getTitleAt(sourceIndex);
Component tcmp = source.getTabComponentAt(sourceIndex);
if (this != source) {
source.remove(sourceIndex);
if (a_targetIndex == getTabCount()) {
addTab(str, cmp);
setTabComponentAt(getTabCount() - 1, tcmp);
} else {
if (a_targetIndex < 0) {
a_targetIndex = 0;
} // if
insertTab(str, null, cmp, null, a_targetIndex);
setTabComponentAt(a_targetIndex, tcmp);
} // if
setSelectedComponent(cmp);
return;
} // if
if (a_targetIndex < 0 || sourceIndex == a_targetIndex) {
return;
} // if
if (a_targetIndex == getTabCount()) {
source.remove(sourceIndex);
addTab(str, cmp);
setTabComponentAt(getTabCount() - 1, tcmp);
setSelectedIndex(getTabCount() - 1);
} else if (sourceIndex > a_targetIndex) {
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex);
setTabComponentAt(a_targetIndex, tcmp);
setSelectedIndex(a_targetIndex);
} else {
source.remove(sourceIndex);
insertTab(str, null, cmp, null, a_targetIndex - 1);
setTabComponentAt(a_targetIndex - 1, tcmp);
setSelectedIndex(a_targetIndex - 1);
}
}
private void initTargetLeftRightLine(int next, TabTransferData a_data) {
if (next < 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} // if
if ((a_data.getTabbedPane() == this)
&& (a_data.getTabIndex() == next
|| next - a_data.getTabIndex() == 1)) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
} else if (getTabCount() == 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} else if (next == 0) {
Rectangle rect = getBoundsAt(0);
m_lineRect.setRect(-LINEWIDTH / 2, rect.y, LINEWIDTH, rect.height);
m_isDrawRect = true;
} else if (next == getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount() - 1);
m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,
LINEWIDTH, rect.height);
m_isDrawRect = true;
} else {
Rectangle rect = getBoundsAt(next - 1);
m_lineRect.setRect(rect.x + rect.width - LINEWIDTH / 2, rect.y,
LINEWIDTH, rect.height);
m_isDrawRect = true;
}
}
private void initTargetTopBottomLine(int next, TabTransferData a_data) {
if (next < 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} // if
if ((a_data.getTabbedPane() == this)
&& (a_data.getTabIndex() == next
|| next - a_data.getTabIndex() == 1)) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
} else if (getTabCount() == 0) {
m_lineRect.setRect(0, 0, 0, 0);
m_isDrawRect = false;
return;
} else if (next == getTabCount()) {
Rectangle rect = getBoundsAt(getTabCount() - 1);
m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,
rect.width, LINEWIDTH);
m_isDrawRect = true;
} else if (next == 0) {
Rectangle rect = getBoundsAt(0);
m_lineRect.setRect(rect.x, -LINEWIDTH / 2, rect.width, LINEWIDTH);
m_isDrawRect = true;
} else {
Rectangle rect = getBoundsAt(next - 1);
m_lineRect.setRect(rect.x, rect.y + rect.height - LINEWIDTH / 2,
rect.width, LINEWIDTH);
m_isDrawRect = true;
}
}
private void initGlassPane(Component c, Point tabPt, int a_tabIndex) {
//Point p = (Point) pt.clone();
getRootPane().setGlassPane(s_glassPane);
if (hasGhost()) {
Rectangle rect = getBoundsAt(a_tabIndex);
BufferedImage image = new BufferedImage(c.getWidth(),
c.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = image.getGraphics();
c.paint(g);
image = image.getSubimage(rect.x, rect.y, rect.width, rect.height);
s_glassPane.setImage(image);
} // if
s_glassPane.setPoint(buildGhostLocation(tabPt));
s_glassPane.setVisible(true);
}
private Rectangle getTabAreaBound() {
Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1);
return new Rectangle(0, 0, getWidth(), lastTab.y + lastTab.height);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (m_isDrawRect) {
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(m_lineColor);
g2.fill(m_lineRect);
} // if
}
public interface TabAcceptor {
boolean isDropAcceptable(DnDCloseButtonTabbedPane a_component, int a_index);
}
}
class GhostGlassPane extends JPanel {
public static final long serialVersionUID = 1L;
private final AlphaComposite m_composite;
private Point m_location = new Point(0, 0);
private BufferedImage m_draggingGhost = null;
public GhostGlassPane() {
setOpaque(false);
m_composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f);
}
public void setImage(BufferedImage draggingGhost) {
m_draggingGhost = draggingGhost;
}
public void setPoint(Point a_location) {
m_location.x = a_location.x;
m_location.y = a_location.y;
}
public int getGhostWidth() {
if (m_draggingGhost == null) {
return 0;
} // if
return m_draggingGhost.getWidth(this);
}
public int getGhostHeight() {
if (m_draggingGhost == null) {
return 0;
} // if
return m_draggingGhost.getHeight(this);
}
public void paintComponent(Graphics g) {
if (m_draggingGhost == null) {
return;
} // if
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(m_composite);
g2.drawImage(m_draggingGhost, (int) m_location.getX(), (int) m_location.getY(), null);
}
}
Ok, After 3 days fighting in 1 file. I Found a way. Still i extend my version of DnD from first link in question.
in DragDropEnd function (Overrides)
#Override
public void dragDropEnd(DragSourceDropEvent e) {
m_isDrawRect = false;
m_lineRect.setRect(0, 0, 0, 0);
// m_dragTabIndex = -1;
if (hasGhost()) {
s_glassPane.setVisible(false);
s_glassPane.setImage(null);
}
// if drop failed, create new JFrame with JTabbedPane included with public access
if(!e.getDropSuccess()){
// MenuLight class Extends JFrame and Included 1 component JTabbedPane called superPane
MenuLight m = new MenuLight();
m.setLocation(e.getLocation());
m.setVisible(true);
// after create Frame, transfer the tab to other jtabbedpane
((DnDCloseButtonTabbedPane) m.superPane).convertTab(getTabTransferData(e), getTargetTabIndex(e.getLocation()));
}
// if current JTabbedPane Tab is empty dispose it.
if(getTabCount() < 1){
// unfortunly i didnt want to close my Original menu, so check the class of parent of DnD is create from MenuLight and dispose it
if(parent.getClass().equals(MenuLight.class)){
((javax.swing.JFrame) parent).dispose();
}
}
}
Also it needed to find parent to close immediately if jtabbedpane is close i need to pass the parent form too. So i change the constructor into this.
public DnDCloseButtonTabbedPane(final Component _parent)
If you want to know MenuLight code, i included it too
public class MenuLight extends javax.swing.JFrame {
public MenuLight() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
superPane = new com.theflavare.minierp.helper.DnDCloseButtonTabbedPane(this);
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setPreferredSize(new java.awt.Dimension(640, 480));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(superPane, javax.swing.GroupLayout.DEFAULT_SIZE, 640, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(superPane, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
// Variables declaration - do not modify
public javax.swing.JTabbedPane superPane;
// End of variables declaration
}
And Viola, my mission success, make jtabbedpane drag out and automatic create JFrame. also Dispose the JFrame if current JTabbedpane are empty.
Thx. R