Why does the last JLabel I add to the JFrame move if I resize the window by dragging the corner with the mouse? - resize

When I run this program, the panel with the 6 buttons appears as it should on the bottom of the screen, and the first 3 labels appear as they should and where they should, but the last label appears at about the center of the screen. Furthermore, when I click and drag on the bottom right corner of the window (resizing the window), the panel and the last label move so they stay in their relative positions with the size of the window but the first 3 labels stay in their designated positions. When I uncomment the line of code towards the bottom that adds a blank JLabel, all 4 labels are now in their correct spots and only the panel moves when I resize the window. Could someone please explain what is going on here? Thanks in advance!
import javax.swing.*;
import java.awt.*;
public class X extends JFrame{
private JPanel panel;
private JButton buttons[];
private JLabel labels[];
private Icon images[];
public X()
{
panel = new JPanel();
panel.setPreferredSize(new Dimension(470,110));
buttons = new JButton[6];
labels = new JLabel[4];
Dimension dim = new Dimension(75,100);
labels = new JLabel[4];
images = new Icon[6];
for(int i = 0; i<6;i++)
images[i] = new ImageIcon(getClass().getResource("image" + i + ".gif"));
int j = 5;
while( j >= 0 ){
Icon image = images[j];
buttons[j] = new JButton(image);
buttons[j].setPreferredSize(dim);
panel.add(buttons[j]);
j--;
}
add(panel, BorderLayout.SOUTH);
j = 3;
while( j>=0){
Icon image = new ImageIcon(getClass().getResource("image6.gif"));
labels[j] = new JLabel(image);
labels[j].setPreferredSize(dim);
if (j==3){
labels[j].setBounds(200,135,75,100);
}
else if (j==2){
labels[j].setBounds(313,70,75,100);
}
else if (j==1){
labels[j].setBounds(425,135,75,100);
}
else if (j==0){
labels[j].setBounds(313,200,75,100);
}
add(labels[j]);
j--;
}
// add(new JLabel());
}
public static void main(String[] args) {
X frame = new X();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,500);
frame.setVisible(true);
}
}

1) You should read Javadocs for JPanel/JButton/JLabel and their default behaviours.
2) You should make sure that the code which you post compiles
3) You should make sure that the code AS you post it illustrates your problem
As it is your post does not meet requirements 2) and 3) and you probably did not read enough of 1)

Related

Horizontal scrollbar updating

