Toolbar swing application - swing

I have to implement 4 functionalities on my GUI. Functionalities are exclusive. Each functionality can have several commands that the user can execute. All this must be represented with icons and buttons only in a toolbar. I'm searching example and ideas to create this kind of toolbar.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MultiToolBar {
private static void addButtons(Container c, int i, JButton[] b) {
int startAt = (i==0 ? 0 : i*3);
int endAt = startAt+3;
for (int ii = startAt; ii<endAt; ii++) {
c.add(b[ii]);
}
c.validate();
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
final JToolBar tb = new JToolBar();
final JButton[] buttons = new JButton[12];
for (int ii=0; ii<buttons.length; ii++) {
buttons[ii] = new JButton("Button " + (ii+1));
}
String[] functions = new String[4];
for (int ii=0; ii<functions.length; ii++) {
functions[ii] = "Function " + (ii+1);
}
final JComboBox cb = new JComboBox(functions);
tb.add(cb);
cb.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent lse) {
Component[] components = tb.getComponents();
for (Component component : components) {
if (!(component instanceof JComboBox)) {
tb.remove(component);
}
}
int index = cb.getSelectedIndex();
addButtons(tb, index, buttons);
}
});
cb.setSelectedIndex(3);
JOptionPane.showMessageDialog(null, tb);
}
});
}
}

Take a look at the class JToolBar, here is a good tutorial from Oracle.
Oracle - How to Use Toolbars

Related

Add custom wms layer to codename one Mapcontainer

