I am writing a little stock quote application and when I compile the code the space for the text will be taken in the Jlist but no text will appear.
def loadStockDisplay(self):
self.display = JPanel()
self.display.setLayout(BorderLayout())
self.display.setBackground(Color.decode("#0A0A33"))
self.display.setBorder(BorderFactory.createMatteBorder(0,3,0,0,Color.decode("#8080E6")))
self.label = JLabel("Stocks")
self.label.setForeground(Color.decode("#FCFCFC"))
self.label.setFont(self.font)
self.display.add(self.label,BorderLayout.NORTH)
self.stocks = DefaultListModel();
self.items = JList(self.stocks)
self.items.setBackground(Color.decode("#0A0A33"))
self.items.setForeground(Color.decode("#FCFCFC"))
self.items.setFont(self.font)
self.items.setSelectionBackground(Color.decode("#0A0A33"))
self.items.setSelectionForeground(Color.decode("#FCFCFC"))
self.display.add(self.items, BorderLayout.CENTER)
self.frame.add(self.display,BorderLayout.EAST)
self.updateStocks()
def updateStocks(self):
companys = ["MSFT","SNDK","GOOGL","NOK","EMC","HPQ","IBM","EBAY","AAPL","AMZN"]
tempList = []
for company in companys:
Quote = web()
tempList.append(company + " " + str(Quote.getQuote(company)))
self.stocks.clear()
for item in tempList:
self.stocks.addElement(item)
Maybe there is a problem in the code that is not yet available in the question? Could you share the class and main method (if you have these)? There could also be an issue with fetching the quotes from the web.
If I add some code to make your program run, the list has items for each company (with a dummy quote):
from java.awt import BorderLayout, Color
from javax.swing import BorderFactory, DefaultListModel, JFrame, JLabel, JList, JPanel
class StocksTest:
def loadStockDisplay(self):
self.frame = JFrame('Stocks', defaultCloseOperation=JFrame.EXIT_ON_CLOSE, size=(300, 300), locationRelativeTo=None)
self.display = JPanel()
self.display.setLayout(BorderLayout())
self.display.setBackground(Color.decode("#0A0A33"))
self.display.setBorder(BorderFactory.createMatteBorder(0,3,0,0,Color.decode("#8080E6")))
self.label = JLabel("Stocks")
self.label.setForeground(Color.decode("#FCFCFC"))
self.label.setFont(self.frame.font)
self.display.add(self.label,BorderLayout.NORTH)
self.stocks = DefaultListModel();
self.items = JList(self.stocks)
self.items.setBackground(Color.decode("#0A0A33"))
self.items.setForeground(Color.decode("#FCFCFC"))
self.items.setFont(self.frame.font)
self.items.setSelectionBackground(Color.decode("#0A0A33"))
self.items.setSelectionForeground(Color.decode("#FCFCFC"))
self.display.add(self.items, BorderLayout.CENTER)
self.frame.add(self.display,BorderLayout.EAST)
self.frame.setVisible(True)
self.updateStocks()
def updateStocks(self):
companys = ["MSFT","SNDK","GOOGL","NOK","EMC","HPQ","IBM","EBAY","AAPL","AMZN"]
tempList = []
for company in companys:
#Quote = web()
#companyQuote = Quote.getQuote(company)
companyQuote = len(str(company)) * 314.15
tempList.append(company + " " + str(companyQuote))
self.stocks.clear()
for item in tempList:
self.stocks.addElement(item)
def main():
StocksTest().loadStockDisplay()
if __name__ == '__main__':
main()
Related
I'm trying to make an app with a panel where it asks a question (whether an image contains humans, cars, or other objects... and more). Each question is answered with yes/no. I didn't want to make JRadioButton for each of the 'yes's and 'no's. So I tried to add the same Radio Button multiple times but it doesn't work (See below).
contentsPanel = new JPanel();
contentsHumans = new JLabel("Humans? ");
contentsCars = new JLabel("Cars? ");
contentsOtherObjects = new JLabel("Other Objects? ");
yes = new JRadioButton("Yes");
no = new JRadioButton("No");
binaryAnswer = new ButtonGroup();
binaryAnswer.add(yes);
binaryAnswer.add(no);
contentsPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Image contains... "));
contentsPanel.add(contentsHumans);
contentsPanel.add(yes); contentsPanel.add(no);
contentsPanel.add(contentsCars);
contentsPanel.add(yes); contentsPanel.add(no);
contentsPanel.add(contentsOtherObjects);
contentsPanel.add(yes); contentsPanel.add(no);
Do I have to separately create y1 = new JRadioButton("Yes");, y2 = new JRadioButton("Yes");, etc., for all my 'yes's and 'no's?? I can definitely copy and paste to do that but I was wondering if there is any other way.
Here's the image of current output:
I'm working on a application which takes pizza orders. Once the user clicks the order summary button the program would display the order summary. The application looks like this:
I would like to print out the order summary(only not the error) in a new penal with a JTextArea like such:
But I don't know how. This is what my application displays right now:
Here is the Code related to the display:
orderSummary = "Customer Name: " + name +
"\nPhone Number: " + phoneNumber +
"\nSize: " + size +
"\nToppings: " + toppings +
"\nTotal: $" + total;
if(error)
JOptionPane.showMessageDialog(null, ErrorString);
else
JOptionPane.showMessageDialog(null, orderSummary);
Error display:
I'm not 100% sure of what you are asking, but if you are looking for a dialog to popup (not just a panel), then you could try something like:
JDialog zMessageDialog = new JDialog((java.awt.Frame) null, true);
zMessageDialog.setTitle("Order summary");
zMessageDialog.setLayout(new BorderLayout());
JTextArea zTextArea = new JTextArea("Blah blah\nblah blah\nblah blah");
zTextArea.setEditable(false);
zTextArea.setColumns(40);
zTextArea.setRows(10);
zTextArea.setBackground(null);
JScrollPane zScrollPane = new JScrollPane(zTextArea);
zMessageDialog.add(zScrollPane, BorderLayout.CENTER);
zMessageDialog.revalidate();
zMessageDialog.pack();
zMessageDialog.setVisible(true);
This just puts a JTextArea in a JDialog. It makes the JTextArea non-editable, and sets its background color to null (which makes it look less editable).
Of course, this may not be the best way to go in terms of a user interface, but that is a different question. If you are using an IDE like Netbeans, you can easily create a separate class based on JDialog and add a panel at the bottom with an "OK" button, and whatever other customizations you desire.
I'm trying to call a method from a class called Circle in my project which displays some basic information about the object in a JLabel. For some reason the text won't go to a new line even when I use HTML to try and format it:
#Override
public String toString(){
return "<html>Type: " + this.getClass().getSimpleName() + "<br>Radius: " + getRadius() + "<br>Area: " + df.format(getArea()) + "<br>Perimeter: </html>" + df.format(getPerimeter());
}
I'm trying to display the info with this code:
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==btnCalc && x==1){
//create object
double R = Double.parseDouble(Txt1.getText());
Circle circ = new Circle(R);
lblResult.setText(circ.toString());
}
When I run the program it just returns this:<html>Type: Circle<br>Radius: 4.0<br>Area: 50.27<br>Perimeter:</html> 25.13
edit: I tried just setting the text as an exception message instead of calling the method and it didn't work this way either
edit: Now this happens when I try to run the cylinder-sphere classes, but it doesn't do that when I don't have any html in the toString() method.
Turns out I was using a DecimalFormat in the last four classes which was what was giving me the exception. Once I got rid of that, the strings formatted nicely using a JTextPane instead of a JtextField.
From the image you pasted, it looks like it is a text INPUT control (under Show Info button), like JTextField and not a JLabel.
You can use HTML content with JLabel constructor as well as with its setText method too. It works fine.
JLabel lbl = new JLabel("<html>Type: Circle<br>Some info<br>More info</html>")
JLabel lbl2 = new JLabel();
lbl2.setText("<html>Type: Circle<br>Some info<br>More info</html>")
But if you want to have an INPUT control (as in your image), you can not use HTML with JTextField. You have to use JTextPane for this.
JTextPane txt = new JTextPane();
txt.setContentType("text/html");
txt.setText("<html>Type: Circle<br>Some info<br>More info</html>");
How do you display the AST GUI if you have code like this, both of console or swing?
My ANTLR is version 3.
CharStream stream = new ANTLRStringStream("program XLSample1 =\n" +
"constant one : Integer := 1;\n" +
"constant two : Integer := 2;\n" +
"var a, b,c : Integer := 42;\n" +
"begin\n" +
" x:= (12 + 6) - (7 * 41) - x mod y;\n" +
" y := 21;\n" +
"\n" +
"if x < 10 then\n" +
" y :=2;\n" +
" elseif x < 20 then\n" +
" y := 20;\n" +
" else\n" +
" y := 30;\n" +
"end if; \n" +
"end XLSample1.");
SampleLexer lexer = new SampleLexer(stream);
TokenStream tokenStream = new CommonTokenStream(lexer);
SampleParser parser = new SampleParser(tokenStream);
parser.program();
System.out.println("OK");
}
Using ANTLR V4 (for V3 try to find out the similar API),to show a gui AST, you can use org.antlr.v4.runtime.tree.gui.TreeViewer.
You can get the Hello demo from ANTLR's site. Once you got it, run this simple demo:
import java.util.Arrays;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.gui.TreeViewer;
/**
* A simple demo to show AST GUI with ANTLR
* #see http://www.antlr.org/api/Java/org/antlr/v4/runtime/tree/gui/TreeViewer.html
*
* #author wangdq
* 2014-5-24
*
*/
public class HelloTestDrive {
public static void main(String[] args) {
//prepare token stream
CharStream stream = new ANTLRInputStream("hello antlr");
HelloLexer lexer = new HelloLexer(stream);
TokenStream tokenStream = new CommonTokenStream(lexer);
HelloParser parser = new HelloParser(tokenStream);
ParseTree tree = parser.r();
//show AST in console
System.out.println(tree.toStringTree(parser));
//show AST in GUI
JFrame frame = new JFrame("Antlr AST");
JPanel panel = new JPanel();
TreeViewer viewer = new TreeViewer(Arrays.asList(
parser.getRuleNames()),tree);
viewer.setScale(1.5); // Scale a little
panel.add(viewer);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
Then you will get the AST print in the console and show in JFrame.
more details, please refer ANTLR API.
Make sure your grammar work fine, then you can modify this demo to meet your requirement.
Update for ANTLR 4: TreeViewer has moved to org.antlr.v4.gui.TreeViewer package from ANTLR 4 Tool.
When using maven, TreeViewer requires the following dependency:
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4</artifactId>
<version>4.7.2</version>
</dependency>
After a few attempts trying to customize wangdq code, I figured out that it's possible to call the open method of TreeViewer class to get a delightful (because it's already done :)) Parse Tree Inspector.
Applied to wangdq example:
public class HelloTestDrive {
public static void main(String[] args) {
//prepare token stream
CharStream stream = new ANTLRInputStream("hello antlr");
HelloLexer lexer = new HelloLexer(stream);
TokenStream tokenStream = new CommonTokenStream(lexer);
HelloParser parser = new HelloParser(tokenStream);
ParseTree tree = parser.r();
//show AST in console
System.out.println(tree.toStringTree(parser));
//show AST in GUI
TreeViewer viewr = new TreeViewer(Arrays.asList(
parser.getRuleNames()),tree);
viewr.open();
}
}
use import org.antlr.v4.runtime.tree.gui.TreeViewer in ANTLR 4...its works :)
After a very long couple of days I have determined that there is a delay when displaying text very quickly in a text area if that text area is in a border layout. My question is, why does the following code take 10-20 times longer to execute using border layout than without (comment out one of the two methods either addWithBorderLayout or addWithoutBorderLayout) AND is there a way to use the border layout without this delay? (The problem exists with or without the SwingUtilities invokeLater() method.)
import java.awt.BorderLayout;
import java.awt.Label;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JDesktopPane;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
public class Driver
{
public static void main(String args[])
{
System.out.println("JEditPane Test");
//window to display the plyed back text
JFrame mainFrame = new JFrame("Main Frame");
//holds some text to be played back
final JEditorPane editPane1 = new JEditorPane();
final JEditorPane editPane2 = new JEditorPane();
//desktop pane to hold docs
JDesktopPane desktopPane = new JDesktopPane();
//create an internal frame
JInternalFrame internalFrame1 = new JInternalFrame("Test Doc 1", true, true, true, true);
internalFrame1.setContentPane(new JScrollPane(editPane1));
internalFrame1.setSize(400, 400);
internalFrame1.setVisible(true);
internalFrame1.setLocation(0, 0);
JInternalFrame internalFrame2 = new JInternalFrame("Test Doc 2", true, true, true, true);
internalFrame2.setContentPane(new JScrollPane(editPane2));
internalFrame2.setSize(400, 400);
internalFrame2.setVisible(true);
internalFrame2.setLocation(400, 0);
//add it to the desktop
desktopPane.add(internalFrame1);
desktopPane.add(internalFrame2);
//map of editor panes
final Map < String, JEditorPane > mapOfPanes = new HashMap < String, JEditorPane >();
mapOfPanes.put("1", editPane1);
mapOfPanes.put("2", editPane2);
//COMMENT ONE OF THESE TWO OUT!!!
addWithBorderLayout(mainFrame, desktopPane);
//addWithoutBorderLayout(mainFrame, desktopPane);
//for closing
mainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//set the size and location of the window
mainFrame.setSize(800,500);
mainFrame.setLocation(100, 100);
//make the window visible
mainFrame.setVisible(true);
//create some text to display
StringBuilder builder = new StringBuilder();
builder.append("This is a rather long string of text. ");
//build up a good amount of text
for(int i = 0;i < 5;i++)
{
//copy it a few times
builder.append(builder.toString());
}
//get the string
final String longStringOfText = builder.toString();
//create a thread to call setText on the editor pane
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
//for gathering stats
int sum = 0;
int numberOfCharsToPrintFromString = 0;
Date prev = new Date();
Date current = new Date();
System.out.println("Num Panes: " + mapOfPanes.size());
//for each pane
for(JEditorPane pane : mapOfPanes.values())
{
//to help in printing subsections of the big string
numberOfCharsToPrintFromString = 0;
while(numberOfCharsToPrintFromString < longStringOfText.length())
{
//wait a short amount of time
try{Thread.sleep(1);}catch(Exception e){}
//grab sections of the long string
String text = longStringOfText.substring(0, numberOfCharsToPrintFromString);
//set the text of the pane
pane.setText(text);
//stats
numberOfCharsToPrintFromString++;
long diff = current.getTime() - prev.getTime();
sum = sum + (int)diff;
prev = current;
current = new Date();
}
}
System.out.println("Average time in between events: " + ((double)sum/(double)numberOfCharsToPrintFromString));
}
});
thread.start();
}
private static void addWithoutBorderLayout(JFrame mainFrame, JDesktopPane desktopPane)
{
mainFrame.add(desktopPane);
}
private static void addWithBorderLayout(JFrame mainFrame, JDesktopPane desktopPane)
{
mainFrame.setLayout(new BorderLayout());
mainFrame.add(new Label("Top Panel"), BorderLayout.NORTH);
mainFrame.add(desktopPane, BorderLayout.CENTER);
mainFrame.add(new Label("Bottom Panel"), BorderLayout.SOUTH);
}
}
On Mac OS X 10.5.8 using Java version 1.6, I see a comparable disparity unless I set apple.awt.graphics.UseQuartz at the beginning of main(). Here is a related example that affects font rendering quality rather than execution time.
if (System.getProperty("os.name").startsWith("Mac OS X")) {
System.setProperty("apple.awt.graphics.UseQuartz", "true");
}
I use JDK6_17 on XP with an older computer and don't notice the difference you experience. My timings where betweenn 20-22 in both cases.
I then changed the sleep time to 10ms and the timings are remarkably similiar.
For the default layout:
Average time in between events: 31.236842105263158
Average time in between events: 31.236842105263158
Average time in between events: 31.236842105263158
For the Border layout:
Average time in between events: 31.236842105263158
Average time in between events: 31.23766447368421
Average time in between events: 31.236842105263158
In fact I can't believe they are identical in 5 of 6 cases.
By default the content pane of a JFrame does use a BorderLayout. So when you add components to the frame all you need to do is:
frame.add(topComponent, BorderLayout.NORTH);
frame.add(centerComponent);
frame.add(bottomComponent, BorderLayout.SOUTH);
and the frame will add the components to the content pane at the proper location.
Why are you changing the layout of the frame, instead of the content pane. Normally you would only ever change the layout of the content pane. The root pane of the frame is use to hold the menu bar and the content pane. So maybe you change the default layout manager of the entire frame you are causing some problems?