I was messing around with SWT (for a PropertyPage), and found a little 'bug'?
Basically, when I resize the shell so it is smaller than my controls, it will make a scrollBar visible, which works just as intended. Though if I resize my controls (which are all children of a single root of course), somehow one or more parents don't get updated of the change which results in some weird behavior.
When my controls grow in size, it basically grows out of the shell (not visible) while there is no Scrollbar made visible. If I resize the shell (smaller than the initial size), the ScrollBar will become visible, but only for the initial size instead of the full width.
When my controls shrink in size it won't 'pack' either parent, which means I can scroll beyond the reach of my controls into emptiness.
Maybe it's worth mentioning that for me only horizontal growing/shrinking is a problem, although I'm pretty sure the same problems are occurring for vertical resizing
My question was if there is a solution/workaround for this. I have tried calling Layout() and pack() on various parents and the shell itself, without success. Now I know there is a custom (sadly private) Layout type used by one of the parents of a property page (the PreferenceDialog#PageLayout). Maybe this behavior comes this implementation?
EDIT: on request an MCVE
I assume one knows how to setup for a propertyPage, so for the sake of clarity I have posted only the createContents method (overriden from org.eclipse.jface.preference.PreferencePage), and a few helper methods/fields which should recreate a setup where this behavior can be observed. Basically play around with hiding/unhiding columns, and make sure to re-open when you want a different initial childSize (to test both growing and shrinking)
// static so you can re-open a the property/preference page for different initial sizes.
private static boolean h1 = false;
private static boolean h2 = false;
private static boolean h3 = false;
private static boolean h4 = false;
private Composite root;
#Override
protected Control createContents(Composite parent)
{
// setup root
this.root = new Composite(parent, SWT.NONE);
this.root.setLayout(new GridLayout());
this.root.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, false));
Table table = new Table(this.root, SWT.SINGLE | SWT.VIRTUAL | SWT.BORDER | SWT.FULL_SELECTION);
table.setHeaderVisible(true);
table.setLinesVisible(true);
table.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, false));
TableColumn c1 = new TableColumn(table, SWT.LEFT);
c1.setMoveable(true);
c1.setText("column 1");
this.updateColumn(c1, h1);
TableColumn c2 = new TableColumn(table, SWT.LEFT);
c2.setMoveable(true);
c2.setText("column 2");
this.updateColumn(c2, h2);
TableColumn c3 = new TableColumn(table, SWT.LEFT);
c3.setMoveable(true);
c3.setText("column 3");
this.updateColumn(c3, h3);
TableColumn c4 = new TableColumn(table, SWT.LEFT);
c4.setMoveable(true);
c4.setText("column 4");
this.updateColumn(c4, h4);
Button hide1 = new Button(this.root, SWT.PUSH);
hide1.setText("Hide column 1");
hide1.addListener(SWT.Selection, E -> {
this.updateColumn(c1, h1 = !h1);
this.resize();
});
Button hide2 = new Button(this.root, SWT.PUSH);
hide2.setText("Hide column 2");
hide2.addListener(SWT.Selection, E -> {
this.updateColumn(c2, h2 = !h2);
this.resize();
});
Button hide3 = new Button(this.root, SWT.NONE);
hide3.setText("Hide column 3");
hide3.addListener(SWT.Selection, E -> {
this.updateColumn(c3, h3 = !h3);
this.resize();
});
Button hide4 = new Button(this.root, SWT.PUSH);
hide4.setText("Hide column 4");
hide4.addListener(SWT.Selection, E -> {
this.updateColumn(c4, h4 = !h4);
this.resize();
});
for(int i = 0; i < 20; i++)
{
TableItem ti = new TableItem(table, SWT.NONE);
ti.setText(new String[] {"c1:" + i, "c2:" + i, "c3" + i, "c4" + i});
}
return root;
}
protected void updateColumn(TableColumn c, boolean hide)
{
if(hide)
{
c.setResizable(false);
c.setWidth(0);
}
else
{
c.setResizable(true);
c.setWidth(300);
}
}
protected void resize()
{
this.root.getDisplay().asyncExec(() -> this.root.getShell().layout(null, SWT.ALL | SWT.CHANGED));
}

Winforms Itext Ghost Script Rectangular coordinates selection

