Centering a JLabel in a Box
Hi,
I'm having trouble centering a JLabel that has been added to a Vertical Box. Does anyone know an easy way to center the label?
Thanks
Jim
import javax.swing.*;
public class Test {
public static void main(String[] args) {
JLabel label = new JLabel("text", SwingConstants.CENTER);
final JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.setSize(400, 50);
SwingUtilities.invokeLater(new Runnable(){
public void run() {
f.setLocationRelativeTo(null);
f.setVisible(true);
}There is a whole forum devoted to Swing, by the way...
Similar Messages
-
Centering a JLabel in an application
Excuse me for being a noob, but it is really annoying me:
I just started with Java and wanted to create something simple and i though; what could be more simple than a program which displays your current IP and hostname. I got everything working exept the fact that i'm having trouble centering the JLabels containing the results on the screen. I was hoping someone could help me with this.
Many thanks in advanceimport javax.swing.*;
public class Test {
public static void main(String[] args) {
JLabel label = new JLabel("text", SwingConstants.CENTER);
final JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.setSize(400, 50);
SwingUtilities.invokeLater(new Runnable(){
public void run() {
f.setLocationRelativeTo(null);
f.setVisible(true);
}There is a whole forum devoted to Swing, by the way... -
Centering text vertically in text box
When you open a text box how do you center the text in the middle from top to bottom(vertically), not left to right. The text starts immediately in the top left corner. I need it in the center of a predefined text box size, so that if you drew a line across the center of the box from left to right, the top half of the letters would be above the line and the bottom half would be below the center line. In other words there should be the same distance above the words to the top edge of the text box, as to the bottom of the text box, from the center.
Thanks for the reply. Let me start by saying I am definitely a newbie with Photoshop. So if you could explain what I should do in PS that would help. I'm using CS6 Extended. I really don't know the difference between Paragraph text and Point text, and not sure what you mean when you ask is this for an Action.
I selected the "T" Horizontal type tool, and drew a box. Then I started typing. It looks like my selections are left align, center align, and right align. But it does not Center it in the middle of the box. The text is still at the top of the box. I have to have the box a certain size because of the project I'm working on. I'm assuming the text I'm selecting is what you are calling Paragraph Text. How do you use Point Text.
It's basically the spine on a book cover. You place the Title and the Authors name there, but you have to make sure it fits within the spine width, and is centered in that area. Like if you were looking at the side of a book, the title/author should be centered along that spine from top to bottom.
Thanks! -
Java Bug? Centering a JLable with just an icon in a JScrollPane
Hi,
I'm attempting to write a image viewing program. I would like the image centered on the window displaying them, but because some images are larger than the window, I would like the image to be in the upper left hand coner of the window with scroll bars to allow you to view the rest of the image.
I have attempted to implement this by placing a JScrollPane on a JFrame, and then placing a JLabel in the JScrollPane's Viewport. I set the Label's text to blank, and then set the image, wraped in an InageIcon, as the JLabel's Icon.
To center the JLabel, I have tried to set the JScrollPane's Viewport's LayoutManager to two different layout managers, but I've found buggy operation with each. The Layout I've tried are the following:
1. a GridLayout(1,1,0,0); - this works fine when the image is smaller that the available area of the JScrollPane. However, if the window is resized so that the image more than totally fills the JScrollPane, the image gets cut off. What happens is that the image is centered in the available scrollpane view, meaning the uper and left edges of the image get cut off. Scroll bars appear to let you view the lower and righer edges of the image, however, when you scroll, the newly uncovered areas of the image never get drawn, so you can't get to see the lower or right edges of the image either.
2. a GridbagLayout with one row, and one column each with a weight of 100, centered and told to fill both horizontally and vertically. Again, this correctly centers the JLabel when th eimage is smaler than the available space in the JScrollPane. Once the window is resized so that the image is bigger than the space to view the image in, strange problems occur. This time it seems that the JScrollPane's scrollbars show that there should be enough room to show the image if the image was in the upper left corner, however, the image isn't in the upper left corner, it is offset down and to the right if the upper left corner by an amount that appears equal to the amount of extra space needed to display the image. For example, if the image is 200x300 and the view area is 150x200, ite image is offest by 50 horizontally and 100 vertically. This results in the bottom and right edges of the image getting cut off because the scrollbars only scroll far enough to show the image if the image was placed at 0,0 and not at the offset location that it is placed at.
You may not understand what I'm trying to say from my description, but below is code that can reproduce the problem.
Questions. Am I doing anything wrong that is causing this problem? Is that another, better way to center the JLabel that doesn't have these problems? Is this a JAVA Bug in either the layoutmanagers, JScrollPane or JLabel when it only contains an icon and no text?
Code:
this is the class that creates and lays out the JFrame. It currently generates a 256x256 pixel image. By changing the imagesize variable to 512, you can get a larger image to work with which will make the bug more obvious.
When first run the application will show what happens when using the GridLayout and described in 1. There are two commented out lines just below the GridLayout code that use a GridbagLayout as descriped in method 2. Comment out the GridLayout code when you uncomment the GridBageLayout code.
package centertest;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;
public class Frame1 extends JFrame {
JPanel contentPane;
BorderLayout borderLayout1 = new BorderLayout();
JScrollPane jScrollPane1 = new JScrollPane();
JLabel jLabel1 = new JLabel();
static final int imagesize=256;
//Construct the frame
public Frame1() {
enableEvents(AWTEvent.WINDOW_EVENT_MASK);
try {
jbInit();
catch(Exception e) {
e.printStackTrace();
//Component initialization
private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(borderLayout1);
this.setSize(new Dimension(400, 300));
this.setTitle("Frame Title");
//setup label
jLabel1.setIconTextGap(0);
jLabel1.setHorizontalAlignment(JLabel.CENTER);
jLabel1.setVerticalAlignment(JLabel.CENTER);
jLabel1.setVerticalTextPosition(JLabel.BOTTOM);
//create image and add it to the label as an icon
int[] pixels = new int[imagesize*imagesize];
for(int i=0;i<pixels.length;i++){
pixels=i|(0xff<<24);
MemoryImageSource mis = new MemoryImageSource(imagesize, imagesize,
pixels, 0, imagesize);
Image img = createImage(mis);
jLabel1.setIcon(new ImageIcon(img));
jLabel1.setText("");
contentPane.add(jScrollPane1, BorderLayout.CENTER);
//center image using a GridLayout
jScrollPane1.getViewport().setLayout(new GridLayout(1,1,0,0));
jScrollPane1.getViewport().add(jLabel1);
//Center the image using a GridBagLayout
/*jScrollPane1.getViewport().setLayout(new GridBagLayout());
jScrollPane1.getViewport().add(jLabel1,
new GridBagConstraints(0, 0, 1, 1, 100.0, 100.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
//Overridden so we can exit when window is closed
protected void processWindowEvent(WindowEvent e) {
super.processWindowEvent(e);
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
System.exit(0);
and here is an application with which to launch the frame
package centertest;
import javax.swing.UIManager;
import java.awt.*;
public class Application1 {
boolean packFrame = false;
//Construct the application
public Application1() {
Frame1 frame = new Frame1();
//Validate frames that have preset sizes
//Pack frames that have useful preferred size info, e.g. from their layout
if (packFrame) {
frame.pack();
else {
frame.validate();
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
frame.setLocation( (screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
//Main method
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
catch (Exception e) {
e.printStackTrace();
new Application1();
}I'm running Java 1.4.1 build 21 on Windows 98. I used JBuilder8 Personal to write this code.Hmmm,
You are correct. Not setting a layout for the scrollpane's viewport (using the default of javax.swing.ViewportLayout) results in the positioning of the image tat I want (center the image if image is smaller than the scrollpane, if the image is larger, place it in the upper-left corener and enable the scrollbars to scroll to see the rest of the image).
Anyone have any idea why the GridLayout and GridBagLayout act as they do? I gues it isn't that important tomy program, but I'm still not sure that they are operating correctly. (Specifically, GridLayout sha scrollbars, but when you scroll, no new parts of the image are revealed.) -
Setting Text over an Icon which is on a JLabel - Urgent
Can someone help me. I need to set some text over an Image/Icon which is placed over a JLabel.
You should simply change the iconTextGap value (according to the string width and the icon width if you want it centered) :
JFrame frame = new JFrame("Centered label");
JLabel label = new JLabel("centered label",new ImageIcon("im1.gif"),SwingConstants.LEFT);
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
int iconWidth = label.getIcon().getIconWidth();
Font font = label.getFont();
Graphics g = label.getGraphics();
FontMetrics fm = g.getFontMetrics();
int stringWidth = fm.stringWidth(label.getText());
label.setIconTextGap(-stringWidth+((stringWidth-iconWidth)/2) );
I have made the frame visible before setting the texticongap because you can't get the graphic context of a component if this component is invisible.
Now the label is perfectly centered on the icon.
I hope this helps,
Denis -
Hello,
I am having difficulty with my box layouts in my form applet.
I have a JFrame with two panels. The left panel will allow the user to enter some parameters via text boxes, drop down menus, etc for a shape, which will appear on the right panel.
To arrange the form entry boxes on the left panel, I implemented a box layout. Here is where my trouble lies. I am not sure if I am using them correctly.
In the left panel, I added a box objectentitled entrySideBox, which has a createVerticalBox() orientation. I further added 7 boxes to this box layout, which had a createHorizontalBox() orientation. I have the form elements within the array of horizontal boxes. In summary, I hoped to create a box layout column with 7 horizontal rows to house the form entry elements.
Can I do this with the Box Layout? My form elements do not appear to be appearing as expected!
I have my code below. What is wrong?
//import the necessary java classes
import java.awt.*; //for the awt widgets
import javax.swing.*; //for the swing widgets
import java.awt.event.*; //for the event handler interfaces
public class DemoShape extends JFrame
//declare private data members of the DemoShape class
//requires seven control buttons
private JTextField xShapeText, yShapeText, messageText, fontSizeText;
private JComboBox shapeTypeDrop, shapeColorDrop, fontTypeDrop,fontColorDrop;
//declare the entry and display panel containers
private Panel entryPanel;
private Panel displayPanel;
//declare public data members of the DemoShape class
//constructor to initialize private data members
public DemoShape()
//call the superclass (JFrame) constructor with the name argument
//this must be done first (as in C++)
super("DemoShape Applet");
//arrays of string to be used later in combo boxes
//some are used more than once
String fonts[] = {"Dialog", "Dialog Input", "Monospaced",
"Serif", "Sans Serif"};
String shapes[] = {"Rectangle", "Round", "Oval"};
String colors[] = {"Black", "Blue", "Cyan", "Dark Gray",
"Gray", "Green", "Light Gray", "Magenta", "Orange",
"Pink", "Red", "White", "Yellow"};
//get the content pane of the class outside
Container entire = this.getContentPane();
entire.setLayout(new GridLayout(1,2));
//create the entry panel and add it to the entire pane
//this will be 7 rows, 1 column
//each row will have a panel with the form entry elements
entryPanel = new Panel(new FlowLayout());
entire.add(entryPanel);
//create the display panel and add it to the entire pane
//this will display the output
displayPanel = new Panel();
entire.add(displayPanel);
//entry panel code
//use a box layout to add the boxes in a row fashion on the entryPanel
Box boxes[] = new Box[7];
//create a main box for the entry side
Box entrySideBox = Box.createVerticalBox();
//iterively create a box layout for each row
for(int b = 0; b < boxes.length; b++)
{ boxes[b] = Box.createHorizontalBox(); }
//add the form elements to the boxes
//the first row should have the shape label
JLabel shapeHeader = new JLabel("Enter Shape Parameters:");
boxes[0].add(shapeHeader);
//second row should have the shape type and color
JLabel shapeTypeLabel = new JLabel("Select Shape:");
boxes[1].add(shapeTypeLabel);
shapeTypeDrop = new JComboBox(shapes);
boxes[1].add(shapeTypeDrop);
JLabel shapeColorLabel = new JLabel("Select Shape Color:");
boxes[1].add(shapeColorLabel);
shapeColorDrop = new JComboBox(colors);
boxes[1].add(shapeColorDrop);
//third row should have the x and y coords
JLabel xShapeLabel = new JLabel("Enter X:");
boxes[2].add(xShapeLabel);
xShapeText = new JTextField("200", 3);
boxes[2].add(xShapeText);
JLabel yShapeLabel = new JLabel("Enter Y:");
boxes[2].add(yShapeLabel);
yShapeText = new JTextField("200", 3);
boxes[2].add(yShapeText);
//fourth row should have the message label
JLabel messageHeader = new JLabel("Enter Message Parameters:");
boxes[3].add(messageHeader);
//the fifth row should have the message
JLabel messageLabel = new JLabel("Enter Message:");
boxes[4].add(messageLabel);
messageText = new JTextField(50);
boxes[4].add(messageText);
//the sixth row should have the font type and size
JLabel fontTypeLabel = new JLabel("Select Font:");
boxes[5].add(fontTypeLabel);
fontTypeDrop = new JComboBox(fonts);
boxes[5].add(fontTypeDrop);
JLabel fontSizeLabel = new JLabel("Enter Font Size:");
boxes[5].add(fontSizeLabel);
fontSizeText = new JTextField("12", 2);
boxes[5].add(fontSizeText);
//the seventh row should have font color
JLabel fontColorLabel = new JLabel("Select Font Color:");
boxes[6].add(fontColorLabel);
fontColorDrop = new JComboBox(colors);
boxes[6].add(fontColorDrop);
//add the boxes to the entrySideBox
for(int e = 0; e < boxes.length; e++)
{ entrySideBox.add(boxes[e]); }
//add the entrySideBox to the entry panel
entryPanel.add(entrySideBox);
//display panel code
//debugging
JLabel test = new JLabel("Display Output Here");
displayPanel.add(test);
//set the size of the entire window and show the entire applet
this.setSize(800,600);
this.show();
} //end the DemoShape constructor
//call the main class
public static void main(String args[])
//create an instance of the DemoShape class
DemoShape DemoShapeRun = new DemoShape();
//add the window listener to the applet
DemoShapeRun.addWindowListener(
new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
} //end main
} //end DemoShape classThe problem with GridLayout is the form elements sizes
change relative to the size of the panel. I want the
form elements to remain in a consistent state.
Should I quit using the box layout?Ok, try to set the layout of the upper content pane to BorderLayout and place the left panel with your components in the WEST part of it (the panel for the drawings goes to CENTER). I don't know if this will produce the result that you want, but it's an idea.
You should use a GridLayout for this panel and only
specify 2 columns (don't specify the number of rowsor
the number of columns will be ignored, see theclass
documentation for further details).
Hope this helps,
Pierre2 Columns? For what?The first column is for the labels (e.g. "Select Font Color") and the second is for the input component (e.g. textarea). -
What channels come with the DTA HD boxes
...and no one at COMCAST can tell you what channels come with the DTA HD boxes. All they do is send you a link to sign in...typical COMCAST
pablomunich wrote:
...and no one at COMCAST can tell you what channels come with the DTA HD boxes. All they do is send you a link to sign in...typical COMCAST
Apologies for any confusion we may have caused.
Currently, the DTAs (small boxes) are limited to viewing (up to and including) Digital Starter content.
Our DTAs don't yet support full strength encryption like full cable boxes do. Full-strength encryption is currently required for authorizing premium channels (like HBO) on a DTA.
DTAs that we have deployed support "privacy mode". This is a limited fixed passkey form of content protection.
We have no current plans to activate full-strength encryption, but if we were to do that in the future it would be done in a way that would be in compliance with FCC rules, including obtaining any necessary FCC waivers.
Some additional background at the link below (the article is from 2012 but still a good primer):
http://www.lightreading.com/spit-(service-provider-it)/security-platforms/comcasts-dtas-security-optional/d/d-id/660833
We can certainly arrange to swap your DTA for a full cable box. Please give us a call at 1-800-COMCAST or stop by one of the the local service centers below to swap your box.
73 Rock Ave
Plainfield, NJ 07063
MONDAY-SATURDAY: 9:30am-6:30pm SUNDAY: closed
800 Rahway Ave
Union, NJ 07083
MONDAY-SATURDAY: 9:30am-6:30pm SUNDAY: closed
381 Lord St
Avenel, NJ 07001
MONDAY-SATURDAY: 9:30am-6:30pm SUNDAY: closed
Additional information here: http://customer.comcast.com/help-and-support/cable-tv/digital-adapter-enhancement
Attached lineup for your area should also help, also sent this to you via e-mail. Digital Starter includes Limited Basic plus Expanded Service in your area -
Hi,
I use an ImageIcon on a JLabel, which is embedded in a ScrollPane, which is embedded in a SplitPane. When I now resize the window or the SplitPane-side, the image is always centered on JLabel. But I want it to be in the upper left corner, since I have to assure that the upper left corner of the image is at (0,0). Otherwise other painting would move relative to the image.
I tried
setHorizontalAlignment(SwingConstants.RIGHT);
setVerticalAlignment(SwingConstants.TOP);
on JLabel, but only the latter had the proper effect. The former seems to be ignored. Is this a bug? How to work around?
I use jdk v1.3.1_01 on Linux.
Thanks for any help.
Greets
PuceYou should embed your JLabel in a container with a flow layout with a left alignment:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ImageScrollPane extends JFrame {
ImageScrollPane() {
super("");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
setBounds(100,100,685,513);
Container c = new Container();
c.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
c.add(new JLabel(new ImageIcon("im.jpg")));
JScrollPane scroller = new JScrollPane(c);
getContentPane().add(scroller);
pack();
setVisible(true);
public static void main(String[] args) {
new ImageScrollPane();
}I hope this helps,
Denis -
Double bounding box when scaling an object...why?
Here is an example of the issue that I am having. I have a rectangle that I am looking to scale up from the top while keeping the width the same. When I zoom out to see the entire artboard and then go to scale the rectangle it shows up with two bounding boxes. As I drag the bounding box the piece is centered withing the second bounding box and all the spaces are stretched. The issue goes away when I am zoomed in but I don't want this to happen when zoomed out. Does anyone have a suggestion for this issue? I am figuring there is was key command I accidentaly hit and I would like to know how to disable this.
Thanks,
Brownj293Mr. Bugge:
Thank you for your response and I apologize for the delay in mine. I couldn't try all of the fixes immediately because I had to complete some job duties before I could tinker with this issue.
Things that did not work:
Closing Firefox
Clearing the Preferences
Moving the Preferences Folder
Deleting Temp Files
Closing Other Adobe Programs (Including Bridge Running in the Background
Things I cannot do for various reasons:
Re-installing Acrobat
Turning Off the Firewall (My Company Only Uses 1 Anyway)
Things I haven't tried yet but hope to try later:
Update Printer Definition or Change Default Printer
Check for Corrupt Fonts
Clear My Font Cache
Things I learned:
The issue is most easily recreated by transforming an object to a smaller object. However, zooming in will realign the bounding box but it will only stay aligned when zoomed in. I find it very curious.
Even if I don't end up finding an answer, I do appreciate your time and help. -
I'm building a report using InDesign CS 6 8.0. I'm fairly new to it, but have been using Quark for years. Anyway, I'm building a report that has multiple pie charts. I used the same action to create all the pie charts, so I know they are all the exact same size. I've imported them into image boxes in InDesign (at 100%) which are all lined up to the same x coordinate. I've centered the pies in their boxes (using the command shift E command). And they are all coming out slightly off alignment from one another. I want them to all line up along the same x coordinate on the page (i.e., if you look at them one on top of the other, the left and right sides all line up if you use a rule alongside of them). I right clicked on each image box and clicked Fitting > Frame Fitting Options > None, just to be sure they weren't trying to fit somehow. Then I used the x/y coordinate of the image within the box and I STILL can't get them to line up. What am I doing wrong? Thanks.
JulieOkay, the pies themselves are all the same size, but I imagine it's unlikely the labels around them are all identically sized and placed. Depending on how the bounding of each chart group is being determined, it may be that some pies are landing at differing coordinates in relation to "center." You might be better off finding a reference point that is more likely to be constant across all the charts in terms of proximity to the pie...one of the corners perhaps.
It's certainly not out of the question that achieving agreeable alignment simply by way of consistent method may be impossible. Sometimes you just have to give in, set some guides, and drag by eye. Might get you done quicker than agonizing over elusive inconsistencies. -
How to center a text in numbers
I am having a little bit of a hard time trying to center a text between 3 or more columns.... how can I do that?
Threre are a few options:
1) select the three cells and merge them, then enter the text and open the cell formatter and center the text horizonatlly. NOTE: merging cells often causes unexpected problems
2) create a text box and type the text, then format as horizontally centered. Place the text box over the cells, set the fill pattern to the same as the cells
3) create another table to be the header :
and set the cell width for one cell to be the same as three in the "other" table
There are porbably more ways than this. Hopefully one of these will work for you or you will suggest another that works. -
Center TEXT in JTextArea?
Is it possible to center text in a JTextArea?
I searched it but nothing on the web ... Is there another way to do this?
with JTextPane or JTextEditor?
I want just to center some text ....
ThanksDo you want editable centered text or do you just want to display centered text and thought that JTextArea/JEditorPane/JTextPane was the only way to do it?
If you just need to display centered text, you can use JLabel with HTML tags:
Example:
String message = "<HTML><CENTER>Centered Text!!!<BR>With line breaks even!!!</CENTER><HTML>"
JLabel centered = new JLabel(message); -
Class error - cannot resolve symbol "MyDocumentListener"
Hello,
this is a groaner I'm sure, but I don't see the problem.
Newbie-itis probably ...
I'm not concerned with what the class does, but it would be nice for the silly thing to compile!
What the heck am I missing for "MyDocumentListener" ?
C:\divelog>javac -classpath C:\ CenterPanel.java
CenterPanel.java:53: cannot resolve symbol
symbol : class MyDocumentListener
location: class divelog.CenterPanel
MyDocumentListener myDocumentListener = new MyDocumentListener(); // define the listener class
^
CenterPanel.java:53: cannot resolve symbol
symbol : class MyDocumentListener
location: class divelog.CenterPanel
MyDocumentListener myDocumentListener = new MyDocumentListener(); // define the listener class
^
2 errors
package divelog;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import javax.swing.text.*;
public class CenterPanel extends JPanel implements ActionListener
{ // Opens class
static private final String newline = "\n";
private JTextArea comments;
private JScrollPane scrollpane;
private JButton saveButton, openButton;
private JLabel whiteshark;
private Box box;
private BufferedReader br ;
private String str;
private JTextArea instruct;
private File defaultDirectory = new File("C://divelog");
private File fileDirectory = null;
private File currentFile= null;
public CenterPanel()
{ // open constructor CenterPanel
setBackground(Color.white);
comments = new JTextArea("Enter comments, such as " +
"location, water conditions, sea life you observed," +
" and problems you may have encountered.", 15, 10);
comments.setLineWrap(true);
comments.setWrapStyleWord(true);
comments.setEditable(true);
comments.setFont(new Font("Times-Roman", Font.PLAIN, 14));
// add a document listener for changes to the text,
// query before opening a new file to decide if we need to save changes.
MyDocumentListener myDocumentListener = new MyDocumentListener(); // define the listener class
comments.getDocument().addDocumentListener(myDocumentListener); // create the reference for the class
// ------ Document listener class -----------
class MyDocumentListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
Calculate(e);
public void removeUpdate(DocumentEvent e) {
Calculate(e);
public void changedUpdate(DocumentEvent e) {
private void Calculate(DocumentEvent e) {
// do something here
scrollpane = new JScrollPane(comments);
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
saveButton = new JButton("Save Comments", new ImageIcon("images/Save16.gif"));
saveButton.addActionListener( this );
saveButton.setToolTipText("Click this button to save the current file.");
openButton = new JButton("Open File...", new ImageIcon("images/Open16.gif"));
openButton.addActionListener( this );
openButton.setToolTipText("Click this button to open a file.");
whiteshark = new JLabel("", new ImageIcon("images/gwhite.gif"), JLabel.CENTER);
Box boxH;
boxH = Box.createHorizontalBox();
boxH.add(openButton);
boxH.add(Box.createHorizontalStrut(15));
boxH.add(saveButton);
box = Box.createVerticalBox();
box.add(scrollpane);
box.add(Box.createVerticalStrut(10));
box.add(boxH);
box.add(Box.createVerticalStrut(15));
box.add(whiteshark);
add(box);
} // closes constructor CenterPanel
public void actionPerformed( ActionEvent evt )
{ // open method actionPerformed
JFileChooser jfc = new JFileChooser();
// these do not work !!
// -- set the file types to view --
// ExtensionFileFilter filter = new ExtensionFileFilter();
// FileFilter filter = new FileFilter();
//filter.addExtension("java");
//filter.addExtension("txt");
//filter.setDescription("Text & Java Files");
//jfc.setFileFilter(filter);
//Add a custom file filter and disable the default "Accept All" file filter.
jfc.addChoosableFileFilter(new JTFilter());
jfc.setAcceptAllFileFilterUsed(false);
// -- open the default directory --
// public void setCurrentDirectory(File dir)
// jfc.setCurrentDirectory(new File("C://divelog"));
jfc.setCurrentDirectory(defaultDirectory);
jfc.setSize(400, 300);
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
Container parent = saveButton.getParent();
//========================= Test Button Actions ================================
//========================= Open Button ================================
if (evt.getSource() == openButton)
int choice = jfc.showOpenDialog(CenterPanel.this);
File file = jfc.getSelectedFile();
/* a: */
if (file != null && choice == JFileChooser.APPROVE_OPTION)
String filename = jfc.getSelectedFile().getAbsolutePath();
// -- compare the currentFile to the file chosen, alert of loosing any changes to currentFile --
// If (currentFile != filename)
// -- get the current directory name -------
// public File getCurrentDirectory( );
File f=new File(System.getProperty("user.dir"));
fileDirectory = jfc.getCurrentDirectory();
// -- remember the last directory used --
if (defaultDirectory != fileDirectory)
{defaultDirectory = fileDirectory;}
try
{ //opens try
comments.getLineCount( );
// -- clear the old data before importing the new file --
comments.selectAll();
comments.replaceSelection("");
// -- get the new data ---
br = new BufferedReader (new FileReader(file));
while ((str = br.readLine()) != null)
{//opens while
comments.append(str);
} //closes while
} // close try
catch (IOException ioe)
{ // open catch
comments.append(newline +"Open command not successful:" + ioe + newline);
} // close catch
// ---- display the values of the directory variables -----------------------
comments.append(
newline + "The f directory variable contains: " + f +
newline + "The fileDirectory variable contains: " + fileDirectory +
newline + "The defaultDirectory variable contains: " + defaultDirectory );
else
comments.append("Open command cancelled by user." + newline);
} //close if statement /* a: */
//========================= Save Button ================================
} else if (evt.getSource() == saveButton)
int choice = jfc.showSaveDialog(CenterPanel.this);
if (choice == JFileChooser.APPROVE_OPTION)
File fileName = jfc.getSelectedFile();
// -- get the current directory name -------
// public File getCurrentDirectory( );
File f=new File(System.getProperty("user.dir"));
fileDirectory = jfc.getCurrentDirectory();
// -- remember the last directory used --
if (defaultDirectory != fileDirectory)
{defaultDirectory = fileDirectory;}
//check for existing files. Warn users & ask if they want to overwrite
for(int i = 0; i < fileName.length(); i ++) {
File tmp = null;
tmp = (fileName);
if (tmp.exists()) // display pop-up alert
//public static int showConfirmDialog( Component parentComponent,
// Object message,
// String title,
// int optionType,
// int messageType,
// Icon icon);
int confirm = JOptionPane.showConfirmDialog(null,
fileName + " already exists on " + fileDirectory
+ "\n \nContinue?", // msg
"Warning! Overwrite File!", // title
JOptionPane.OK_CANCEL_OPTION, // buttons displayed
// JOptionPane.ERROR_MESSAGE
// JOptionPane.INFORMATION_MESSAGE
// JOptionPane.PLAIN_MESSAGE
// JOptionPane.QUESTION_MESSAGE
JOptionPane.WARNING_MESSAGE,
null);
if (confirm != JOptionPane.YES_OPTION)
{ //user cancels the file overwrite.
try {
jfc.cancelSelection();
break;
catch(Exception e) {}
// ----- Save the file if everything is OK ----------------------------
try
{ // opens try
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
bw.write(comments.getText());
bw.flush();
bw.close();
comments.append( newline + newline + "Saving: " + fileName.getName() + "." + newline);
break;
} // closes try
catch (IOException ioe)
{ // open catch
comments.append(newline +"Save command unsuccessful:" + ioe + newline);
} // close catch
} // if exists
} //close for loop
else
comments.append("Save command cancelled by user." + newline);
} // end-if save button
} // close method actionPerformed
} //close constructor CenterPanel
} // Closes class CenterPanelThere is no way to be able to see MyDocumentListener class in the way you wrote. The reason is because MyDocumentListener class inside the constructor itself. MyDocumentListener class is an inner class, not suppose to be inside a constructor or a method. What you need to do is simple thing, just move it from inside the constructor and place it between two methods.
that's all folks
Qusay -
Seemingly trivial but can't see to do it
Hi,
I always liked using the arrow keys for moving objects in situations where I need more precise control e.g. I use this technique in Photoshop all the time. Is there a trick to using arrow keys in PrE 9? For example, I'm trying to position my text on my video layer but I seem to be able to move it around only using my mouse. Is there not a way to use the arrow keys to move objects like that?
Also, in once situation, I needed to put a white background behind my text to make it more legible. So I placed a white rectangle behind it. Then I tried centering the text inside the box. I used "Align Objects" from the right click menu but the Vertical and Horizontal Align just didn't do the trick. The idea was the center the text inside the box with equal margin around the text.
Such trivial things seem to become challenges for me. Is it me or can you not do these things in PrE 9?
Thanks,
SamOne thing that might prove useful is an alignment grid, as outlined and provided in this ARTICLE.
There is also a pair of alignment tools in Titler - vertical and horizontal center for alignment.
For a Feature Request, see this ARTICLE. I've filled in one from PrE 4, but no luck so far.
Good luck,
Hunt -
Trying to move inner class to a class file
Hi folks,
I keep getting an error which puzzles me. I cut the following class (MyDocumentListener) out of an outer class (CenterPanel).
MyDocumentListener compiles OK but...
Now when I compile the outerclass I get the folowing error:
C:\divelog> javac -classpath C:\ CenterPanel.java
CenterPanel.java:54: cannot access divelog.MyDocumentListener
bad class file: C:\divelog\MyDocumentListener.class
class file contains wrong class: MyDocumentListener
Please remove or make sure it appears in the correct subdirectory of the classpath.
MyDocumentListener myDocumentListener = new MyDocumentListener(); // define
the listener class
^
1 error
... yes I checked, it is there..
C:\divelog>dir m*.j*
Directory of C:\divelog
MYDOCU~1 JAV 936 03-04-03 11:16p MyDocumentListener.java
====================================================================
MyDocumentListener tests to see if the current document has changed.
Required fields: boolean documentWasChanged;
import javax.swing.event.*;
// ------ Document listener class -----------
public class MyDocumentListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
wasChanged(e);
public void removeUpdate(DocumentEvent e) {
wasChanged(e);
public void changedUpdate(DocumentEvent e) {
public boolean wasChanged(DocumentEvent e) {
// indicate that the document was changed
//and test before opening another file or closing the application.
boolean documentWasChanged = true;
return documentWasChanged;
} // close class MyDocumentListener
====================================================================
package divelog;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.*;
// import javax.swing.text.JTextComponent.*;
import javax.swing.text.*;
public class CenterPanel extends JPanel implements ActionListener
{ // Opens class
static private final String newline = "\n";
private JTextArea comments;
private JScrollPane scrollpane;
private JButton saveButton, openButton;
private JLabel whiteshark;
private Box box;
private BufferedReader br ;
private String str;
private JTextArea instruct;
private File defaultDirectory = new File("C://divelog");
private File fileDirectory = null;
private File currentFile= null;
// public boolean changed;
public boolean documentWasChanged;
public CenterPanel()
{ // open constructor CenterPanel
setBackground(Color.white);
comments = new JTextArea("Enter comments, such as " +
"location, water conditions, sea life you observed," +
" and problems you may have encountered.", 15, 10);
comments.setLineWrap(true);
comments.setWrapStyleWord(true);
comments.setEditable(true);
comments.setFont(new Font("Times-Roman", Font.PLAIN, 14));
// add a document listener for changes to the text,
// query before opening a new file to decide if we need to save changes.
MyDocumentListener myDocumentListener = new MyDocumentListener(); // define the listener class
comments.getDocument().addDocumentListener(myDocumentListener); // create the reference for the class
scrollpane = new JScrollPane(comments);
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
saveButton = new JButton("Save Comments", new ImageIcon("images/Save16.gif"));
saveButton.addActionListener( this );
saveButton.setToolTipText("Click this button to save the current file.");
openButton = new JButton("Open File...", new ImageIcon("images/Open16.gif"));
openButton.addActionListener( this );
openButton.setToolTipText("Click this button to open a file.");
whiteshark = new JLabel("", new ImageIcon("images/gwhite.gif"), JLabel.CENTER);
Box boxH;
boxH = Box.createHorizontalBox();
boxH.add(openButton);
boxH.add(Box.createHorizontalStrut(15));
boxH.add(saveButton);
box = Box.createVerticalBox();
box.add(scrollpane);
box.add(Box.createVerticalStrut(10));
box.add(boxH);
box.add(Box.createVerticalStrut(15));
box.add(whiteshark);
add(box);
} // closes constructor CenterPanel
public void actionPerformed( ActionEvent evt )
{ // open method actionPerformed
// --------- test to see if the current file was modified and give an option to save first.
if (documentWasChanged) // add and IF filename not null
// ----- display pop-up alert --------------------------------------------------------------
int confirm = JOptionPane.showConfirmDialog(null,
"Click OK to discard current changes, \n or Cancel to save before proceeding.", // msg
"Unsaved Modifications!", // title
JOptionPane.OK_CANCEL_OPTION, // buttons displayed
// JOptionPane.ERROR_MESSAGE
// JOptionPane.INFORMATION_MESSAGE
// JOptionPane.PLAIN_MESSAGE
// JOptionPane.QUESTION_MESSAGE
JOptionPane.WARNING_MESSAGE,
null);
if (confirm != JOptionPane.YES_OPTION) //user wants to save changes
try {
// let user save the file
catch(Exception e) {}
else // let user open a new file
} // close "if (documentWasChanged)" - display pop-up alert ----------
JFileChooser jfc = new JFileChooser();
//Add a custom file filter and disable the default "Accept All" file filter.
jfc.addChoosableFileFilter(new JTFilter()); // /** found in Utils.java /*
jfc.setAcceptAllFileFilterUsed(false);
// -- open the default directory --
// public void setCurrentDirectory(File dir)
// jfc.setCurrentDirectory(new File("C://divelog"));
jfc.setCurrentDirectory(defaultDirectory);
jfc.setSize(400, 300);
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
Container parent = saveButton.getParent();
//========================= Test Button Actions ================================
//========================= Open Button ================================
if (evt.getSource() == openButton)
int choice = jfc.showOpenDialog(CenterPanel.this);
File file = jfc.getSelectedFile();
// --------- change test was here -----------
/* a: */
if (file != null && choice == JFileChooser.APPROVE_OPTION)
String filename = jfc.getSelectedFile().getAbsolutePath();
// -- get the current directory name -------
// public File getCurrentDirectory( );
File f=new File(System.getProperty("user.dir"));
fileDirectory = jfc.getCurrentDirectory();
// -- remember the last directory used --
if (defaultDirectory != fileDirectory)
{defaultDirectory = fileDirectory;}
try
{ //opens try
comments.getLineCount( );
// -- clear the old data before importing the new file --
comments.selectAll();
comments.replaceSelection("");
// -- get the new data ---
br = new BufferedReader (new FileReader(file));
while ((str = br.readLine()) != null)
{//opens while
comments.append(str);
} //closes while
} // close try
catch (IOException ioe)
{ // open catch
comments.append(newline +"Open command not successful:" + ioe + newline);
} // close catch
// ---- display the values of the directory variables -----------------------
comments.append(
newline + "The f directory variable contains: " + f +
newline + "The fileDirectory variable contains: " + fileDirectory +
newline + "The defaultDirectory variable contains: " + defaultDirectory );
else
comments.append("Open command cancelled by user." + newline);
} //close if statement /* a: */
//========================= Save Button ================================
} else if (evt.getSource() == saveButton)
int choice = jfc.showSaveDialog(CenterPanel.this);
if (choice == JFileChooser.APPROVE_OPTION)
File fileName = jfc.getSelectedFile();
// -- get the current directory name -------
// public File getCurrentDirectory( );
File f=new File(System.getProperty("user.dir"));
fileDirectory = jfc.getCurrentDirectory();
// -- remember the last directory used --
if (defaultDirectory != fileDirectory)
{defaultDirectory = fileDirectory;}
//check for existing files. Warn users & ask if they want to overwrite
for(int i = 0; i < fileName.length(); i ++) {
File tmp = null;
tmp = (fileName);
if (tmp.exists()) // display pop-up alert
//public static int showConfirmDialog( Component parentComponent,
// Object message,
// String title,
// int optionType,
// int messageType,
// Icon icon);
int confirm = JOptionPane.showConfirmDialog(null,
fileName + " already exists on " + fileDirectory
+ "\n \nContinue?", // msg
"Warning! Overwrite File!", // title
JOptionPane.OK_CANCEL_OPTION, // buttons displayed
// JOptionPane.ERROR_MESSAGE
// JOptionPane.INFORMATION_MESSAGE
// JOptionPane.PLAIN_MESSAGE
// JOptionPane.QUESTION_MESSAGE
JOptionPane.WARNING_MESSAGE,
null);
if (confirm != JOptionPane.YES_OPTION)
{ //user cancels the file overwrite.
try {
jfc.cancelSelection();
break;
catch(Exception e) {}
// ----- Save the file if everything is OK ----------------------------
try
{ // opens try
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
bw.write(comments.getText());
bw.flush();
bw.close();
comments.append( newline + newline + "Saving: " + fileName.getName() + "." + newline);
break;
} // closes try
catch (IOException ioe)
{ // open catch
comments.append(newline +"Save command unsuccessful:" + ioe + newline);
} // close catch
} // if exists
} //close for loop
else
comments.append(newline + "Save command cancelled by user." + newline);
// ========= }
} // end-if save button
} // close method actionPerformed
} //close constructor CenterPanel
// <<<<<<<<<<<<<<<<<
// <<<<<<<<<<<<<<<<< MyDocumentListener class was here <<<<<<<<<<<<<<<<<
// <<<<<<<<<<<<<<<<<
} // Closes class CenterPanelYou didn't put your MyDocumentListener class in the package divelog.
Add
package divelog;to the top of MyDocumentListener.java and recompile.
Maybe you are looking for
-
Spawn jobs are not getting priority and target servergiven at selection scn
Hi Abapers, I am scheduling main program as a job in backend through FMs JOB_OPEN, JOB_SUBMIT and JOB_CLOSE with priority and target server taken from user at selection screen through SE38,after executing the job,job will generate the spawn jobs (i.e
-
IPhone Bugs, Flaws & Wishlist (ADD YOURS TO LIST!!)
iPhone Bugs, Flaws & Wishlist -AT&T’s EDGE cellular network: "excruciatingly slow" -Making calls can be a 6 step process if phone is off. -halfway decent internal speakers for listening if you set the thing down -iPod games are not compatible with iP
-
제품 : MFG_PO 작성날짜 : 2004-05-24 PO 가 IN PROCESS 상태이고, 해당 PO의 WF_ITEM_TYPE 또는 WF_ITEM_KEY이 존재하지 않는 경우의 처리 방안. ============================================================================ PURPOSE In Process 상태의 PO의 Data fix 방안. Problem Description 어떠한 원인
-
Download PrintWork Bench Output on Application Server
Hi Experts, My requirement goes like this. I have to download the output of the form IS_U_METER_READING_DOWNLOAD into .txt files on application server. and Also, these files should be named as "CCYYMMCitycodePORTIONMRUD.txt" How do I do it? Even a sm
-
Unable to setup Yahoo account in Mail.app.
Everything worked ok till a couple of days ago and now keep getting error messages saying unable to connect to server. This is the latest message. There may be a problem with the mail server or network. Verify the settings for account "yahoo.com.au"