How to load background image into JPanel dynamically? - image

I have a swing gui application. I want to type into a image path and then click button to load the image into a jpanel. The problem is it won't be loaded, but if I add the extended jpanel which is able to load image when I instiate the jframe, image can be loaded normally. why is that?
code related:
package com.xdg.graphic;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImageLoader extends JPanel {
private String imgPath;
private BufferedImage image;
public ImageLoader(String imgPath) {
this.imgPath = imgPath;
try {
this.image=ImageIO.read(new File(imgPath));
} catch (IOException e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
}
#Override
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);
}
public Dimension getPreferredSize() {
if (image == null) {
return new Dimension(100,100);
} else {
return new Dimension(image.getWidth(null), image.getHeight(null));
}
}
public String getImgPath() {
return imgPath;
}
public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}
}
invoker class:
package com.xdg.image;
import com.xdg.graphic.ImageLoader;
import sun.awt.windows.ThemeReader;
import java.awt.*;
public class FrmImgCropper extends javax.swing.JFrame {
private ImageLoader imageLoader;
/** Creates new form FrmImgCropper */
public FrmImgCropper() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
//GEN-BEGIN:initComponents
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel2 = new javax.swing.JPanel();
tfImagePath = new javax.swing.JTextField();
btnPreview = new javax.swing.JButton();
tfRatioW = new javax.swing.JTextField();
tfRatioH = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
btnLoad = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnPreview.setText("Preview");
jLabel1.setText(":");
btnLoad.setText("Load");
btnLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadActionPerformed(evt);
}
});
jLabel2.setText("Image Path:");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(jPanel2Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
jPanel2Layout
.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(tfRatioW, javax.swing.GroupLayout.PREFERRED_SIZE, 55,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tfRatioH, javax.swing.GroupLayout.PREFERRED_SIZE, 53,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 123,
Short.MAX_VALUE)
.addComponent(btnLoad, javax.swing.GroupLayout.PREFERRED_SIZE, 82,
javax.swing.GroupLayout.PREFERRED_SIZE).addGap(46, 46, 46)
.addComponent(btnPreview).addGap(276, 276, 276))
.addGroup(
jPanel2Layout.createSequentialGroup().addGap(66, 66, 66).addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tfImagePath, javax.swing.GroupLayout.DEFAULT_SIZE, 593, Short.MAX_VALUE)
.addGap(29, 29, 29)));
jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
jPanel2Layout
.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addGroup(
jPanel2Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(tfImagePath, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(
jPanel2Layout
.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(tfRatioW, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tfRatioH, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnPreview).addComponent(btnLoad)).addGap(20, 20, 20)));
getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH);
pack();
}// </editor-fold>
//GEN-END:initComponents
private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {
if (imageLoader == null) {
imageLoader = new ImageLoader(tfImagePath.getText());
imageLoader.setBackground(Color.green);
getContentPane().add(imageLoader, BorderLayout.CENTER);
getContentPane().repaint();
this.repaint();//image does not show up this way dnamically
} else {
imageLoader.setImgPath(tfImagePath.getText());
imageLoader.repaint();
}
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
FrmImgCropper cropper = new FrmImgCropper();
cropper.getContentPane().add(new ImageLoader("i:\\temp4\\car.jpg")); //if I add the image loader here directly,image shows up
cropper.setSize(800, 900);
cropper.setVisible(true);
}
});
}
//GEN-BEGIN:variables
// Variables declaration - do not modify
private javax.swing.JButton btnLoad;
private javax.swing.JButton btnPreview;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel2;
private javax.swing.JTextField tfImagePath;
private javax.swing.JTextField tfRatioH;
private javax.swing.JTextField tfRatioW;
// End of variables declaration//GEN-END:variables
}
any ideas? I've been working on it two hours.