I am building an android GPS app with Codename one. I use com.codename1.googlemaps.MapContainer to create a Google map;
In my app is use tabs to create different "pages".
Code:
cnt = new MapContainer();
t.addTab("Tab3", cnt);
And for my current location I use:
try {
Coord position = new Coord(lat,lng);
cnt.clearMapLayers();
cnt.setCameraPosition(position);
cnt.addMarker(EncodedImage.create("/maps-pin.png"), position, "Hi marker", "Optional long description", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// stuff todo...
}
});
} catch(IOException err) {
// since the image is iin the jar this is unlikely
err.printStackTrace();
}
I like to add a wms layer to the Google Maps. Is this possible? I can't find in codenameone a command addLayer. If yes, do you have a code snippet how to do this?
If it is not possiple, can I use openlayers in my codename one app? Can you give me a code snippet to do this?
Edit
I started to create an native file to "catch"the addtileoverlay from google maps api. The layer I want to use is a xyz layer, so I think I can use a urltileprovider from the googlemap api
I made the native code for the tileoverlay but the tileoverlay doesn't appear. Is it because i didn't get a link with the mapcontainer.
I am little bit stuck. I tried to build from scratch with the googmaps example but the mapcompnent is not anymore used.
package com.Bellproductions.TalkingGps;
import com.google.android.gms.maps.model.UrlTileProvider;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import com.google.android.gms.maps.model.TileOverlay;
import com.codename1.impl.android.AndroidNativeUtil;
import java.util.Locale;
import java.net.MalformedURLException;
public class SeamarksImpl {
private GoogleMap mapInstance;
private TileOverlay m;
TileProvider provider;
public boolean isSupported() {
return true;
}
public long addTilelayer (){
final String URL_FORMAT = "http://t1.openseamap.org/seamark/{z}/{x}/{y}.png";
AndroidNativeUtil.getActivity().runOnUiThread(new Runnable() {
public void run() {
provider = new UrlTileProvider(256, 256) {
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
try {
y = (1 << zoom) - y - 1;
return new URL(String.format(Locale.US, URL_FORMAT, zoom, x, y ));
} catch (MalformedURLException e) {
throw new RuntimeException();
}
}
TileOverlayOptions tileopt = new TileOverlayOptions().tileProvider(provider);
public void addlayer() {
m = mapInstance.addTileOverlay(tileopt);
}
};
}
});
long p = 1;
return p;}
}
My seamarks.java file has this code to bind with the native interface
import com.codename1.system.NativeInterface;
/**
*
* #author Hongerige Wolf
*/
public interface Seamarks extends NativeInterface {
public void addTilelayer ();
}
In the mainactivity java file i have the statements
public Seamarks seamark;
public void init(Object context) {
seamark = (Seamarks)NativeLookup.create(Seamarks.class);
}
public void start() {
seamark.addTilelayer();
}
Update
I created a new googlemaps.CN1lib. But the xyz layer is not showing on the googlemaps. I used native code tot use the Tileoverlay feature and tried to add tileoverlay in the same way as Markers.
In the InternalNativeMapsImpl file i changed
private void installListeners() {
/*
if (mapInstance == null) {
view = null;
System.out.println("Failed to get map instance, it seems google play services are not installed");
return;
}*/
view.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mapInstance = googleMap;
TileProvider tileProvider;
tileProvider = new UrlTileProvider(256, 256) {
String tileLayer= "http://t1.openseamap.org/seamark/";
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
// The moon tile coordinate system is reversed. This is not normal.
int reversedY = (1 << zoom) - y - 1;
//String s = String.format(Locale.US, tileLayer , zoom, x, y);
String s = tileLayer + "/" + zoom + "/" + x + "/" + reversedY + ".png";
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
mapInstance.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
public boolean onMarkerClick(Marker marker) {
Long val = listeners.get(marker);
if (val != null) {
MapContainer.fireMarkerEvent(InternalNativeMapsImpl.this.mapId, val.longValue());
return true;
}
return false;
}
});
mapInstance.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
public void onCameraChange(CameraPosition position) {
MapContainer.fireMapChangeEvent(InternalNativeMapsImpl.this.mapId, (int) position.zoom, position.target.latitude, position.target.longitude);
}
});
mapInstance.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng point) {
Point p = mapInstance.getProjection().toScreenLocation(point);
MapContainer.fireTapEventStatic(InternalNativeMapsImpl.this.mapId, p.x, p.y);
}
});
mapInstance.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
public void onMapLongClick(LatLng point) {
Point p = mapInstance.getProjection().toScreenLocation(point);
MapContainer.fireLongPressEventStatic(InternalNativeMapsImpl.this.mapId, p.x, p.y);
}
});
mapInstance.setMyLocationEnabled(showMyLocation);
mapInstance.getUiSettings().setRotateGesturesEnabled(rotateGestureEnabled);
}
});
}
Secondly i added a addTilexyz method also in the same way as addMarkers
public long addTilexyz(final String Turl) {
uniqueIdCounter++;
final long key = uniqueIdCounter;
AndroidNativeUtil.getActivity().runOnUiThread(new Runnable() {
public void run() {
TileProvider tileProvider;
tileProvider = new UrlTileProvider(256, 256) {
// Tileurl = "http://t1.openseamap.org/seamark/";
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
// The moon tile coordinate system is reversed. This is not normal.
int reversedY = (1 << zoom) - y - 1;
String s = String.format(Locale.US, Turl , zoom, x, reversedY);
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
}
});
return key;
}
In the InternalNativeMaps file i added te method
public long addTilexyz(String Turl);
And in the Mapcontainer file i added
public MapObject addTilexyz(String Turl) {
if(internalNative != null) {
MapObject o = new MapObject();
Long key = internalNative.addTilexyz(Turl);
o.mapKey = key;
markers.add(o);
return o;
} else {
}
MapObject o = new MapObject();
return o;
}
I am puzzeled what is wrong with the code. I wonder if the commands
Long key = internalNative.addTilexyz(Turl);
and
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
put the tileoverlay on the googlemap. Or is the tileurl wrong. http://t1.openseamap.org/seamark/z/x/y.png is correct.
We don't expose layers in the native maps at this time, you can fork the project and just add an API to support that to the native implementations.

"Cannot resolve symbol" in some of the javax.swing.Timer methods in IntelliJ IDEA

I have been searching for a couple hours now and can't seem to find an answer on this.
I import javax.swing.* so that i can use Timer in my program, but while Timer is imported and seem to be functioning, other methods that Timer has cannot be resolved by intellij and I get the following Errors :
Errors picture
enter image description here
Here is my code:
`
import java.util.Random;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.*;
public class Board
{
Random rn = new Random();
private SquareType[][] squares;
private int height;
private int width;
public Poly falling;
private int fallingX;
private int fallingY;
public Board(final int height, final int width) {
this.width = width;
this.height = height;
squares = new SquareType[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
squares[i][j] = SquareType.EMPTY;
}
}
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public SquareType whichSquareType(int height, int width) {
//Takes in two integers one for height and one for width and returns
// the SquareType of the particular cell
return squares[height][width];
}
public void randomizeBoard() {
SquareType[] myTypes = SquareType.values();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
squares[i][j] = myTypes[rn.nextInt(myTypes.length)];
}
}
}
public int getFallingX() {
return fallingX;
}
public int getFallingY() {
return fallingY;
}
public Poly getFalling() {
return falling;
}
final Action doOneStep = new AbstractAction()
{
public void actionPerformed(ActionEvent e) {
}
};
final Timer clockTimer = new Timer(500, doOneStep);
clockTimer.setCoalesce(true);
clockTimer.start();
}
`
Note you are calling Timer class methods at Board class declaration level, not from within a Board class method. Those are illegal Java statements and the actual reason of the error messages. You should encapsulate those calls in a new Board class method -let's say initTimer()- and call this method when needed.
On the other hand clockTimer variable declaration and initialization are ok.

how to ViewFlipper addView or removeView after autoStart set to true

For my app, I have lots of images(from url not from phone memory) required to be shown as slideshow. I am using ViewFlipper for this. I am getting this images from url and adding them in viewFlipper. Problem is when i add 5-6 images it works fine but for more than 5-6 it goes into OutOfMemory error.
I think, this can be done if we can somehow do something like this..
1. add some set of images to ViewFlipper
2. startFlipping, remove view after showing that image/view,
3. add more images.
Not sure if it can be done using viewFlipper or are there any other way ?
Sample Code of my AutoSlideShow:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ViewFlipper;
public class AutoSlideShow extends Activity {
ViewFlipper viewFlipper = null;
Button pauseButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_slide_show);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Intent intent = getIntent();
String[] allUrls = intent.getExtras().getStringArray("allImageUrls");
viewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
viewFlipper.setFlipInterval(2000);
viewFlipper.setAutoStart(true);
for (int i = 0; i < allUrls.length; i++) {
setFlipperImage(allUrls[i]);
}
pauseButton = (Button) findViewById(R.id.pauseButton);
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pauseButton.getText().equals("Resume")) {
viewFlipper.startFlipping();
pauseButton.setText("Pause");
} else {
viewFlipper.stopFlipping();
pauseButton.setText("Resume");
}
}
});
}
private void setFlipperImage(String url) {
ImageView image = new ImageView(getApplicationContext());
Bitmap bitmap = null;
try {
InputStream content = (InputStream) new URL(url).getContent();
bitmap = BitmapFactory.decodeStream(content);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
viewFlipper.addView(image);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auto_slide_show, menu);
return true;
}
}
private ViewFlipper mViewFlipper;
private GestureDetector mGestureDetector;
int i = 0;
int k = 0;
int l = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_slide_show);
mViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Intent intent = getIntent();
String[] allUrls = intent.getExtras().getStringArray("allImageUrls");
if (i == 0) {
for (int i = 0; i < 2; i++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(allUrls[i]);
mViewFlipper.addView(imageView);
k++;
}
i = 1;
}
mViewFlipper.getDisplayedChild();
// Add all the images to the ViewFlipper
CustomGestureDetector customGestureDetector = new CustomGestureDetector();
mGestureDetector = new GestureDetector(this, customGestureDetector);
mViewFlipper.setInAnimation(this, android.R.anim.fade_in);
mViewFlipper.setOutAnimation(this, android.R.anim.fade_out);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
class CustomGestureDetector extends GestureDetector.SimpleOnGestureListener {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// Swipe left (next)
if (e1.getX() > e2.getX()) {
mViewFlipper.setInAnimation(MainActivity.this, R.anim.left_in);
mViewFlipper.setOutAnimation(MainActivity.this, R.anim.left_out);
mViewFlipper.showNext();
if (mViewFlipper.getDisplayedChild() > 1) {
mViewFlipper.removeViewAt(l);
}
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(allUrls[k]);
mViewFlipper.addView(imageView);
k++;
Log.d("Count", "" + mViewFlipper.getChildCount());
}
// Swipe right (previous)
if (e1.getX() < e2.getX()) {
mViewFlipper.setInAnimation(MainActivity.this, R.anim.right_in);
mViewFlipper.setOutAnimation(MainActivity.this, R.anim.right_out);
mViewFlipper.showPrevious();
if (mViewFlipper.getDisplayedChild() > 1) {
mViewFlipper.removeViewAt(l);
}
ImageView imageView = new ImageView(MainActivity.this);
imageView.setImageResource(allUrls[k]);
mViewFlipper.addView(imageView);
k++;
}
return super.onFling(e1, e2, velocityX, velocityY);
}
}