Using C# and Winforms, I want to display a PDF, select a rectangular region, and then extract that area of text from a number of PDFs. For displaying the PDF, I have a number of options...
Use an "Adobe PDF Reader" control to display the PDF - However, I cant use mouseover events and according to https://forums.adobe.com/thread/1640606 its just not possible to select a region.
Use a "WebBrowser" control to display the PDF, but it appears I have the same issue with mouseover events and cannot select a region.
Convert the PDF to an image (using ghostscript in my case) and displaying it in a picturebox. I'm finding the most success here, as I can now generate and record the coordinates of a rectangular region. When I take these coordinates and apply them to the PDF using Itext, I don't think my rectangular region translates correctly.
My question is, How do I render the GhostScripted image in a picture box maintaining the same ratios so that my coordinates will line up with the PDF?
Thank you in advance for the down votes!!
Here is the current state of my code... Everything works with the exception that my units are off in space somewhere. The action DOES return text, but it's never the text I selected. Im sure its a combination of the coordinate system / units and I will continue to try to understand this.
---- update
With a PDF at 0 deg rotation (portrait), I think the following holds true, or is at least working for me right now... User Units having not been changed, the coordinates taken from selecting in the picturebox need adjusting. The Y coordinates need to be subtracted from the overall height while the X coordinate remains the same.
iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(first.X, 3024-first.Y, last.X, 3024-last.Y);
This is picking text up exactly as expected on 0 deg rotated PDFs. On 90 deg rotated PDFs, the X and Y coordinates just need to be swapped.I am updating the code snippet below to show my working example.
using System;
using System.Drawing;
using System.Windows.Forms;
using Ghostscript.NET.Rasterizer;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace formPdf
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string fileName; // The filename of the pdf
float width; // The width of the PDF in pixels
float hight; // the Height of the PDF in pixels
float rotation; // the Rotation of the PDF 0 or 90
float llx = 0; // The Lower Left X value for applying to the PDF
float lly = 0; // the Lower Left Y value for applying to the PDF
float urx = 0; // the Upper Right X value for applying to the PDF
float ury = 0; // the Upper Right Y value for applying to the PDF
// OnCLick event to open the file browser and select a file... The Width, Height and rotation values are set and the program
// is directed to render the First page of the pdf by calling the setPicture function
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
fileName = openFileDialog1.FileName;
PdfReader reader = new PdfReader(fileName);
iTextSharp.text.Rectangle dim = reader.GetPageSizeWithRotation(1);
width = dim.Width;
hight = dim.Height;
rotation = dim.Rotation;
setPicture(openFileDialog1.FileName);
} catch
{
// do nothing for now
}
}
}
// Using Ghostscript, the image is rendered to a picturebox. DPIs are set assuming the PDF default value is used
private void setPicture(string fileName)
{
GhostscriptRasterizer rasterizer = new GhostscriptRasterizer();
rasterizer.Open(fileName);
Image img = rasterizer.GetPage(72, 72, 1);
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
pictureBox1.Image = img;
}
// Declare point variables for the user defined rectangle indicating the locatoin of the PDF to be searched...
Point first = new Point();
Point last = new Point();
// The first point is collected on the MouseDown event
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
first = e.Location;
}
// The second point is collected on the mouse down event. Points to be applied to the PDF are adjusted based on the rotation of the PDF.
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
last = e.Location;
if (rotation == 0)
{
llx = first.X;
lly = hight - first.Y;
urx = last.X;
ury = hight - last.Y;
} else if(rotation == 90) {
llx = first.Y;
lly = first.X;
urx = last.Y;
ury = last.X;
}
gettext();
}
// the original PDF is opened with Itext and the text is extracted from t he defined location...
private void gettext()
{
PdfReader reader = new PdfReader(fileName);
iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(llx, lly, urx, ury);
RenderFilter[] renderfilter = new RenderFilter[1];
renderfilter[0] = new RegionTextRenderFilter(rect);
ITextExtractionStrategy textExtractionStrategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), renderfilter);
string text = PdfTextExtractor.GetTextFromPage(reader, 1, textExtractionStrategy);
iTextSharp.text.Rectangle mediabox = reader.GetPageSizeWithRotation(1);
MessageBox.Show("", text+" "+mediabox+" "+first+" "+last);
}
// Image Controls....
}
}

JavaFX Separator depend not on the Width of the Class