To update your panel you should call revalidate() method on panel's parent, not repaint() on the new panel since you change the content itself (the panel) but the image. In your case its content pane, which content should be validated.
But its still not the best way to update the image inside the panel if you ask me...
You can try this simple example (its much more simple and works perfectly):
private static BufferedImage image = null;
public static void main ( String[] args )
{
final JFrame imageFrame = new JFrame ();
imageFrame.setLayout ( new BorderLayout () );
final JPanel panel = new JPanel ()
{
protected void paintComponent ( Graphics g )
{
super.paintComponent ( g );
if ( image != null )
{
g.drawImage ( image, getWidth () / 2 - image.getWidth () / 2,
getHeight () / 2 - image.getHeight () / 2, this );
}
}
};
imageFrame.add ( panel, BorderLayout.CENTER );
imageFrame.add ( new JButton ( "Load image" )
{
{
addActionListener ( new ActionListener ()
{
public void actionPerformed ( ActionEvent e )
{
JFileChooser fc = new JFileChooser ();
fc.setDialogType ( JFileChooser.OPEN_DIALOG );
if ( fc.showOpenDialog ( imageFrame ) == JFileChooser.APPROVE_OPTION )
{
try
{
image = ImageIO.read ( fc.getSelectedFile () );
panel.repaint ();
}
catch ( IOException e1 )
{
//
}
}
}
} );
}
}, BorderLayout.SOUTH );
imageFrame.setSize ( 500, 500 );
imageFrame.setLocationRelativeTo ( null );
imageFrame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
imageFrame.setVisible ( true );
}
The only actual thing you need to do if you change the image inside panel - repaint the affected panel rect (or the whole panel if you don't like to get deep into the way graphics in Swing works).
As you can see i didn't even touch the panel itself - just changed the image source.

Related

Why are my validations not working from input file?

Full respect for your talents, please ignore how awful my code is. I am no natural and appreciate many of you will find my coding offensive!
I am wanting to create a GUI that 1 -chooses a text file, 2- displays the text to text panel and 3- validates the code ( i have a valid and invalid text file to demonstrate the validations work).
I can get points 1 and 2 to work but none of my validations are erroring when i select an invalid text file.
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.Image;
public class MainClass extends JFrame implements ActionListener {
#SuppressWarnings("deprecation")
public static void main(String[] args) {
// Creates new Window Frame with title and sets app to close on clicking cross
JFrame frame = new JFrame("SE2 - Graphics Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Creates JFrame as top level container in hierarchy
Container toplevelContainer = frame.getContentPane();
// Sets Grid Layout
GridLayout layout = new GridLayout(1, 0);
frame.setLayout(layout);
// Splits Panel into 2 halves and sets parameters for text panel and area
String str = "This is the area your imported text will be displayed";
JTextArea TextPanel = new JTextArea(str);
TextPanel.setBackground(Color.YELLOW);
TextPanel.setEditable(false);
TextPanel.setLineWrap(true);
TextPanel.setWrapStyleWord(true);
frame.add(TextPanel);
// calls graphicspanel class
GraphicsPanel grp = new GraphicsPanel();
toplevelContainer.add(grp);
grp.drawLine(Color.BLACK, 100, 100, 200, 100);
grp.drawLine(Color.BLACK, 200, 100, 200, 200);
grp.drawLine(Color.BLACK, 200, 200, 100, 200);
grp.drawLine(Color.BLACK, 100, 200, 100, 100);
// adds graphic panel to frame
frame.pack();
frame.setVisible(true);
// Creates new menubar within frame
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
// Creates new menu with new jmenuitems for File (load,save,exit) with shortcuts
JMenu file = new JMenu("File");
menubar.add(file);
JMenuItem load = new JMenuItem("Load");
load.setIcon(new ImageIcon("Images/Looad.png"));
load.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, KeyEvent.SHIFT_MASK));
file.add(load);
// enables user to browse and choose files to load from filepath
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
String filename = f.getAbsolutePath();
try
{
// reads file and displays in text panel
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
TextPanel.read(br, null);
br.close();
TextPanel.requestFocus();
File Fileobject = new File(filename);
#SuppressWarnings("resource")
Scanner fileReader = new Scanner(Fileobject);
fileReader = new Scanner(Fileobject);
while (fileReader.hasNext())
{
String line = fileReader.nextLine();
String[] splitArray = line.split(" ");
String command = splitArray[0];
if (command.contains ("MOVE"))
{
String MOVE = splitArray[0];
String x1 = splitArray[1];
String y1 = splitArray[2];
if (isNumeric(MOVE))
{
JOptionPane.showMessageDialog(null, "Command cannot be a number");
}
if(isLetter(x1))
{
JOptionPane.showMessageDialog(null, "Must be integer value");
}
if(isLetter(y1))
{
JOptionPane.showMessageDialog(null, "Must be integer value");
}
else if (command.contains("LINE"))
{
String LINE = splitArray[0];
String x2 = splitArray[1];
String y2 = splitArray[2];
if (isNumeric(LINE))
{
JOptionPane.showMessageDialog(null, "Command cannot be a number");
}
if(isLetter(x2))
{
JOptionPane.showMessageDialog(null, "Must be integer value");
}
if(isLetter(y2))
{
JOptionPane.showMessageDialog(null, "Must be integer value");
}
else if(command.contains("CIRCLE"))
{
String CIRCLE =splitArray[0];
int r = Integer.parseInt(splitArray[1]);
if(r < 0)
{
JOptionPane.showMessageDialog(null, "Must be positive number");
}
JOptionPane.showMessageDialog(null, "Must be integer value");
}
else if (command.contains("SOLID_CIRCLE"))
{
String SOLID_CIRCLE = splitArray[0];
try {
int r = Integer.parseInt(splitArray[1]);
if(r<0)
{
JOptionPane.showMessageDialog(null, "Must be positive number");
}
}
catch(NumberFormatException e) {
}
JOptionPane.showMessageDialog(null, "Must be integer value");
}
else if (command.contains("CLEAR"))
{
JOptionPane.showMessageDialog(null, "Commands have been cleared");
}
else if (command.contains("COLOUR"))
{
String Colour = splitArray[0];
int red = Integer.parseInt(splitArray[1]);
int green = Integer.parseInt(splitArray[2]);
int blue = Integer.parseInt(splitArray[3]);
if(red>255)
if(red<0)
if (green>255)
if(green<0)
if(blue>255)
if(blue<0)
{
JOptionPane.showMessageDialog(null, "Colour values must range between 0 and 255");
}
else if (command.contains("TEXT"))
{
String text = null;
if(isNumeric(text))
{
JOptionPane.showMessageDialog(null, "Text must not contain numbers");
}
if (!contains(""))
{
JOptionPane.showMessageDialog(null, "Text must contain double quotation marks");
}
}
}
}
}
}}
//confirm checks are complete for user
catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error Check Complete");
}
}
private boolean contains(String string) {
// TODO Auto-generated method stub
return false;
}
private boolean isLetter(String string) {
// TODO Auto-generated method stub
return false;
}
private boolean isNumeric(String command) {
// TODO Auto-generated method stub
return false;
}
});
// adds image icon and shortcut keys to JMenuItems
JMenuItem save = new JMenuItem("Save");
save.setIcon(new ImageIcon("Images/Saveas.png"));
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.SHIFT_MASK));
// Attempt at requirement 4 to add functionality to save JMENUITEM
// save.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent ae) {
// JFileChooser fc = new JFileChooser();
// fc.showSaveDialog(this);
// encoder.encode(image);
// byte[] jpgData = bos.toByteArray();
// FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg");
// fos.write(jpgData);
// fos.close();
file.add(save);
JMenuItem exit = new JMenuItem("Exit");
exit.setIcon(new ImageIcon("Images/Exiit.png"));
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, KeyEvent.SHIFT_MASK));
file.add(exit);
JMenu help = new JMenu("Help");
menubar.add(help);
JMenuItem about = new JMenuItem("About");
about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.SHIFT_MASK));
help.add(about);
// Adds Action listener to display dialog box with app description
about.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(about,
"This Application allows you to import, save and display graphical content from a file containing a set of instructions.",
"About", JOptionPane.INFORMATION_MESSAGE);
}
});
frame.setVisible(true);
class exitaction implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
exit.addActionListener(new exitaction());
}
protected static int isEmpty() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}