How to create 12x8 swing button array

I wonder if there is a way to change to source code format automatically produced
by Net Beans IDE in GUI - applet applications. For example placement of the items in the source code are relational but what if I want them in absolute coordinates. I am asking this question because I need source code in that format so that I can easily change source code and can do some manual job. More specially, I want to create a Button Group of 12x8 array with no gap between them . But using IDE to do this takes long time and indeed, I couldn't even placed the buttons with no gap between them. Any help highly appreciated!
This is simple to put together manually. GUI builders usually harm more than they help.
Here's the test run:
And here's the code. I put the classes together in one file to make it easier to paste. The classes should be in separate files.
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ButtonArray implements Runnable {
#Override
public void run() {
JFrame frame = new JFrame("JButton Array Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ButtonPanel buttonPanel = new ButtonPanel();
frame.add(buttonPanel.getMainPanel());
frame.setLocationByPlatform(true);
// frame.setSize(new Dimension(800, 600));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new ButtonArray());
}
public class ButtonPanel {
private static final int WIDTH = 12;
private static final int HEIGHT = 8;
private JButton[][] buttonArray;
private JPanel mainPanel;
public ButtonPanel() {
buttonArray = new JButton[WIDTH][HEIGHT];
createPartControl();
}
private void createPartControl() {
mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(HEIGHT, WIDTH));
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
buttonArray[j][i] =
new JButton(createButtonText(j, i));
mainPanel.add(buttonArray[j][i]);
}
}
}
private String createButtonText(int j, int i) {
StringBuilder builder = new StringBuilder();
builder.append("(");
builder.append(i);
builder.append(", ");
builder.append(j);
builder.append(")");
return builder.toString();
}
public JPanel getMainPanel() {
return mainPanel;
}
}
}
You need to use some grid like layout for the panel (ex. FormLayout) configure it and simply add all buttons there.

