Pretty straightforward issue. My Java AWT (not Swing) label is simply not showing up. Most of the following code isn't even being used (for debugging this issue).
Just a note: this is within a Frame's constructor (and yes I have added several other panels and such that work just fine). Secondly, the frame's layout has been set to null.
I'm stumped.
File inf = new File("instructions.txt");
Label ilb;
if(inf.exists())
{
Log.v("Loading instructions");
try
{
FileInputStream fis = new FileInputStream(inf);
byte[] insb = new byte[65535];
fis.read(insb);
fis.close();
String inst = new String(insb);
ilb = new Label("test", Label.LEFT);
File fntfile = new File("font/pf_tempesta_seven.ttf");
Font infnt = null;
try {
FileInputStream ffis = new FileInputStream(fntfile);
infnt = Font.createFont(Font.TRUETYPE_FONT, ffis);
ffis.close();
} catch (FontFormatException e) {
Log.e("Could not format LCD font!", e);
} catch (IOException e) {
Log.e("Could not read LCD font file!", e);
}
if(infnt == null)
infnt = new Font("Trebuchet MS", Font.PLAIN, 8);
else
infnt = infnt.deriveFont(8.0f);
//ilb.setFont(infnt);
//ilb.setForeground(new Color(123, 123, 123));
//ilb.setPreferredSize(new Dimension(350, 400));
//ilb.setSize(350, 400);
//ilb.setLocation(580, 190);
Log.d("adding label");
add(ilb);
} catch(IOException e) {
Log.e("Could not read instructions!", e);
}
}else
Log.w("Instructions file not found!");
1) for todays GUI use Swing JComponents (starts with J) rather than prehistoric AWT Label
2) for your issue could be better use JTextArea with method append()
3) you have got issues with Concurency (in Swing) AWT / Swing is single threaded and all output to the GUI must be wrapped into invokeLater
4) for better help sooner you have edit your question with SSCCE
As #JBNizet suggested, null layouts don't work with all AWT components.
I was thrown off since my Panels were positioned just fine with a null layout on my Frame, whereas Labels require a basic layout in order to display. I was tempted to go as far as saying all other components had the same 'feature', but another part of my code proved that point wrong:
// Load Image
Log.v("Loading header image");
_iBG = new ImageIcon("img/hpcount_top_bg.png").getImage();
// Set size
setSize(1024, 152);
setPreferredSize(new Dimension(1024, 152));
// Set position
setLocation(0, 0);
// Set visible
setVisible(true);
// Set layout
setLayout(null);
// Add children
add(new Exit()); // Exit extends java.awt.Button
The above code (which is located within the constructor of a class extending java.awt.Panel) works perfectly.
My workaround is to put the label inside another Panel with a layout (messy, but it works) and position that panel within the Frame absolutely to achieve the same effect.
Related
Hi I am unsure on how to format my animated gif images to let them show on Jars created on eclipse.
try {
//ImageIcon titleIcon = new ImageIcon(ImageIO.read(getClass().getResource("title.gif")));
title = new ImagePicture (new ImageIcon(ImageIO.read(getClass().getResource("title.gif"))), 0, 0);
//title = new ImagePicture (new ImageIcon("title.gif"), 0, 0);
}//end try
catch (IOException e) {
}//end catch
//set title bounds
title.setBounds(260, 0, 400, 100);
That is my code right now for an animated GIF, Thank you for your input.
Hard to give a good example without more context, but you can try adding the ImageIcon to a JLabel like this.
URL url = this.getClass().getResource("title.gif");
Icon title = new ImageIcon(url);
JLabel titleLbl = new JLabel(title);
//You have to add titleLbl to a container after this, of course
I am trying to do a fairly basic swing GUI where a user can enter a url, choose a local file location etc. I am using multiple layout managers including boxlayout, borderlayout and flowlayout. The code is below.
My problem is that some of the components are moving around when the user puts text into the optionsTxt jtextarea. Anyone know where I should start to stop this happening?
Setup menu bar
JButton menu_File = new JButton("File");
JButton menu_Edit = new JButton("Edit");
JToolBar toolBar = new JToolBar();
toolBar.add(menu_File);
toolBar.add(menu_Edit);
//Setup options area
JPanel options = new JPanel();
options.setBorder(BorderFactory.createTitledBorder("Options"));
BoxLayout layout_Options = new BoxLayout(options, BoxLayout.Y_AXIS);
options.setLayout(layout_Options);
JLabel optionsLblURL = new JLabel("Enter URL:");
optionsTxtUrl = new JTextArea(1,15);
JLabel chooseDestLbl = new JLabel("Choose save location:");
chooseDest = new JButton("Browse");
chooseDest.addActionListener(this);
options.add(optionsLblURL);
options.add(optionsTxtUrl);
options.add(chooseDestLbl);
options.add(chooseDest);
//Setup launch area
JPanel launch = new JPanel();
launch.setBorder(BorderFactory.createTitledBorder("Launch"));
launchBtnStart = new JButton("Start Download");
launchBtnStart.setVerticalAlignment(SwingConstants.CENTER);
launchBtnStart.setHorizontalAlignment(SwingConstants.CENTER);
launchBtnStart.addActionListener(this);
launch.add(launchBtnStart);
//Setup reporting area
JPanel logging = new JPanel();
logging.setBorder(BorderFactory.createTitledBorder("Log"));
BoxLayout layout_Logging = new BoxLayout(logging, BoxLayout.Y_AXIS);
logging.setLayout(layout_Logging);
JTextArea loggingTxt = new JTextArea(3,10);
loggingTxt.setEditable(false);
logging.add(pb);
logging.add(loggingTxt);
//Add components to window
BorderLayout borderLayout = new BorderLayout();
setLayout(borderLayout);
add("North", toolBar);
add("West", options);
add("East", launch);
add("South", logging);
setVisible(true);
"My problem is that some of the components are moving around when the user puts text into the optionsTxt jtextarea. Anyone know where I should start to stop this happening?"
Start by putting your JTextArea in a ScrollPane and setLineWrap(true) and setWrapStyleWord(true). You may want to consider doing this with both JTextAreas you have
JTextArea optionsTxtUrl = new JTextArea(1,15);
optionsTxtUrl.setLineWrap(true);
optionsTxtUrl.setWrapStyleWord(true);
JScrollPane scroll = new JScrollPane(optionsTxtUrl);
options.add(scroll); // take out options.add(optionsTxtUrl);
This will make your lines wrap when they reach the right edge of the text area
public void setWrapStyleWord(boolean word) - Sets the style of wrapping used if the text area is wrapping lines. If set to true the lines will be wrapped at word boundaries (whitespace) if they are too long to fit within the allocated width. If set to false, the lines will be wrapped at character boundaries. By default this property is false.
public void setLineWrap(boolean wrap) - Sets the line-wrapping policy of the text area. If set to true the lines will be wrapped if they are too long to fit within the allocated width. If set to false, the lines will always be unwrapped. A PropertyChange event ("lineWrap") is fired when the policy is changed. By default this property is false.
If this doesn't solve your problem, you should edit your post with a Minimal, Complete, Tested and Readable example so we can test out your problem.
So basically im creating a GUI that allows the user to select a file, this file is check to be a .wav file. Then this file's data is graphed through JFreechart.
This graph or image created by Jfreechart i want to put into the JFrame.
The problem is that the code:
ImageIcon myIcon1 = new ImageIcon("blah.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
southContent.add(graphLabel1);
must be created & declared in the method where i create the JFrame ( must be added to the frame )
thus i cannot dynamically update the image to new created graphs, depending on what file the user selects. ( on selection of a new file, via button a new graph image is created )
is there a way to force
ImageIcon myIcon1 = new ImageIcon("blah.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
southContent.add(graphLabel1);
to update to the new image ( in the same direcotry, with the same name )
or is there a way using Mapping to set the image name ("blah.jpg") dynamically with a counter?
here is my SSCCE
public class gui extends JFrame {
ImageIcon myIcon1 = new ImageIcon("C:/location/chart1.jpg");
JLabel graphLabel1 = new JLabel(myIcon1);
gui() {
// create Pane + contents & listeners...
JPanel content = new JPanel();
JPanel southContent = new JPanel();
content.setLayout(new FlowLayout());
content.add(open_File);
// Jfreechart graph image -- not visible until selected
graphLabel1.setVisible(false);
// this is the graph image being added to the panel
southContent.add(graphLabel1);
southContent.setLayout(new FlowLayout());
// add action listeners to buttons
open_File.addActionListener(new OpenAction());
// set Pane allignments & size...
this.setContentPane(content);
this.add(southContent, BorderLayout.SOUTH);
this.setTitle("Count Words");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1100, 720);
this.setLocationRelativeTo(null);
}
// opening selected file directory.
class OpenAction implements ActionListener {
public void actionPerformed(ActionEvent ae) {
/// gets user selection ( file ) and procesess .wav data into array
/// loops through array creating X series for JfreeChart
// Add the series "series" to data set "dataset"
dataset.addSeries(series);
// create the graph
JFreeChart chart = ChartFactory.createXYLineChart(
".Wav files", // Graph Title
"Bytes", // X axis name
"Frequency", // Y axis name
dataset, // Dataset
PlotOrientation.VERTICAL, // Plot orientation
true, // Show Legend
true, // tooltips
false // generate URLs?
);
try {
ChartUtilities.saveChartAsJPEG(
new File("C:/location/chart1.jpg"), chart, 1000, 600);
} catch (IOException e) {
System.err.println("Error occured: " + e + "");
}
// !!!!! this is where i need to set the ImageIcon added to the
// panel in "gui" to this new created Graph image ("chart1.jpg")
// as above
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// sets the image label itself to visible as a new image has been
// added ot it
graphLabel1.setVisible(true);
}
}
}
Just add the JLabel to its container as you usually do. Then, once you created the image and you have an instance of an ImageIcon, just call the setIcon() method for the JLabel.
Using something like this should allow displaying both images of the waveform, as well as new images of the waveform.
try {
//ChartUtilities.saveChartAsJPEG(
// new File("C:/location/chart1.jpg"), chart, 1000, 600);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ChartUtilities.saveChartAsPNG(baos, chart, 1000, 600);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
BufferedImage image = ImageIO.read(bais);
// !!!!! this is where we need to set the ImageIcon..
graphLabel1.setIcon(new ImageIcon(image));
} catch (IOException e) {
e.printStackTrace();
System.err.println("Error occured: " + e + "");
}
OTOH you might look to increasing the memory size and generate the entire waveform in one pass, then display the label in a scroll pane.
Thanks to Dan and Andrew Thompson, i have a working product.
I used a counting variable to count teach time the "OpenAction" button was selected.
i then used this variable to make dynamic names for each image i created through JFreechart.
Thus i used .setIcon to reset the icon image to each new created image with a new name.
.setIcon does not seem to work if you are trying to reset the label to a Image icon that has the same name as the previously selected Image icon.
the finished code segment looks like:
ImageIcon myIcon1 = new ImageIcon("C:/location/chart"+CounterVariable+".png");
graphLabel1.setIcon(myIcon1);
for example this will create charts;
chart1
chart2
chart3
and so forth.
Is there a way in Java Swing to show text in small caps (small capitals)?
http://en.wikipedia.org/wiki/Small_caps
I have loaded a custom font which supports small caps via Font.createFont(). The text should be rendered somehow in small caps. Is this possible in JLabel, JTextPane or some other component?
You can try that, it works : (I get the font here for test : http://www.fonts101.com/fonts/view/Uncategorized/28374/Tahoma_Small_Cap.aspx)
String labelText ="Dfd";
JLabel lbl = new JLabel(labelText);
Font g=null;
Font g2=null;
try {
InputStream myStream = new BufferedInputStream(new FileInputStream("/home/alain/Bureau/tahomscb/tahomscb.ttf"));
g = Font.createFont(Font.TRUETYPE_FONT, myStream);
g2 = g.deriveFont(Font.PLAIN, 24);
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("font not loaded.");
}
lbl.setFont(g2);
this.add(lbl); //this is the parent component
Usually, when I initialize the fonts I want to use in my SWING applications, I do it this way:
public static final Font TITLEFONT = new Font("Calibri", Font.BOLD, 40);
Now, I have to do it a bit differently since I'm using some custom fonts from a .ttf file. I initialize the font this way:
try
{
InputStream is = OptionsValues.class.getResourceAsStream("fonts//KOMIKAX_.ttf");
TITLEFONT = Font.createFont(Font.TRUETYPE_FONT, is);
}
catch (Exception ex)
{
ex.printStackTrace();
System.err.println("Font not loaded. Using Calibri font.");
TITLEFONT = new Font("Calibri", Font.BOLD, 40);
}
I'm pretty sure it initializes it correctly (I can't tell for sure since it is too small for me to see), but I'd like to know how I can manually set the font's size (and if it's bold / other attributes) when loading a font this way.
Thanks a lot in advance!
createFont returns a Font and you can call deriveFont(...) on this, passing in a float for the point size, or an int and float for Font style and point size. I cannot say whether it will work for your particular situation, but it's worth a try.
e.g.,
InputStream is = OptionsValues.class.getResourceAsStream("fonts//KOMIKAX_.ttf");
TITLEFONT = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(Font.BOLD, 40f);
I'd simply use:
Font.ITALIC
Font.BOLD
Font.PLAIN