i would like to get a Separator, which changes his Size with the Size of the Mother-Component.
In my Example, i have a JavaFX Popup and there i add a VBox. To this VBox i add a HBox. And this HBox has a Label, a Speparator and a Button.
Now i would like to have that the Button is on the Right End and the Label is on the Left End of the HBox. I think i have to use a Separator between these components to get the Space.
How can i handle it...
I made something like this, but it does not work.
// Box for the Headline
HBox headLine = new HBox();
headLine.setPadding(new Insets(5, 5, 5, 5));
// Label with the HeadLine Description in
final Label heading = new Label(headLineText);
heading.getStyleClass().addAll("popup-label-name");
// Close Button
close = new Button("X");
close.setVisible(false);
closeButtonHandler();
// Creates an invisble Separator1
Separator sep = new Separator(Orientation.HORIZONTAL);
sep.setVisible(false);
sep.widthProperty().add(m_container.widthProperty().get());
close.getStyleClass().addAll("popup-button", "popup-button-color");
// Adds to the Headline the Data
headLine.getChildren().addAll(heading, sep, close);
The Variable m_container is the VBox! How can i handle it?
Thanks for your help :)
The simplest way (if not using a different container like AnchorPane) is to insert an invisible, but expandible 'space' object:
void testLabelSpace(HBox box) {
Text first = new Text("first");
Text second = new Text("second");
Node space = new HBox();
HBox.setHgrow(space, Priority.ALWAYS);
box.getChildren().addAll(first, space, second);
}
If I understand the question correctly, you just want blank space between the label and the button. Just tell the Label always to grow horizontally, and set its maximum width to allow it to grow to any size:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;
public class HBoxExample extends Application {
#Override
public void start(Stage primaryStage) {
HBox hbox = new HBox();
Label label = new Label("Label");
Button button = new Button("Button");
HBox.setHgrow(label, Priority.ALWAYS);
label.setMaxWidth(Double.MAX_VALUE);
hbox.getChildren().addAll(label, button);
primaryStage.setScene(new Scene(hbox, 350, 75));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Java3D disappearance act

It seems to me Java3D has a problem redrawing the scene sometimes when the Frame/JPanel/Canvas3D has been resized. I have a problem in my application using Java3D/JUNG3D where if the Frame/JPanel/Canvas3D's horizontal size is of certain size, the entire scene disappears. I was trying to simply the problem then found that a similar problem occurs in the following sample code: http://www.java3d.org/samples.html (The second to last example, "Text 3D Example") I will paste at the bottom for convenience.
Steps:
Install Java3D
Build this example using the 3 Java3D jars.
Run
Stretch the frame horizontally to 500 pixels or so then everything disappears. Shrink it back then it's there again. While things have disappeared, stretch vertically and things appear again.
It certainly seems to have something to do with the Frame/JPanel/Canvas3D aspect ratio and that of the content that it displays. My own problem is slightly different I'm guessing because I'm displaying scene of different aspect ratio and the underlying problem is the same. Can anyone tell me how I might be able to get around this bug/feature so that the scene never disappears when the window is resized?
Here are what I've tried so far with no success:
Catching the JPanel resize event then forcing the Canvas3D to redraw
Playing with double buffering settings
Many other things I can't recall right now - just came back from a vacation :)
Code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.geometry.*;
public class Titles {
public static void main(String[] args) {
Titles t = new Titles();
t.setUp();
}
public void setUp() {
JFrame jf = new JFrame("Welcome");
// kill the window on close
jf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent winEvent) {
System.exit(0);
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 1, 2, 2));
GraphicsConfiguration config = SimpleUniverse
.getPreferredConfiguration();
Canvas3D canvas3D = new Canvas3D(config);
canvas3D.setSize(360, 160);
SimpleUniverse universe = new SimpleUniverse(canvas3D);
BranchGroup group = new BranchGroup();
addObjects(group);
addLights(group);
universe.getViewingPlatform().setNominalViewingTransform();
universe.addBranchGraph(group);
panel.add(canvas3D);
jf.getContentPane().add(panel, BorderLayout.CENTER);
jf.pack();
jf.setVisible(true);
}
public void addLights(BranchGroup group) {
BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0),
1000.0);
Color3f light1Color = new Color3f(1.0f, 1.0f, 1.0f);
Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f);
DirectionalLight light1 = new DirectionalLight(light1Color,
light1Direction);
light1.setInfluencingBounds(bounds);
group.addChild(light1);
// Set up the ambient light
Color3f ambientColor = new Color3f(.1f, .1f, .1f);
AmbientLight ambientLightNode = new AmbientLight(ambientColor);
ambientLightNode.setInfluencingBounds(bounds);
group.addChild(ambientLightNode);
}
private void addObjects(BranchGroup group) {
Font3D f3d = new Font3D(new Font("TestFont", Font.PLAIN, 2),
new FontExtrusion());
Text3D text = new Text3D(f3d, new String("Java3D.org"), new Point3f(-3.5f,
-.5f, -4.5f));
text.setString("Java3D.org");
Color3f white = new Color3f(1.0f, 1.0f, 1.0f);
Color3f blue = new Color3f(.2f, 0.2f, 0.6f);
Appearance a = new Appearance();
Material m = new Material(blue, blue, blue, white, 80.0f);
m.setLightingEnable(true);
a.setMaterial(m);
Shape3D sh = new Shape3D();
sh.setGeometry(text);
sh.setAppearance(a);
TransformGroup tg = new TransformGroup();
Transform3D t3d = new Transform3D();
Transform3D tDown = new Transform3D();
Transform3D rot = new Transform3D();
Vector3f v3f = new Vector3f(-1.6f, -1.35f, -6.5f);
t3d.setTranslation(v3f);
rot.rotX(Math.PI / 5);
t3d.mul(rot);
v3f = new Vector3f(0, -1.4f, 0f);
tDown.setTranslation(v3f);
t3d.mul(tDown);
tg.setTransform(t3d);
tg.addChild(sh);
group.addChild(tg);
}
}
Try setting up a Buffer,Tutorial here. http://www.youtube.com/watch?v=vzfnUSLKUDs&list=ECA331A6709F40B79D
It's been 5 years but try this solution.
I tried it and it worked with lookAt() function.