I'm able to update the TableModel using setValueAt() but changes are not visible in the Table

I'm able to update the TableModel using setValueAt() but changes are not visible in the Table
below is the code:
import javax.swing.JFrame;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.Dimension;
import java.awt.GridLayout;
public class TableFTFEditDemo extends JPanel {
private boolean DEBUG = true;
JTable table;
MyTableModel tableModel=new MyTableModel();
public TableFTFEditDemo() {
super(new GridLayout(1,0));
table = new JTable(tableModel);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Set up stricter input validation for the integer column.
table.setDefaultEditor(Integer.class,
new IntegerEditor(0, 100));
//If we didn't want this editor to be used for other
//Integer columns, we'd do this:
//table.getColumnModel().getColumn(3).setCellEditor(
// new IntegerEditor(0, 100));
//Add the scroll pane to this panel.
add(scrollPane);
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames ;
private Object[][] data;
MyTableModel(){
columnNames=new String[] {"First Name","Last Name","Sport","# of Seaters","Vegetarian","blank"};
data=new Object[][] {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false),"sdf"},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true),"reytry"},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false),"wwttu"},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true),"yuiyio"},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false),"ertey"}
};
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}
data[row][col] = value;
this.fireTableCellUpdated(row,col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TableFTFEditDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TableFTFEditDemo newContentPane = new TableFTFEditDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
void runtable(){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
tableModel.setValueAt(new Integer(5),2,5);
((AbstractTableModel)table.getModel()).fireTableCellUpdated(2,5);
}
});
}
/** using this to call setValueAt from other classes*/
public void setValueAt1(Object value, int row, int col) {
table.setValueAt(new Integer(5),row,col);
((AbstractTableModel)table.getModel()).fireTableCellUpdated(row,col);
}
}
PS: the code is taken frm oracle' example..i just want to knw how to reflect the changes made in tablemodel in the table.
Your code works as expected, just you do not actually call setValueAt() on your model. Your runtable() method where you do is never invoked.
To verify, change createAndShowGUI() to return the newContentPane and use the following main:
static TableFTFEditDemo instance;
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
instance = createAndShowGUI();
}
});
Thread.sleep(5000);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
instance.tableModel.setValueAt(5, 2, 5);
}
});
}
After the programmed five second delay, the value in column 2 row five will change from "wwtu" into "5".