JTextArea is repositioning and reziseing itself - java

i just started to use Java to build a GUI. Now i ran in an error that causes very strange behaviour with the JTextArea. I used this to create the TextArea:
`
public class gui{
JTextArea ausgabe;
public gui(){
//Some other Stuff in here
//
//
ausgabe = new JTextArea("Test \n Text",15,50);
ausgabe.setSize(110, 170);
ausgabe.setVisible(true);
mainFrame.add(ausgabe);
ausgabe.setLocation(170,20);
ausgabe.setEnabled(false);
}
}
Now until this point everything just works fine. But I want another method to change the text of the area (with ausgabe.setText("String");) the area relocates itself to x,y = 0 of the JFrame and layers itself above all other JFrame elements. Thanks for help!

I highly recommend not trying to fight the Layout Managers
For a simple fix, use the default layout manager for a JFrame like so
public class gui
{
JTextArea ausgabe;
public gui()
{
ausgabe = new JTextArea("Test \n Text");
mainFrame.add(ausgabe, BorderLayout.CENTER);
}
}
You also don't need to set Swing Components other than the JFrame itself visible.
You can then call setText() in an action listener or such and the TextArea should stay in the same position.

Related

Aligning JTextFields, JLabels, and JButtons in a JPanel [duplicate]

I have the following code where I try to place a JLabel in a custom location on a JFrame.
public class GUI extends JFrame
{
/**
*
* #param args
*/
public static void main(String args[])
{
new GUI();
}
/**
*
*/
public GUI()
{
JLabel addLbl = new JLabel("Add: ");
add(addLbl);
addLbl.setLocation(200, 300);
this.setSize(400, 400);
// pack();
setVisible(true);
}
}
It doesn't seem to be moving to where I want it.
The problem is that the LayoutManager of the panel is setting the location of the label for you.
What you need to do is set the layout to null:
public GUI() {
setLayout(null);
}
This will make it so the frame does not try to layout the components by itself.
Then call setBounds(Rectangle) on the label. Like so:
addLbl.setBounds(new Rectangle(new Point(200, 300), addLbl.getPreferredSize()));
This should place the component where you want it.
However, if you don't have a really great reason to lay out the components by yourself, it's usually a better idea to use LayoutManagers to work in your favor.
Here is a great tutorial on getting started with using LayoutManagers.
If you must go without a LayoutManager here is a good tutorial for going without one.
You put the location code under the frame and it will work but if you want it to work for sure
put the location code in a run while loop. That's what I did to figure it out and it works.

JLabel Not Showing Up Besides My JText

I am not able to get how to put up a text besides my button or text fields, when I made a separate code for just the label and a text field(copied as it from the internet) it is working, but it isn't in this case, please tell me how do I make it work? I got an idea like I might have to use some frame or some layout, but is it necessary? Just the basics please. Thanks. :
public class UIClass extends JFrame {
public UIClass()
{ super("GUIPart1");
super.setBounds(50,50,1000,700);
super.setResizable(true);
super.setVisible(true);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
// Button
JButton btn1=new JButton();
btn1.setBounds(50,50, 100, 50);
super.add(btn1);
super.setLayout(null);
btn1.setText("Test");
//TextField
JTextField tf1=new JTextField(15);
super.add(new JLabel("Label :"));
super.add(tf1);
tf1.setBounds(100,100,200,200);
//OptionPane
JOptionPane text=new JOptionPane();
String Message=JOptionPane.showInputDialog("My Message");
JOptionPane.showMessageDialog(null,"Thank you");
}
public static void main(String args[])
{
UIClass u=new UIClass();
}
}
You should call
this.repaint();
at the end. I wouldn't recommend using setBounds in JavaDoc it reads:
This method changes layout-related information, and therefore, invalidates the component hierarchy.
It was shown, when you resize window. This is valid for code with
JLabel jl=new JLabel("Label : "); jl.setBounds(300,300,400,400); super.add(jl);
as you mentioned in comment...
In your original code you explicitly set container layout to null.
In this case you must specify the position and the size of every other component you add and you did it for the button and textfield components only.
The code you posted in your comment you use BorderLayout as LayoutManager which automatically resizes and positions every component according to his strategy.
I strongly reccomend you to learn how to use LayoutManagers, because they are such a critical component in the Java UI environment, at least BorderLayout and GridLayout, because if your application is not too complex they should do the trick.

Refresh java program with Button

I am trying to make a refresh button that will essentially restart the program when ever I click the button. I don't know how I should go about doing this.
I've place the Graphical User Interface i decided to use do complete this action. Any and all help would be greatly appreciated.
package pdfView;
import javax.swing.*;
import java.awt.*;
public class View extends JFrame {
public View() {
super("PDF Viewer");
setLookAndFeel();
setSize(500, 125);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
setLayout(flo);
JTextField Search = new JTextField ("Search", 29);
JButton Search1 = new JButton("Search");
//this is where i have the button
JButton ReFresh = new JButton("ReFresh");
add(Search);
add(Search1);
add(ReFresh);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.squing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc){
}
}
public static void main(String[] args) {
View pdf = new View();
}
}
What do you mean by refresh or restart?
Do you mean:
Let the application be as it is, just update what it's showing?
Really restart the application?
Updating what the application is showing
You first need to decide what actually should cause your application to refresh. You already talked about a Button. The mechanism for activating something like a button is called Action. You can do that stuff manually, using an ActionListener, or you could extend AbstractAction, which is what I recommend. Extending AbstractAction allows you to use the same logical action something in more than one location on the UI. Look at typical applications, they offer Cut/Copy/Paste through menu, toolbar, popupmenu and keyboard shortcuts. The simplest way to achieve this in Java is using Action by extending AbstractAction.
The methods you need to call to update your application are invalidate(), validate() or repaint().
Restarting an application
So you want to run through main() again? That should actually not be required, unless you have an application that supports updating itself. Even then it can sometimes be avoided by smart usage of a ClassLoader.
Some more notes on your code
Usage by extension anti-pattern
I wouldn't extend JFrame just to display a window on the screen. Usage by extension is an anti-pattern. You don't need to extend JFrame to get a JFrame displayed on the screen and do what you want.
Referring static members
I would refer to constants via their original declaration. I.e. I'd refer to EXIT_ON_CLOSE via WindowConstants.EXIT_ON_CLOSE, not JFrame.EXIT_ON_CLOSE.
Typo
You have a typo in your UIManager.setLookAndFeel() code. Search for swing and you will see the typo.
Exception information
You might actually want to print the exception to stderr using exc.printStackTrace() instead of ignoring it completely, because when you have a typo in the LaF class name, as you do, and you don't print the exception, you might actually not come to know what's going wrong.
Sequence of widget construction and UIManager.setLookAndFeel()
The sequence of UIManager.setLookAndFeel() and the effective new JFrame() via super(...) does not guarantee you that the whole UI will be in Nimbus, parts of it might still be in Metal. I recommend to set the LaF before even constructing the first widget, to be on the safe side. As far as I remember, it's not guaranteed that changing the LaF after component construction has an effect, unless you tell the UIManager to update the LaF. See also this quote from the documentation of UIManager:
Once the look and feel has been changed it is imperative to invoke updateUI on all JComponents. The method SwingUtilities.updateComponentTreeUI(java.awt.Component) makes it easy to apply updateUI to a containment hierarchy. Refer to it for details. The exact behavior of not invoking updateUI after changing the look and feel is unspecified. It is very possible to receive unexpected exceptions, painting problems, or worse.
http://docs.oracle.com/javase/8/docs/api/javax/swing/UIManager.html
setSize() vs. pack() with a little help of Insets and Border
Instead of setting the size manually, you might want to play with Insets or Border and JFrame.pack() in order to get a decent layout of your window. Setting the size manually assumes that you know a lot about the screen resolution and the font size of the user.
The pack() method performs automatic size calculation based on the contents. Insets and Border allow you to create some space and borders, even with some designs or labels, around components so they wouldn't be cramped tightly in a window but be nicely spaced.
First you have to assign an actionListener to the ReFresh Jbutton.
You can either implement the interface ActionListener to the class, and override the actionPerformed() method like this
public class View extends JFrame implements ActionListener{
private JButton ReFresh;
public View() {
super("PDF Viewer");
setLookAndFeel();
setSize(500, 125);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
setLayout(flo);
JTextField Search = new JTextField ("Search", 29);
JButton Search1 = new JButton("Search");
//this is where i have the button
ReFresh = new JButton("ReFresh");
ReFresh.addActionListener(this);
add(Search);
add(Search1);
add(ReFresh);
setVisible(true);
}
private void setLookAndFeel() { //right way for nimbus: http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/nimbus.html
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.equals(ReFresh))
{
super.repaint();
}
}}
public static void main(String[] args) {
View pdf = new View();
}
Or you can do inline assignment to addActionListener, like this
ReFresh.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
super.repaint();
}
});
You can try these methods to refresh/reload the JFrame,
invalidate();
validate();
repaint();
you can also use dispose(); and then new View(); to create the new JFrame, but in this sequence it will close the window and create new one.
or you can even try setVisible(false); then setVisible(true);
I recommend the first 3.

NetBeans & Swing - dynamically add JPanel to JDialog

I am designing an application in NetBeans, as illustrated in the screenshot below.
When the user clicks on a JButton on a JFrame, a JDialog pops-up asking the user to enter a numeric value using a numeric keypad. I would like the JDialog to dynamically add 2 JPanels. JPanel 1 will contain a textbox for input. JPanel 2 will contain a numeric keypad. I designed them this way so that I could reuse the numeric keypad whenever I need it. The problem I am facing is displaying dynamically these 2 JPanels on the JDialog that pops-up. JDialog pops-up empty. Please take a look at my code below. Thank you all, I appreciate your help
This is the sample code of JDialog:
public class MyDialog extends javax.swing.JDialog {
public MyDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {//Add JPanel 2 (Numeric Keypad) to JDialog
Container contentPane = getContentPane();
NumericKeypadPanel nkp = new NumericKeypadPanel();
nkp.setLayout(new java.awt.BorderLayout());
contentPane.removeAll();
contentPane.add(nkp);
contentPane.validate();
contentPane.repaint();
}
});
}
This is the sample code for JPanel 2 (Numeric Keypad):
public class NumericKeypadPanel extends javax.swing.JPanel {
/** Creates new form NumericKeypadPanel */
public NumericKeypadPanel() {
initComponents();//Draws 10 number buttons
}
}
basicall there are two ways
1) add a new JComponent by holding JDialog size (in pixels) on the screen, all JCompoenets
or part of them could be shrinked
2) resize JDialog by calling pack(), then JDialog will be resized
both my a.m. rulles works by using Standard LayoutManagers (excepting AbsoluteLayout)
What is in the initComponents() function of the NumericKeypadPanel? If it's not actually creating components, you're not going to see anything in the dialog. I added a single line to the NumericKeypadPanel's constructor to change the background color of this panel, and indeed, it shows up in the dialog as a green panel.
public NumericKeypadPanel() {
//initComponents();//Draws 10 number buttons
setBackground(Color.green);
}

add components to a panel in Java

I'm creating an applet which consists of a class which extends JApplet, with a menubar and a class which extends a JPanel.(So there is a menubar and a JPanel shown in the applet).
In this class I add and remove some textfields to the JPanel. This all works fine. Here's where it gets tricky: it only works the first time. When I add some new textfields to the JPanel, they are added and visible in the JPanel, but the menubar in the JFrame stops working.
Since the code is too extensive I'll only post parts of it.
Here's the code where I add the JPanel to the JApplet:
public class Simulator extends JApplet implements ItemListener, ActionListener {
Container pane = getContentPane();
canvas = new DrawCanvas();
pane.add(canvas, BorderLayout.LINE_END);
}
Here's the code of the JPanel:
class DrawCanvas extends JPanel {
public void paintComponent(Graphics g) {
if(textfield != null)
remove(textfield);
textfield = new JTextField();
this.add(textfield);
}
}
This works the first time(when nothing is removed), but the second time the menubar stops working.
When I leave out the this.add(textfield); line, the menubar keeps working.
I once had similar problems with popup menus beeing painted behind other components.
Try calling static JPopupMenu.setDefaultLightWeightPopupEnabled(false); or the setLightWeightPopupEnabled on your specific submenu. This will make (all) popup menus (i.e. submenus) to heavy weight components that have a native peer.
I believe you are running into issues with threading. Adding and removing JComponents during painting might mess up the EDT (which is calling the paint method in the first place).

Categories