Creating a closeable tab in Mono/GTK

I'm trying to create new GTK Notebook tabs that contain both a name (as a Label) and a close button (as a Button with an Image) with the following code:
Label headerLabel = new Label();
headerLabel.Text = "Header";
HBox headerBox = new HBox();
Button closeBtn = new Button();
Image closeImg = new Image(Stock.Close, IconSize.Menu);
closeBtn.Image = closeImg;
closeBtn.Relief = ReliefStyle.None;
headerBox.Add(headerLabel);
headerBox.Add(closeBtn);
headerBox.ShowAll();
MyNotebook.AppendPage(childWidget, headerBox);
This seems to work just fine; however, the button is about 1.5 - 2 times the size is needs to be, so there is a lot of extra space around the image inside the button. Having looked at remove inner border on gtk.Button I now see that the culprit is the "inner-border" style property of the GtkButton, but (being new to GTK) I can't seem to figure out how to override its value.
Is there some method of doing this that I'm missing? I don't have any reservations about not using a Button/Image combination, so any more obvious suggestions are welcome.
Note: I have seen the suggestion in the linked question to use an EventBox, but I was not able to add the Relief and mouseover effects to that Widget.
You are in luck. I just made the exact same thing yesterday, and can fortunately give you some code. The trick is to create a Custom Tab Widget.
public class MultiTab : Gtk.Box
{
public Gtk.Label Caption;
Gtk.Image img = new Gtk.Image(Platform.IMG + "tab_close.ico");
public Gtk.ToolButton Close;
public Gtk.Notebook _parent;
public MultiTab ( string name )
{
CreateUI(name);
}
public MultiTab(string name, Gtk.Notebook parent)
{
_parent = parent;
CreateUI(name);
CreateHandlers();
}
void CreateUI(string name)
{
Caption = new Gtk.Label(name);
Close = new Gtk.ToolButton(img,"");
PackStart( Caption );
PackStart( Close );
ShowAll();
Close.Hide();
}
void CreateHandlers()
{
Close.Clicked += delegate {
_parent.RemovePage(_parent.CurrentPage);
};
}
public bool Active;
}
Next all you have to do is use this widget(or a similar one created by you) in Gtk.Notebook like this:
MyNoteBook.AppendPage(new <YourPage>(), new MultiTab("<your caption>",this));
And You're done.
Here is a screenshot:
Add this:
RcStyle rcStyle = new RcStyle ();
rcStyle.Xthickness = 0;
rcStyle.Ythickness = 0;
closeBtn.ModifyStyle (rcStyle);
Add items to box using Gtk.Box.PackStart/PackEnd methods rather than generic Gtk.Container.Add method. PackStart/PackEnd will allow you control how child widgets will be allocated space:
headerBox.PackStart (headerLabel, true, true, 0);
headerBox.PackEnd (closeBtn, false, false, 0);