getting source scene from menuItem

I found related questions on the side, but no without using FXML, MenuItem doesn't have a super class that I can cast down to get the scene. I use the below approach when I found the same problem with a button instance.
(Scene) ((Node) event.getSource()).getScene();
I any ideas on how to solve this issue will be most appreciated.
Thanks In advance
here is the window's view
/**
* #author Jose Gonzalez
*
*/
public class Transaction extends TempletePattern{
private ImageView viewImage;
private Button button;
private TransactionController controller;
private TableView<Saving> table;
private TableColumn dateColum;
private TableColumn descriptionColum;
private TableColumn amountColum;
private TableColumn valanceColum;
/**
*
* #param controller
*/
public Transaction(TransactionController controller)
{
this.controller = controller;
}
/**
* main method all private methods in the class and set them up on the borderpane
* #return pane fully setup to be mount on the scene
*/
public BorderPane setScreen()
{
BorderPane trans = new BorderPane();
trans.setStyle("-fx-background: #FFFFFF;");
VBox topBox = new VBox ();
topBox.getChildren().addAll( setMenu(),setTop() );
trans.setTop(topBox );
trans.setBottom(processUpdate(process) );
trans.setCenter(setCenter() );
return trans;
}
/**
*
* #return vbox holding all note pertaining to the center of the borderpane
*/
private VBox setCenter()
{
VBox center = new VBox();
center.setPadding(new Insets(30, 20, 20, 20) );
table = new TableView<>();
table.setEditable(true);
dateColum = new TableColumn("Date");
dateColum.setCellValueFactory( new PropertyValueFactory<>("firstName"));
dateColum.prefWidthProperty().bind(table.widthProperty().divide(4));
dateColum.setResizable(false);
descriptionColum = new TableColumn("Description");
descriptionColum.prefWidthProperty().bind(table.widthProperty().divide(4));
descriptionColum.setResizable(false);
descriptionColum.setCellValueFactory(new PropertyValueFactory<>("lastName") );
amountColum = new TableColumn("Amount");
amountColum.prefWidthProperty().bind(table.widthProperty().divide(4));
amountColum.setResizable(false);
amountColum.setCellValueFactory( new PropertyValueFactory<>("transaction") );
valanceColum = new TableColumn("Availble Valance");
valanceColum.prefWidthProperty().bind(table.widthProperty().divide(4));
valanceColum.setResizable(false);
valanceColum.setCellValueFactory( new PropertyValueFactory<>("valance"));
table.getColumns().addAll(dateColum, descriptionColum, amountColum,valanceColum );
mockInfo();
center.getChildren().add(table);
return center;
}
/**
*
* #return the screen's menu fully set up
*/
private MenuBar setMenu()
{
MenuBar menubar = new MenuBar();
final Menu UserMenu = new Menu("User");
UserMenu.setId("user");
UserMenu.setOnAction(controller);
MenuItem itemLog = new MenuItem("log out");
itemLog.setId("logout");
itemLog.setOnAction(controller);
MenuItem itemAcount = new MenuItem("new acount");
itemAcount.setId("newAccount");
UserMenu.getItems().addAll(itemLog, itemAcount);
final Menu acctMenu = new Menu("Accounts");
MenuItem itemsavis = new MenuItem("Savings");
MenuItem itemCredit = new MenuItem("Credit");
MenuItem itemChecking = new MenuItem("Checking");
acctMenu.getItems().addAll(itemsavis, itemCredit, itemChecking);
final Menu aboutMenu = new Menu("about");
MenuItem itemHelp = new MenuItem("Help");
aboutMenu.getItems().addAll(itemHelp);
menubar.getMenus().addAll(UserMenu, acctMenu, aboutMenu);
return menubar;
}
/**
* #param receive constumer info from model through controller and set it on table.
*/
public void tableDataSetter(ObservableList<Saving> costumerInfo)
{
table.setItems(costumerInfo);
}
/**
* insert mock data to be displayed as a place holder
*/
private void mockInfo()
{
ObservableList<Saving> data =
FXCollections.observableArrayList(
new Saving("11/10/16", "Deposit", 123, "123" ),
new Saving("11/11/16", "Withdraw", 5, "123" ),
new Saving("11/12/16", "Deposit", 24, "123" ),
new Saving("11/13/16", "Withdraw", 62, "123" ),
new Saving("11/14/16", "Deposit", 134, "123" ),
new Saving("11/15/16", "Deposit", 134, "123" ),
new Saving("11/10/16", "Withdraw", 123, "123" ),
new Saving("11/11/16", "Deposit", 5, "123" ),
new Saving("11/12/16", "Withdraw", 24, "123" ),
new Saving("11/13/16", "Deposit", 62, "123" ),
new Saving("11/14/16", "Withdraw", 134, "123" ),
new Saving("11/15/16", "Deposit", 134, "123" )
);
table.setItems( data );
}
}
and here is the controller. ps I just started working on it.
public class TransactionController implements EventHandler{
//private LoginModel model ;
private Transaction view;
public TransactionController()
{
// model = new LoginModel();
view = new Transaction(this);
}
#Override
public void handle(Event event) {
if( ( event.getSource() instanceof MenuItem))
{
System.out.println( "afe " + (((Object)event.getTarget())) );
if( ( (MenuItem) (event.getSource()) ).getId().equals("logout") )
{
System.err.println("from inside logout");
/// this.goTologInt(event);
}else if( ( (MenuItem) (event.getSource()) ).getId().equals("newAccount") )
{
// this.goToNewAct(event);
}
}
}
private void goToNewAct(Event event)
{
Scene scene = (Scene) ( (Control) event.getSource()).getScene();
// Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
NewCustomerView newAcct = new NewCustomerView();
scene.setRoot( newAcct.newCustomerScreen());
}
private void goTologInt(Event event)
{
Scene scene = (Scene) ((Node)event.getSource()).getScene() ;
//Scene scene = (Scene) ((Control) event.getSource()).getScene();
// Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
LoginView newAcct = new LoginView( new LoginController());
scene.setRoot( newAcct.loginScreen());
}
}
You could go up through the menu hierarchy until you reach a menu with a popup and get the owner window of this popup, which is the window the context menu was opened from.
#Override
public void start(Stage primaryStage) {
MenuItem menuItem = new MenuItem("Something");
Menu menuInner = new Menu("menu", null, menuItem);
Menu menuOuter = new Menu("menu", null, menuInner);
MenuBar menuBar = new MenuBar(menuOuter);
StackPane root = new StackPane();
root.setAlignment(Pos.TOP_LEFT);
root.getChildren().add(menuBar);
Scene scene = new Scene(root);
menuItem.setOnAction(evt -> {
MenuItem m = (MenuItem) evt.getSource();
while (m.getParentPopup() == null) {
m = m.getParentMenu();
}
Scene s = m.getParentPopup().getOwnerWindow().getScene();
System.out.println(s == scene);
});
primaryStage.setScene(scene);
primaryStage.show();
}
In general I'd consider it a better idea though to simply make the information about the scene in question available to the EventHandler of the MenuItem:
final Scene scene = ...
menuItem.setOnAction(evt -> {
// do something with scene
});
The alternative to a (effectively) final local variable would be using a field...

