I'm looking to make about 10 textboxes for the user to type into then store that value as a variable. Is there anyway to make a textbox function with the parameters being the position?
Yes, that’s possible using the library controlP5.
import controlP5.*;
ControlP5 cp5;
String[] textfieldNames = {"tf1", "tf2", "tf3", "tf4", "tf5"};
void setup() {
size(700,400);
PFont font = createFont("arial",20);
cp5 = new ControlP5(this);
int y = 20;
int spacing = 60;
for(String name: textfieldNames){
cp5.addTextfield(name)
.setPosition(20,y)
.setSize(100,40)
.setFont(font)
.setFocus(true)
.setColor(color(255,0,0))
;
y += spacing;
}
textFont(font);
}
void draw() {
background(0);
}
void controlEvent(ControlEvent theEvent) {
if(theEvent.isAssignableFrom(Textfield.class)) {
println("controlEvent: accessing a string from controller '"
+theEvent.getName()+"': "
+theEvent.getStringValue()
);
}
}
If you're a proficient Java programmer, you may consider using the Swing Library, the primary Java GUI widget toolkit. However, you'd also find yourself messing around with the Processing core code. Don't do that.
The main rule when using Java code [in a Processing sketch]: you cannot use most of the AWT or
Swing (which is built on the AWT), because it will interfere with the
graphics model. If you want to add scroll bars and buttons to your
projects, you should make them using Processing code, or embed your
Processing applet inside another Swing or AWT application.
Even if they appear to work, such sketches will usually break when you
try to run on other operating systems or other versions of Java. – Processing FAQ
If you're not a Java programmer, stick with Processing libraries or make your own text field class.
The popular ControlP5 GUI library has built-in classes for text fields and text areas. As of yet, This version has been tested with processing 2.0b7 and it may not work with the latest 2.0 release.
You may also use the G4P library and its text area implementation.
If it's the first time you're using external libraries, open Processing and add contributed libraries by selecting "Add Library..." from the "Import Library..." submenu within the upper bar menu.
EDIT: I've never tried it, but Interfascia (alpha release) has a text field class too. The documentation seems easy to read and the code easy to use.
Related
I am porting my Android app to iOS and I am using Codename One for that.
In my app an EditText can contain icons mixed with text. It is accomplished with instructions like these:
MyImageSpan iconSpan=new MyImageSpan(activity, R.drawable.icon);
editText.getText().insert(caretPosition,CHAR);
editText.getText().setSpan(iconSpan,caretPosition,caretPosition+1,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
then in other parts, spans have to be detected, if present, and it is performed like this:
Editable editable = editText.getText();
for (int i = 0; i < editable.length(); i = next) {
// find the next span transition
next = editable.nextSpanTransition(i, editable.length(), MyImageSpan.class);
// get all spans in this range
MImageSpan[] tempSpans = editable.getSpans(i, next, MyImageSpan.class);
...
...
//In my app that becomes really complex
...
...
...
...
}
I tried to use this online tool:
http://fontello.com/
to manage icons like font glyphs, as it seems to be adviced by Codename One documentation.
In fact I do not understand if it is possible to have spans with different fonts in an TextField in Codename One, and I do not know if I could find and manage them inside the TextField.
But the most important thing is that the online tool to create fonts out of svg files did not work for me because some icons are reverted, others are broken or confused, others are tiny, depending on the saving format (eventually I saved in pure SVG format to avoid issues but it's the same).
What I am asking is how to handle the spans in the TextField in Codename One.
It has not to be the same "way" but the result has to be the same.
This won't work. Rich text edit is something that's just too different between platforms and isn't universally available. Since the edit component is implemented using native widgets it's very hard to consistently abstract something like this and effectively impossible.
However, web tools solved that problem already and include some cross platform rich edit tools that work. You can just use one of those tools and embed a BrowserComponent in your app. Then perform the rich editing within the browser component.
Back in the day we did it with CK editor, but this library is pretty out of date by now so I'm not sure how well it works. It should be relatively easy to create something like this though.
I have tons of jbuttons, jtextfields, jlabels, jmenus, gui items and it is extremely time consuming to set the background color and foreground color one at a time.
I want to be able to color the fonts(foreground) and backgrounds all the jmenus, jmenuitems,jtextfields,jbuttons, etc quickly/concisely in my project instead of having to set them one at a time.
Is there any technique to do this more concisely instead of doing it one at a time?
1) most eficient way would be to use Custom Look and Feel, part of them have got a nice Themes
2) set value to the UIDefault, Listing UIDefault Properties
EDIT:
best of all UIManager Defaults by #camickr
You can combine Swing with CSS or use a Swing Look & Feel in order to create a standard look for your components. The Java site says:
Before we get into a CSS implementation, let's consider the alternative: a custom look and feel. Swing Look and Feels (L&Fs) are sets of classes that implement the actual drawing of components at a very low level (think lines and bitmaps). They can be swapped out for new ones at runtime, often to implement the look of a native platform; i.e., the JDK for OSX has a set of classes that make Swing apps look like native Aqua apps, with candy buttons and blue tint. Custom L&Fs are powerful, but not trivial or quick to build. You will usually have to touch 20 or so classes and implement a whole bunch of special drawing code.
So CSS is easier to use. The same article goes on to give a tutorial about how to implement the CSS with Swing. They provide a nice walkthrough of creating the right rules and then going on to implement them in CSS. However, this is not simply "copy and paste" code.
If you'd just like to use a package (without having to code it yourself) the answers to the question Can I use CSS for Java Swing? suggest Flying Saucer and Jaxx.
They're all JComponents so you can make an ArrayList of everything:
//Adding everything to the ArrayList
ArrayList<JComponent> myComponents = new ArrayList<JComponents>();
JButton b1 = new JButton("Button 1");
myComponents.add(b1);
JMenuItem item = new JMenuItem("Menu Item 1");
myComponents.add(item);
//Coloring the foreground/background
for(JComponent j : myComponents) {
j.setForeground(new Color("BLUE"));
j.setBackground(new Color("RED"));
}
If you use a Look and Feel that honors the UI constants in javax.swing.UIManager then you can just set them. There are values for e.g. panel background. If not or if you can't control the look enough by this you can write you own UI delegate that draws a specific component (e.g. javax.swing.plaf.ButtonUI for JButtons). If even this is not enough you can write your own Look And Feel. If you just extend the Metal LnF it is not that hard, you would write own UI delegates and set properties, like above, but centralized.
I have decent knowledge in J2EE frameworks such as Spring,Hibernate and got inspired by the separation of concerns . I am a starter in desktop development in java. Things are going somewhat fuzzy in swing. In VB, Form design will be kept as a separate one, and our form will only contains event listeners. But when I am started in swing many stuffs are loading in a single class making things difficult. I am unable to find where I am wrong. Similar thing continues when I started for alternatives such as SWT.
Sample SWT code I got from internet
import java.awt.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import edu.umd.cs.piccolox.swt.PSWTCanvas;
import edu.umd.cs.piccolox.swt.PSWTPath;
import edu.umd.cs.piccolox.swt.PSWTText;
public final class SWTBasicExample {
/**
* Create and open a new shell on the specified display.
*
* #param display display
* #return a new shell on the specified display
*/
public static Shell open(final Display display) {
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
// create a new SWT canvas
final PSWTCanvas canvas = new PSWTCanvas(shell, 0);
// create some SWT nodes
// and add them as child nodes to the canvas' camera's first layer
PSWTPath rect = PSWTPath.createRectangle(25, 25, 50, 50);
rect.setPaint(Color.RED);
canvas.getLayer().addChild(rect);
rect = PSWTPath.createRectangle(300, 25, 100, 50);
rect.setPaint(Color.BLUE);
canvas.getLayer().addChild(rect);
PSWTPath circle = PSWTPath.createEllipse(100, 200, 50, 50);
circle.setPaint(Color.GREEN);
canvas.getLayer().addChild(circle);
circle = PSWTPath.createEllipse(400, 400, 75, 150);
circle.setPaint(Color.YELLOW);
canvas.getLayer().addChild(circle);
PSWTText text = new PSWTText("Hello World\nMultiline");
text.translate(350, 150);
text.setPenColor(Color.GRAY);
text.setBackgroundColor(Color.BLACK);
canvas.getLayer().addChild(text);
text = new PSWTText("Goodbye World");
text.translate(50, 400);
text.setPenColor(Color.MAGENTA);
canvas.getLayer().addChild(text);
shell.open();
return shell;
}
public static void main(final String[] args) {
final Display display = new Display();
final Shell shell = open(display);
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
Here everything is messing up so our business logic and the design are on single class. I studied that a method can have up to 10 lines to make it less complex and reusable. Is it applicable only to logic not desktop development.
Meanwhile, I heard Swing is an MVC framework. So, I want neat separation of logic, design and control. I want good engineering practices being followed in swing and swt to ease desktop development in java. Since I am using eclipse SWT will be preferable for me.
Thanks,
Spring (and other mentioned technologies/frameworks) have absolutely another purpose than GUI frameworks. You may not require same thing from two so different technologies. Desktop is not web, there aren't same rules as we speak.
If you want use MVC like patterns with SWT (especially for data binding) learn JFace.
As for Swing vs. SWT, I have used both (but mainly Swing). At least back when I was looking into SWT (~5 years ago) the documentation for SWT was very poor compared to Swing. Even though I liked many design aspects of SWT, and it is simpler than Swing, IMO, Swing is the one to learn because, IMO, it has far far better documentation, examples, etc. And it is used in many more places.
As for general design ideas, one technique, if your major JPanels (or whatever your Component is) are modal, is to have a Model / DataObject / BusinessObject associated with each JPanel. The JPanel will have methods named something like panelToModel() and modelToPanel(). The former creates (or updates) a model corresponding to what the user has changed, and the latter takes a model and updates the GUI to match. Now, personally, I hate modal anythings, but this is a fairly simple way to get started.
In Swing the components itself follow the MVC pattern - most of the time. They are based on models, the visual representation can be replaced easily. For a larger scope you have to implement this yourself. Some approaches for separation of concerns exist, like the usage of Actions. But it is in no way a ready to use application platform, it is a GUI toolkit. There exist projects for application frameworks, like JSR 296 - "Swing Application Framework". But this one doesn't get finalized for years. Another notable platform based on Swing is the Netbeans platform, but this is a level higher.
SWT components are not designed with MVC concepts. JFace brings this concept to SWT. Ontop of this you can use Eclipse RCP which is an application framework similar to the Netbeans platform in functionality.
So if you are programming "raw" Swing you get some support but still have to do a lot of work by yourself. SWT asks for more basic effort (and discipline) from your side. But for both exist platforms that implement the MVC ideas.
I have a pretty complex Java (JDK 6) code that needs to be converted so it works on Android. That Java code is intended to work with graphics: thus i have a class that extends JLabel (Swing component), "paintComponent" method reshapes that extended JLabel ("cuts" it to look like a circle) and draws it on the screen (i know, i know - i might use come "drawCircle" method but i need to extend JLabel because it has some popup menu attached to it).
Now, i have a problem - Android don't seem to have "Graphics" type, "Dimension" type, "Rectangle" type, "paintComponent" method and after all, i have no idea what control should i use to draw those customized JLabels on (in JDK 6, i have used JPanel that was container for those customized JLabels).
Please help! I need some advice on what would be the most painless method for converting given Java logic to Android logic?
Android provides Graphics and 2D Graphics, used for drawing.
Have a look at Shape Drawable which should assist you in drawing rectangles. Instead of JLabel use TextView. You will have to spend some time in getting to know Android and redrawing your GUI, but I hope I provided some good starting points.
Also note that depending on complexity of your code, you may not be able to use all your Java code, becase Android doesn't provide full Java version.
AFAIK Android doesn't support Swing, so you're going to have to use equivalent Android UI classes. The android UI classes are not a 1-to-1 match with Swing classes, so sometimes an Android port means you need to do a pretty heavy UI rewrite.
Android do not have JLabel, so you can not use this code.
Instead use TextView . You can declare TextView in xml or in java code
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
What pure Java HTML viewers and renderers are available? The requirements are:
It should implement the JComponent interface to be placed into Scrollable pane.
It should be preferably a free solution; open source is a plus.
Its availability as Maven artifact is a plus.
I know only of a few components and projects, some of which are now defunct:
Built-in JEditorPane, supports HTML 3.2 (as of Java 1.4)
DJ Project (it is pure Java?)
Ekit by hexidec (is based on javax.swing.text.html.HTMLEditorKit)
JSyndrome HTML Editor by Sferyx
JWebPane (was it ever released)?
JDIC (abandoned; from some info here I see that it is native)
(PDF renderer) WebRenderer (former XHTMLRenderer)
Since Java 8, you can use JavaFX's WebView Component, which can also be used in Swing.
Code is as simple as:
JFXPanel jfxPanel = new JFXPanel(); // Scrollable JCompenent
Platform.runLater( () -> { // FX components need to be managed by JavaFX
WebView webView = new WebView();
webView.getEngine().loadContent( "<html> Hello World!" );
webView.getEngine().load( "http://www.stackoverflow.com/" );
jfxPanel.setScene( new Scene( webView ) );
});
It is backed by the WebKit engine (version depends on JRE and is reasonably up to date).
But keep in mind that it is not a full browser, so don't count on support of, say, HTML5 audio/video.
Otherwise, it runs HTML + CSS + JS as good as your browser.
Technically, the underlying engine is C++, not native Java.
But it is bundled in Oracle's official JRE, requires no library, has zero config, is as cross-platform as Java FX, and is actively updated and maintained.
As good as native Java for most use cases, I think?
The information below is outdated, seeing that we now have WebView in Java.
Tried Cobra/Lobo, CSSBox, and Flying Saucer, all pure Java. Others are either native or commercial.
Content: Simple HTML generated on the fly (as string), embedded CSS 2.1, no JS.
Short story: Flying Saucer is simplest to use and render is most correct, but you better have full control over content. Otherwise look for a native solution.
Long story:
CSSBox seems to be more active, however it seems to depends on some 3rd party libraries. For example the demo depends on nekohtml which use apache xerces which changed the way the default Java 1.7 sax parser works and broke my program, but when I force it to use java's built in xerces I get ClassCastException (InlineBox to BlockBox). Can't get it to work at the end. Plus still haven't found a way to replace the document in an existing BrowserCanvas.
Cobra is no longer maintained, have to manually fix an incompatibility issue to make it works in 1.7. Also need to grab mozilla Rhino (not using any JS) but that is all. After that it is fairly smooth, just need to ask Logger to hide paint messages. Render is correct and speed is fair - as long as the document is simple. When you start to use less common tags or more complicated layout, Cobra falls apart pretty quickly.
Flying Saucer has the best CSS support of the three as of writing (Feb 2011). Setup is very easy (e.g. no need to setup document like cobo or domparser like cssbox) has few dependency - which also means no javascript. But Flying Saucer is very strict about what you feed it. The source must be a well-formed XML, for example style and script may have to be wrapped in CDATA and if you use html entities you must declare DTD (so no html5 doctype). However if you are embedding content that you can control then it may be your best choice.
If you are using Swing, you can embed a JavaFX WebView.
1)Should implement JComponent interface to be placed into Scrollable pane.
In order to add the WebView to Swing you need to add it to JFXPanel, which is a JComponent.
To make the WebView fill the full JFXPanel, I used an AnchorPane like so:
final AnchorPane anchorPane = new AnchorPane();
WebView webBrowser = new WebView();
//Set Layout Constraint
AnchorPane.setTopAnchor(webBrowser, 0.0);
AnchorPane.setBottomAnchor(webBrowser, 0.0);
AnchorPane.setLeftAnchor(webBrowser, 0.0);
AnchorPane.setRightAnchor(webBrowser, 0.0);
//Add WebView to AnchorPane
anchorPane.getChildren().add(webBrowser);
//Create Scene
final Scene scene = new Scene(anchorPane);
// Obtain the webEngine to navigate
final WebEngine webEngine = webBrowser.getEngine();
webEngine.load("http://www.google.com");
_jfxPanel.setScene(scene);
Whenever you run JavaFX code, make sure to run it in Platform.runLater().
2) Should be preferably a free solution; opensource is a plus.
Well, it's pure Oracle java.
3) Availability as maven artifact is a plus.
See the StackOverflow answer Maven project with JavaFX (with jar file in `lib`) for advice on integrating JavaFX and Maven.
From Java8 on JavaFX will be fully integrated in Java.
Additonal Pros:
-supports HTML5 and JavaScript (uses webkit)
-supports platform interoperability
-even supports interacting with the DOM, run JavaScript, get notified of events from the Webview.
Cons:
-JavaFX needs to be installed. But it comes bundled with java since v7u6 (August 2012).
Other experiences:
I tried djproject, but had lots of problems with platform interoperability. Worked quite well on Windows, but only with major effort on Linux and I couldn't get it to work on Mac. For every platform you also need to build a 32bit and 64bit version of your jar. With lot of effort and a huge jar file you could possibly merge everything together in one jar. But this was far from being convenient.
Compared to the JavaFX solution I mentioned above, the DJProject was a way bigger pain.
CSSBox might be what you're looking for: http://cssbox.sourceforge.net
Check out this article: http://devdaily.com/blog/post/jfc-swing/how-create-simple-swing-html-viewer-browser-java
It uses JEditorPane and some other Swing classes to parse and render not only HTML, but also CSS.
You can also access the native browser through something like:
http://djproject.sourceforge.net/ns/
For certain web pages, this is sometimes the only way to go. There are always trade offs.
I have yet to find a browser component that renders well, is open source, and sufficiently flexible at the same time. Cobra comes close but there are pages that it won't render and it's tough (impossible?) to do things like get rid of its own scroll bars, etc..
Wow haferblues, I never thought I would find something I like about JavaFX. But the browser implementation is really nice. For those (like me) that never have used JavaFx before here the complete class (for the snippet of haferblues):
import com.sun.javafx.application.PlatformImpl;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
public class SwingBrowser extends JFXPanel {
private static final long serialVersionUID = 1L;
public SwingBrowser(String url) {
PlatformImpl.startup(new Runnable() {
#Override
public void run() {
final AnchorPane anchorPane = new AnchorPane();
WebView webBrowser = new WebView();
// Set Layout Constraint
AnchorPane.setTopAnchor(webBrowser, 0.0);
AnchorPane.setBottomAnchor(webBrowser, 0.0);
AnchorPane.setLeftAnchor(webBrowser, 0.0);
AnchorPane.setRightAnchor(webBrowser, 0.0);
// Add WebView to AnchorPane
anchorPane.getChildren().add(webBrowser);
// Create Scene
final Scene scene = new Scene(anchorPane);
// Obtain the webEngine to navigate
final WebEngine webEngine = webBrowser.getEngine();
webEngine.load(url);
setScene(scene);
}
});
}
}
The Flying Saucer was doing the job OK, but the following rendered text example was a huge turnoff for my mobile app development on Linux Java :
Sometimes the period at the end changes line without the text beside
.
Also, the text isn't selectable unlike for the JTextPanel.
Parser only seems to accept UTF-8 encoding. I couldn't manage to force my own encoding when parsing.