how can i make the unity gui window dragable

i am trying to make my window dragable
i'm currently making a multiplayer game and the status to be shown has this window
public bool finishSession = false;
public bool showHelp = false;
private ArrayList messages = new ArrayList();
private string currentTime = "";
private string newMessage = "";
private Vector2 windowScrollPosition;
private SmartFox smartFox;
private GUIStyle windowStyle;
private GUIStyle userEventStyle;
private GUIStyle systemStyle;
public Rect rctWindow;
public float windowPanelPosX;
public float windowPanelPosY;
public float windowPanelWidth;
public float windowPanelHeight;
public StatusWindow() {
smartFox = SmartFoxConnection.Connection;
}
public void AddSystemMessage(string message) {
messages.Add(new StatusMessage(StatusMessage.StatusType.SYSTEM, message));
windowScrollPosition.y = 100000;
}
public void AddStatusMessage(string message) {
messages.Add(new StatusMessage(StatusMessage.StatusType.STATUS, message));
windowScrollPosition.y = 100000;
}
public void AddTimeMessage(string message) {
//messages.Add(new StatusMessage(StatusMessage.StatusType.TIME, message));
//windowScrollPosition.y = 100000;
currentTime = message;
}
public void Draw(float panelPosX, float panelPosY, float panelWidth, float panelHeight) {
windowPanelPosX = panelPosX;
windowPanelPosY = panelPosY;
windowPanelWidth = panelWidth;
windowPanelHeight = panelHeight;
// Status history panel
rctWindow = new Rect(windowPanelPosX, windowPanelPosY, windowPanelWidth, windowPanelHeight);
rctWindow = GUI.Window (1, rctWindow, DoMyWindow, "Interreality Portal Status", GUI.skin.GetStyle("window"));
GUI.DragWindow();
}
void DoMyWindow(int windowID)
{
windowStyle = GUI.skin.GetStyle("windowStyle");
systemStyle = GUI.skin.GetStyle("systemStyle");
userEventStyle = GUI.skin.GetStyle("userEventStyle");
//Cuadro blanco
GUILayout.BeginArea (new Rect (10, 25, windowPanelWidth - 20, windowPanelHeight - 70), GUI.skin.GetStyle ("whiteBox"));
GUILayout.BeginVertical ();
//General information area
if (smartFox != null && smartFox.LastJoinedRoom != null) {
GUILayout.Label ("Current room: " + smartFox.LastJoinedRoom.Name);
//if (currentGameState == GameState.RUNNING ) {
//GUILayout.Label(trisGameInstance.GetGameStatus()); //ACPR
//}
}
GUILayout.Label ("Activity: 1 - Construct");
GUILayout.Label ("Elapsed time: " + currentTime);
//Message area
windowScrollPosition = GUILayout.BeginScrollView (windowScrollPosition);
foreach (StatusMessage message in messages) {
DrawStatusMessage (message);
}
GUILayout.EndScrollView ();
//Cierra cuadro blanco
GUILayout.EndVertical ();
GUILayout.EndArea ();
//Logout area
GUILayout.BeginArea (new Rect (windowPanelWidth / 2, windowPanelHeight - 70 + 30, windowPanelWidth / 2 + 10, 30));//, GUI.skin.GetStyle("whiteBox"));
GUILayout.BeginHorizontal ();
if (GUILayout.Button ("Help", GUI.skin.GetStyle ("greenBtn"))) {
showHelp = true;
}
GUILayout.Space (10);
if (GUILayout.Button ("End Session", GUI.skin.GetStyle ("redBtn"))) {
finishSession = true;
}
GUILayout.EndHorizontal ();
GUILayout.EndArea ();
GUI.DragWindow();
}
private void DrawStatusMessage(StatusMessage message) {
GUILayout.BeginHorizontal();
GUILayout.Space(5);
switch (message.GetStatusType()) {
case StatusMessage.StatusType.SYSTEM:
GUILayout.Label(message.GetMessage(), systemStyle);
break;
case StatusMessage.StatusType.STATUS:
GUILayout.Label(message.GetMessage(), windowStyle);
break;
case StatusMessage.StatusType.TIME:
GUILayout.Label(message.GetMessage(), userEventStyle);
break;
default:
// Ignore and dont print anything
break;
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(1);
GUI.DragWindow();
}
class StatusMessage {
public enum StatusType {
IGNORE = 0,
SYSTEM,
STATUS,
TIME,
};
private StatusType type;
private string message;
public StatusMessage() {
type = StatusType.IGNORE;
message = "";
}
public StatusMessage(StatusType type, string message) {
this.type = type;
this.message = message;
}
public StatusType GetStatusType() {
return type;
}
public string GetMessage() {
return message;
}
}
}
but when i'mm trying to drag the window it doesn't drag it
i tried a simpler class with jnothing that works fine but when i call this window it doesn't drag
StatusWindow statusWindow = null;
void Start(){
statusWindow = new StatusWindow();
}
public Rect windowRect = new Rect(20, 20, 120, 50);
void OnGUI() {
windowRect = GUI.Window(0, windowRect, DoMyWindow, "My Window");
statusWindow.Draw (100, 100, 100, 100);
}
void DoMyWindow(int windowID) {
GUI.Button(new Rect(10, 20, 100, 20), "Can't drag me");
GUI.DragWindow();
}
If anyone who knows much about Unity GUI can help that would be great

viewpagerindicator and different layouts

i referred this code for viewpagerindicator from http://www.zylinc.com/blog-reader/items/viewpager-page-indicator.html .I want to display different views on different pages.Right now i m able to display list items on every page(3 pages) but i want to display lets say textview on second and third pages.i made some changes and created title using array here is the snippet for that
#Override
public String getTitle(int pos){
Log.i("FragmentList", "current page position is : " +mViewPager.getCurrentItem());
switch (pos) {
case 0:return titles[0];
case 1:return titles[1];
case 2:return titles[2];
default:return titles[0];
}
// pageListener = new DetailOnPageChange();
// mViewPager.setOnPageChangeListener(pageListener);
}
so when i change the page i also want to change the layouts i was thinking if i could get current position of the page i could put them in switch case and implement layout... but invain as mViewpager.getcurrentitem behaves properly in this function can some1 help me who should i implement that here is my code viewpagerindicator activty
package com.zylinc.view;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.zip.Inflater;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ViewPagerIndicatorActivity extends FragmentActivity
{
DetailOnPageChange pageListener;
PagerAdapter mPagerAdapter;
static ViewPager mViewPager;
ViewPagerIndicator mIndicator;
static TextView stv;
static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
static SimpleDateFormat readableDateFormat = new SimpleDateFormat("yyyy - MM/dd");
public int numberofPages = 3;
Inflater inflater;
public static final String[] titles = new String[]{"First Page","Second Page","Third Page"};
public static int pos;
public int currentPageIs;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create our custom adapter to supply pages to the viewpager.
mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setAdapter(mPagerAdapter);
// Start at a custom position
mViewPager.setCurrentItem(0);
// Find the indicator from the layout
mIndicator = (ViewPagerIndicator)findViewById(R.id.indicator);
// Set the indicator as the pageChangeListener
mViewPager.setOnPageChangeListener(mIndicator);
// Initialize the indicator. We need some information here:
// * What page do we start on.
// * How many pages are there in total
// * A callback to get page titles
Log.i("number of counts are ", "pages are"+mPagerAdapter.getCount());
mIndicator.init(0, mPagerAdapter.getCount(), mPagerAdapter);
Resources res = getResources();
Drawable prev = res.getDrawable(R.drawable.indicator_prev_arrow);
Drawable next = res.getDrawable(R.drawable.indicator_next_arrow);
mIndicator.setFocusedTextColor(new int[]{255, 0, 0});
// Set images for previous and next arrows.
mIndicator.setArrows(prev, next);
mIndicator.setOnClickListener(new OnIndicatorClickListener());
}
class OnIndicatorClickListener implements ViewPagerIndicator.OnClickListener{
#Override
public void onCurrentClicked(View v) {
Toast.makeText(ViewPagerIndicatorActivity.this, "Hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onNextClicked(View v) {
mViewPager.setCurrentItem(Math.min(mPagerAdapter.getCount() - 1, mIndicator.getCurrentPosition() + 1));
}
#Override
public void onPreviousClicked(View v) {
mViewPager.setCurrentItem(Math.max(0, mIndicator.getCurrentPosition() - 1));
}
}
class PagerAdapter extends FragmentPagerAdapter implements ViewPagerIndicator.PageInfoProvider
{
ArrayList<Fragment> fragments = new ArrayList<Fragment>();
//ArrayList<String> showTitles = new ArrayList<String>();
//String myPos = titles[pos];
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, pos - getCount() / 2);
return ItemFragment.newInstance(cal.getTime());
//return ItemFragment.newInstance(titles[pos]);
}
#Override
public String getTitle(int pos){
Log.i("FragmentList", "current page position is : " +mViewPager.getCurrentItem());
switch (pos) {
case 0:return titles[0];
case 1:return titles[1];
case 2:return titles[2];
default:return titles[0];
}
// pageListener = new DetailOnPageChange();
// mViewPager.setOnPageChangeListener(pageListener);
}
#Override
public int getCount() {
return numberofPages;
}
}
public class DetailOnPageChange extends ViewPager.SimpleOnPageChangeListener{
#Override
public void onPageSelected(int position) {
Log.i("FragmentList", "************* position is : " +currentPageIs);
currentPageIs = position;
}
public int getCurrentPage(){
return currentPageIs;
}
}
public static class ItemFragment extends ListFragment
{
static Date date;
TextView tv;
static ItemFragment newInstance(Date date) {
ItemFragment f = new ItemFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putString("date", sdf.format(date));
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
this.date = sdf.parse(getArguments().getString("date"));
} catch (ParseException e) {
e.printStackTrace();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Log.i("FragmentList", "current page checker position is : " +titles[pos]);
View v = inflater.inflate(R.layout.date_fragment, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText(readableDateFormat.format(date));
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, list));
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Log.i("FragmentList", "Item clicked: " + id);
}
}
public static final String[] list = new String[]{"France", "London", "Sweden", "Denmark", "Germany", "Finland", "Thailand", "Taiwan", "USA", "Norway", "Lithuania", "Bosnia", "Russia", "Vietnam", "Australia"};
}
and here is adapter
package com.zylinc.view;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* An small bar indicating the title of the previous,
* current and next page to be shown in a ViewPager.
* Made to resemble the indicator in the Google+ application
* in function.
*
* #author Mark Gjøl # Zylinc
*/
public class ViewPagerIndicator extends RelativeLayout implements OnPageChangeListener {
private static final int PADDING = 5;
TextView mPrevious;
TextView mCurrent;
TextView mNext;
int mCurItem;
int mRestoreCurItem = -1;
LinearLayout mPreviousGroup;
LinearLayout mNextGroup;
int mArrowPadding;
int mSize;
ImageView mCurrentIndicator;
ImageView mPrevArrow;
ImageView mNextArrow;
int[] mFocusedTextColor;
int[] mUnfocusedTextColor;
OnClickListener mOnClickHandler;
public interface PageInfoProvider{
String getTitle(int pos);
}
public interface OnClickListener{
void onNextClicked(View v);
void onPreviousClicked(View v);
void onCurrentClicked(View v);
}
public void setOnClickListener(OnClickListener handler){
this.mOnClickHandler = handler;
mPreviousGroup.setOnClickListener(new OnPreviousClickedListener());
mCurrent.setOnClickListener(new OnCurrentClickedListener());
mNextGroup.setOnClickListener(new OnNextClickedListener());
}
public int getCurrentPosition(){
return mCurItem;
}
PageInfoProvider mPageInfoProvider;
public void setPageInfoProvider(PageInfoProvider pageInfoProvider){
this.mPageInfoProvider = pageInfoProvider;
}
public void setFocusedTextColor(int[] col){
System.arraycopy(col, 0, mFocusedTextColor, 0, 3);
updateColor(0);
}
public void setUnfocusedTextColor(int[] col){
System.arraycopy(col, 0, mUnfocusedTextColor, 0, 3);
mNext.setTextColor(Color.argb(255, col[0], col[1], col[2]));
mPrevious.setTextColor(Color.argb(255, col[0], col[1], col[2]));
updateColor(0);
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable state = super.onSaveInstanceState();
Bundle b = new Bundle();
b.putInt("current", this.mCurItem);
b.putParcelable("viewstate", state);
return b;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(((Bundle)state).getParcelable("viewstate"));
mCurItem = ((Bundle)state).getInt("current", mCurItem);
this.setText(mCurItem - 1);
this.updateArrows(mCurItem);
this.invalidate();
}
/**
* Initialization
*
* #param startPos The initially selected element in the ViewPager
* #param size Total amount of elements in the ViewPager
* #param pageInfoProvider Interface that returns page titles
*/
public void init(int startPos, int size, PageInfoProvider pageInfoProvider){
setPageInfoProvider(pageInfoProvider);
this.mSize = size;
setText(startPos - 1);
mCurItem = startPos;
}
public ViewPagerIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
addContent();
}
public ViewPagerIndicator(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
addContent();
}
public ViewPagerIndicator(Context context) {
super(context);
addContent();
}
/**
* Add drawables for arrows
*
* #param prev Left pointing arrow
* #param next Right pointing arrow
*/
public void setArrows(Drawable prev, Drawable next){
this.mPrevArrow = new ImageView(getContext());
this.mPrevArrow.setImageDrawable(prev);
this.mNextArrow = new ImageView(getContext());
this.mNextArrow.setImageDrawable(next);
LinearLayout.LayoutParams arrowLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
arrowLayoutParams.gravity = Gravity.CENTER;
mPreviousGroup.removeAllViews();
mPreviousGroup.addView(mPrevArrow, arrowLayoutParams);
mPreviousGroup.addView(mPrevious, arrowLayoutParams);
mPrevious.setPadding(PADDING, 0, 0, 0);
mNext.setPadding(0, 0, PADDING, 0);
mArrowPadding = PADDING + prev.getIntrinsicWidth();
mNextGroup.addView(mNextArrow, arrowLayoutParams);
updateArrows(mCurItem);
}
/**
* Create all views, build the layout
*/
private void addContent(){
mFocusedTextColor = new int[]{0, 0, 0};
mUnfocusedTextColor = new int[]{190, 190, 190};
// Text views
mPrevious = new TextView(getContext());
mCurrent = new TextView(getContext());
mNext = new TextView(getContext());
RelativeLayout.LayoutParams previousParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
previousParams.addRule(RelativeLayout.ALIGN_LEFT);
RelativeLayout.LayoutParams currentParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
currentParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
RelativeLayout.LayoutParams nextParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
nextParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
// Groups holding text and arrows
mPreviousGroup = new LinearLayout(getContext());
mPreviousGroup.setOrientation(LinearLayout.HORIZONTAL);
mNextGroup = new LinearLayout(getContext());
mNextGroup.setOrientation(LinearLayout.HORIZONTAL);
mPreviousGroup.addView(mPrevious, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mNextGroup.addView(mNext, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addView(mPreviousGroup, previousParams);
addView(mCurrent, currentParams);
addView(mNextGroup, nextParams);
mPrevious.setSingleLine();
mCurrent.setSingleLine();
mNext.setSingleLine();
mPrevious.setText("previous");
mCurrent.setText("current");
mNext.setText("next");
mPrevious.setClickable(false);
mNext.setClickable(false);
mCurrent.setClickable(true);
mPreviousGroup.setClickable(true);
mNextGroup.setClickable(true);
// Set colors
mNext.setTextColor(Color.argb(255, mUnfocusedTextColor[0], mUnfocusedTextColor[1], mUnfocusedTextColor[2]));
mPrevious.setTextColor(Color.argb(255, mUnfocusedTextColor[0], mUnfocusedTextColor[1], mUnfocusedTextColor[2]));
updateColor(0);
}
#Override
public void onPageScrollStateChanged(int state) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
positionOffsetPixels = adjustOffset(positionOffsetPixels);
position = updatePosition(position, positionOffsetPixels);
setText(position - 1);
updateColor(positionOffsetPixels);
updateArrows(position);
updatePositions(positionOffsetPixels);
mCurItem = position;
}
void updatePositions(int positionOffsetPixels){
int textWidth = mCurrent.getWidth() - mCurrent.getPaddingLeft() - mCurrent.getPaddingRight();
int maxOffset = this.getWidth() / 2 - textWidth / 2 - mArrowPadding;
if(positionOffsetPixels > 0){
maxOffset -= this.getPaddingLeft();
int offset = Math.min(positionOffsetPixels, maxOffset - 1);
mCurrent.setPadding(0, 0, 2 * offset, 0);
// Move previous text out of the way. Slightly buggy.
/*
int overlapLeft = mPreviousGroup.getRight() - mCurrent.getLeft() + mArrowPadding;
mPreviousGroup.setPadding(0, 0, Math.max(0, overlapLeft), 0);
mNextGroup.setPadding(0, 0, 0, 0);
*/
}else{
maxOffset -= this.getPaddingRight();
int offset = Math.max(positionOffsetPixels, -maxOffset);
mCurrent.setPadding(-2 * offset, 0, 0, 0);
// Move next text out of the way. Slightly buggy.
/*
int overlapRight = mCurrent.getRight() - mNextGroup.getLeft() + mArrowPadding;
mNextGroup.setPadding(Math.max(0, overlapRight), 0, 0, 0);
mPreviousGroup.setPadding(0, 0, 0, 0);
*/
}
}
/**
* Hide arrows if we can't scroll further
*
* #param position
*/
void updateArrows(int position){
if(mPrevArrow != null){
mPrevArrow.setVisibility(position == 0 ? View.INVISIBLE : View.VISIBLE);
mNextArrow.setVisibility(position == mSize - 1 ? View.INVISIBLE : View.VISIBLE);
}
}
/**
* Adjust position to be the view that is showing the most.
*
* #param givenPosition
* #param offset
* #return
*/
int updatePosition(int givenPosition, int offset){
int pos;
if(offset < 0){
pos = givenPosition + 1;
}else{
pos = givenPosition;
}
return pos;
}
/**
* Fade "currently showing" color depending on it's position
*
* #param offset
*/
void updateColor(int offset){
offset = Math.abs(offset);
// Initial condition: offset is always 0, this.getWidth is also 0! 0/0 = NaN
int width = this.getWidth();
float fraction = width == 0 ? 0 : offset / ((float)width / 4.0f);
fraction = Math.min(1, fraction);
int r = (int)(mUnfocusedTextColor[0] * fraction + mFocusedTextColor[0] * (1 - fraction));
int g = (int)(mUnfocusedTextColor[1] * fraction + mFocusedTextColor[1] * (1 - fraction));
int b = (int)(mUnfocusedTextColor[2] * fraction + mFocusedTextColor[2] * (1 - fraction));
mCurrent.setTextColor(Color.argb(255, r, g, b));
}
/**
* Update text depending on it's position
*
* #param prevPos
*/
void setText(int prevPos){
if(prevPos < 0){
mPrevious.setText("");
}else{
mPrevious.setText(mPageInfoProvider.getTitle(prevPos));
}
mCurrent.setText(mPageInfoProvider.getTitle(prevPos + 1));
if(prevPos + 2 == this.mSize){
mNext.setText("");
}else{
mNext.setText(mPageInfoProvider.getTitle(prevPos + 2));
}
}
// Original:
// 244, 245, 0, 1, 2
// New:
// -2, -1, 0, 1, 2
int adjustOffset(int positionOffsetPixels){
// Move offset half width
positionOffsetPixels += this.getWidth() / 2;
// Clamp to width
positionOffsetPixels %= this.getWidth();
// Center around zero
positionOffsetPixels -= this.getWidth() / 2;
return positionOffsetPixels;
}
#Override
public void onPageSelected(int position) {
// Reset padding when the page is finally selected (May not be necessary)
mCurrent.setPadding(0, 0, 0, 0);
}
class OnPreviousClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onPreviousClicked(ViewPagerIndicator.this);
}
}
}
class OnCurrentClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onCurrentClicked(ViewPagerIndicator.this);
}
}
}
class OnNextClickedListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
if(mOnClickHandler != null){
mOnClickHandler.onNextClicked(ViewPagerIndicator.this);
}
}
}
}
You may find this blog useful; Making ActionBarSherlock and ViewPagerIndicator play nice
You may also come across a bug mentioned here; Android - SupportMapFragment with GoogleMaps API 2.0 giving IllegalArgumentException
Good Luck..!!

blackberry: AbsoluteFieldManager dont show custom fields

I'm trying to make a menu with an absolute layout that contains custom items extending Field. This items show well in the HorizontalFieldManager for example, but with the AbsoluteFieldManager it just shows a blank screen.
This is my code so far:
/********************
* CustomField.java *
********************/
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Keypad;
public class CustomField extends Field {
Bitmap img;
String s1, s2;
Font font;
int textColorUnfocused, textColorFocused, bgColorUnfocused, bgColorFocused;
public CustomField(long style) {
super(style);
}
public CustomField(Bitmap img, String s1, String s2) {// , long style) {
// super(style);
this.img = img;
this.s1 = s1;
this.s2 = s2;
this.font = Font.getDefault();
textColorUnfocused = 0x000000;
textColorFocused = 0xffffff;
bgColorUnfocused = 0xffffff;
bgColorFocused = 0x3956F7;
}
protected void layout(int maxWidth, int maxHeight) {
Font font = getFont();
int width = img.getWidth() + 10;
int height = img.getHeight() + (font.getHeight() * 3);
setExtent(Math.min(width, maxWidth), Math.min(height, maxHeight));
}
protected void onFocus(int direction) {
super.onFocus(direction);
invalidate();
}
protected void onUnfocus() {
super.onUnfocus();
invalidate();
}
public boolean isFocusable() {
return true;
}
protected void paint(Graphics g) {
// Draw background
g.setColor(isFocus() ? bgColorFocused : bgColorUnfocused);
g.fillRect(0, 0, getWidth(), getHeight());
// draw image
g.drawBitmap(5, 5, img.getWidth(), img.getHeight(), img, 0, 0);
g.setColor(isFocus() ? textColorFocused : textColorUnfocused);
// draw text
g.drawText(s1, ((img.getWidth() + 10) / 2) - (font.getAdvance(s1) / 2),
img.getHeight() + font.getHeight());
g.drawText(s2, ((img.getWidth() + 10) / 2) - (font.getAdvance(s2) / 2),
img.getHeight() + (2 * font.getHeight()));
}
protected boolean keyChar(char character, int status, int time) {
if (character == Keypad.KEY_ENTER) {
fieldChangeNotify(0);
return true;
}
return super.keyChar(character, status, time);
}
public int getY() {
return img.getHeight() + (font.getHeight() * 3);
}
public int getX() {
return img.getWidth();
}
}
/**************
* MyApp.java *
**************/
import net.rim.device.api.ui.UiApplication;
public class MyApp extends UiApplication{
public static void main(String args[]){
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp()
{
// Push a screen onto the UI stack for rendering.
pushScreen(new MyScreen());
}
}
/*****************
* MyScreen.java *
*****************/
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.container.AbsoluteFieldManager;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
public class MyScreen extends MainScreen {
public MyScreen() {
AbsoluteFieldManager manager = new AbsoluteFieldManager();
Bitmap img = Bitmap.getBitmapResource("1.png");
CustomField cf1 = new CustomField(img, "an", "Item");
CustomField cf2 = new CustomField(img, "another", "Item");
manager.add(cf1, 10, 10);
manager.add(cf2, 150, 150);
//HorizontalFieldManager hfm = new HorizontalFieldManager(
// Manager.HORIZONTAL_SCROLL);
//hfm.add(cf1); hfm.add(cf2);
//add(hfm);
add(manager);
}
}
And the image (1.png) http://www7.pic-upload.de/14.05.11/rhr4jcfuy9f8.png
How can I get the absolute manager to show my custom field?
My guess is that maybe AbsoluteFieldManager is passing 0, 0 to the layout method of your custom field. So your logic in there is calling setExtent(0, 0).

Resources