String result = JOptionPane.showInputDialog(this, temp);
result value will be the inputted value.
String result = JOptionPane.showInternalInputDialog(this, temp);
result value will be null even you inputted a string.
temp is a panel that will contain in the JOptionPane. This JOptionPane will show on top of another customized JOptioPane.
JOptionPane.showInternalInputDialog is to be used with JDesktopPane/JInternalFrames only, where this is the JDesktopPane/JInternalFrames instance.
final JDesktopPane desk = new JDesktopPane();
...
String s=JOptionPane.showInternalInputDialog(desk, "Enter Name");
If not used with either of the 2 above mentioned components it will not produce the correct output, in fact it will throw a Runtime Exception:
java.lang.RuntimeException: JOptionPane: parentComponent does not have
a valid parent
UPDATE
As per your comments here is an example of how you would add JPanel to JDesktopPane and call JOptionPane#showInternalInputDialog. The important part is we need to call setBounds and setVisible on JPanel like we would as if it was JInternalFrame being added to the JDesktopPane, except of course we are adding a JPanel
JFrame frame = new JFrame("JInternalFrame Usage Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// A specialized layered pane to be used with JInternalFrames
jdpDesktop = new JDesktopPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
};
frame.setContentPane(jdpDesktop);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 600, 600);
jdpDesktop.add(panel);
frame.pack();
frame.setVisible(true);
panel.setVisible(true);
String result = JOptionPane.showInternalInputDialog(jdpDesktop, "h");
System.out.println(result);
Related
Here is part of my code:
JFrame window = new JFrame();
JPanel panel = new JPanel();
JTextArea text = new JTextArea();
JScrollPane scroll = new JScrollPane(text);
private Window()
{
createWindow();
}
public void createWindow()
{
window.setLayout(null);
window.setVisible(true);
panel.setVisible(true);
text.setBounds(20, 100, 320, 270);
}
public void update2(String employee)
{
text.setText(null);
try
{
scanner = new Scanner(employee);
}catch(Exception e){
e.printStackTrace();
}
while(scanner.hasNextLine())
{
String line = scanner.nextLine();
text.append(line+"\n");
}
revalidate();
}
I'm wondering how to add scroll bar to TextArea "text". It's a database app and it sends String of data to TextArea. I want the app to show scrollbar (vertical or horizontal) if necessary - too many Strings in TextArea. I have been trying many things but nothing works. Constructor has to be private because I'm using Singleton.
Avoid using null layouts. Take a look at Layout Managers for better options.
Unless you are not including the part where you add the Scrollpane to the JFrame, I suggest you do something similar to this
frame.add(scrollpane, BorderLayout.CENTER);
The BorderLayout.CENTER is a position in the default layout for JFrames. Read here for more.
Btw, where did you add your scroll to the Frame?
window.add(scroll);
window.setVisible (true);
JScrollPane is a container that places scrollbars around your component when its needed and also has its own layout. All you need to do when you want to wrap anything into a scroll just pass it into JScrollPane constructor:.
JFrame window = new JFrame();
JPanel panel = new JPanel();
JTextArea text = new JTextArea();
JScrollPane scroll = new JScrollPane(text);
If the above did not work, use:
JScrollPane scroll = new JScrollPane ();
scroll.getViewport ().setView ( text );
I want to create a JDialog which has a JTextField, this dialog box should start taking input from user no sooner it starts(i.e WITHOUT user having to click on it). I am calling the code using combination of key tap.So if any other app is running and I would want to pop this dialog box, i would just press the required keys.However currently, I have to click on the dialog box when it pops beacuse the present running app has the focus.Anyhelp..Thanks
//Creating a panel
JPanel panel = new JPanel( new SpringLayout() );
//creating a text field
final JTextField textfield = new JTextField(65);
// Modifying text field
Font font = new Font("SansSerif",Font.LAYOUT_LEFT_TO_RIGHT, 19);
textfield.setFont(font);
textfield.setForeground(Color.black);
textfield.setBackground(new Color(200,200,200,70)); //253,245,230
//border
textfield.setBorder(new BevelBorder(BevelBorder.LOWERED));
textfield.requestFocusInWindow();
//modifying panel
label.setLabelFor(textfield);
panel.add(textfield);
panel.setBackground(new Color(0,0,0,25));
panel.setPreferredSize(new Dimension(750,70));
panel.setBorder(new EtchedBorder(EtchedBorder.RAISED));
//Lay out the panel.
SpringUtilities.makeCompactGrid(panel,
1 , 2, //rows, cols
10, 10, //initX, initY
10, 10); //xPad, yPad
//Create and set up the Window Frame
final JDialog frame = new JDialog();
frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
//Positioning the dialog at the center of screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/4-frame.getSize().width/4, dim.height/3-frame.getSize().height/3);
//Set up the content pane.
//adding background
frame.setLayout(new SpringLayout());
frame.setUndecorated(true);
frame.add(panel);
frame.setSize(750,71);
frame.repaint();
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
frame.toFront();
frame.setAlwaysOnTop(true);
frame.repaint();
frame.setVisible(true);
}
});
frame.addWindowFocusListener( new WindowAdapter() {
public void windowOpened( WindowEvent e ){
frame.requestFocus();
}
});
Almost every line of code is not needed or in the wrong order:
frame.pack();
frame.setSize(750,71);
Well, make up your mind what are you trying to do? The pack() method is used to have the frame automatically calculate the size based on the components added to the frame. The setSize() would override the results of the pack() method. You should only pack() the frame AFTER adding all the components to the frame.
frame.repaint();
No need for the repaint(), the setVisible(true) method will make sure the frame is painted.
frame.requestFocus();
Not needed, when the frame is made visible focus will automatically go to the first component.
So the basic order of your code should be something like:
JTextField textField = new JTextField(20);
JFrame frame = new JFrame(...);
frame.add(textField, BorderLayout.PAGE_START);
frame.pack();
frame.setVisible(true);
There is no need to request focus on the text field. Focus will automatically be placed on the first component.
You may also want to take a look at the Swing tutorial on How to Make Dialogs. You can use a JOptionPane to prompt a user for text input. The tutorial has working examples.
field = new JTextField(40);
f.addWindowListener( new WindowAdapter() {
public void windowOpened( WindowEvent e ){
field.requestFocus();
}
});
What are you doing here?
There is no textfield show in your code. All you have is a dialog... Do you need help making a textfield? How to add components to JDialog
Then after you make a text field select it by using textField.requestFocusInWindow()
or look at this post to help, Java Textfield focus
For some reason even though I have implemented the validate method in my code, and added my JPanel to my JFrame. I am also trying to get my JLabel to have Comic Sans font and for it to be centered in the screen. Why is my JLabel not showing up on my JPane
package math_program;
import java.awt.Color;
import java.awt.Font;
import java.util.Random;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class Canvas
{
Images obj = new Images();
public void paintFrame()
{
//Instantiation of objects
Random gen = new Random();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
//Text
JLabel problem = new JLabel();
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //Make frame actually closeable
frame.setTitle("Math Owl: Alpha V:0.1 (coded by John)");
frame.setSize(800, 500);
frame.setLocationRelativeTo(null);
frame.add(panel); //Add JPanel to JFrame
panel.setVisible(true);
panel.setLayout(null);
panel.setBackground(Color.WHITE); //To see if text is even appearing
//Adding Components
problem.setFont(new Font("Comic Sans MS", Font.PLAIN, 20));
problem.setLocation(400,250);
problem.setText(gen.nextInt(11) + " + " + gen.nextInt(11));
panel.add(problem);
panel.validate();
}
}
Use a proper Layout Manager just as copeg said. Even the default Layout Manager (Flow Layout) will work. Just remove panel.setLayout(null); and your JLabel will show up.
Also when I try your snippet code there also problem on Images obj = new Images(); I assume you already have the Images class defined in your package somehow.
`
//frame.add(panel);
frame.setContentPane(panel);
//panel.setVisible(true); // not necessary code
//panel.setLayout(null); // not necessary code
panel.setBackground(Color.WHITE); //To see if text is even appearing
frame.getContentPane().add(problem);
The problem is that with null layout, you have to set both the location and the size of each component. You set only the location of the label, so you can fix it with problem.setSize(x, y);. With that being said, it's just wrong to take this approach. See what your whole GUI design for this frame looks like and choose an appropriate LayoutManager.
Try this:
public class MyCanvas {
public MyCanvas() {
Random gen = new Random();
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel problem = new JLabel();
panel.setBackground(Color.WHITE);
problem.setFont(new Font("Comic Sans MS", Font.PLAIN, 20));
problem.setText(gen.nextInt(11) + " + " + gen.nextInt(11));
panel.add(problem); // Default FlowLayout
frame.add(panel); // Default BorderLayout at position CENTER
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Math Owl: Alpha V:0.1 (coded by John)");
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new MyCanvas();
}
}
Notes:
frame.setVisible(true) should be the last call you make.
frame.setAlwaysOnTop(true) and frame.setResizable(false) are things you usually want to avoid from the user's perspective.
frame.setSize(...) should be replace with frame.pack().
frame.setLocationRelativeTo(null) should be called between pack() and setVisible(true).
No need for panel.setVisible(true), it does nothing for you.
No need for panel.validate() (should be revalidate()), it is only needed when changing the layout during runtime.
The class Canvas already exists, use a different name.
There two way
is you are using any layout manager then you can simply show the component by using setSize(new Dimension(width, height)
if you have set the layout manager to null then you must use
setBounds(x,y, width, height) (if you do this obviously no need to set size) to show the component
otherwise just do
setSize(new Dimension(width,height)
then setLocation(x,y)
if you want to dynamically calculate the position then you can set the initial locaion as setLocation(0,0)
afterwards when all the components are showing you can use your algorithm to recalculate x and y position and again setLocation(x,y)
for e.g.
label1=setSize(new Dimension(100,20)
label1.setLocation(0,0)
Label2=setSize(new Dimension(100,20)
Label2.setLocation((int)label1.getSize().getWidth()+10,20) and so on
I want to do a dynamic form in Swing. When I call firstly the dataShow method, it creates the GUI. But when I call it again, it keeps the old panel and display the new at the background.
And when I try to remove the current panel, and then add the new. The GUI became empty
A Thread listen to events (int id in that case).
here is my code to display the dynamic form :
public void showData(int id) throws DAOException, ClassNotFoundException{
FormDAOImpl form = new FormDAOImpl();
String b = form.importTagPoint(id);
//if(compteur%2 == 0) {System.out.println("Compteur : " +compteur); scrollPane.remove(panel);
//frame.getContentPane().remove(scrollPane);
//}
panel = new JPanel(new MigLayout());
if(b == null) b = "";
String[] bits = b.split("\\,");
String delims = "[=]";
while(i<bits.length){
textField = new JTextField();
String[] bitsS = bits[i].split(delims);
textField.setText(bitsS[1]);
JLabel label = new JLabel(bitsS[0]+ " : ");
panel.add(label);
panel.add(textField, "span, grow, alignx center, flowx");
i++;
}
JButton annuler = new JButton("Annuler");
JButton enregistrer = new JButton("Enregistrer");
panel.add(annuler);
panel.add(enregistrer);
panel.revalidate();
panel.repaint();
scrollPane = new JScrollPane(panel);
scrollPane.revalidate();
scrollPane.repaint();
frame.getContentPane().add(scrollPane);
//frame.repaint();
frame.invalidate();
frame.validate();
frame.repaint();
frame.pack();
frame.setMaximumSize(new Dimension(300, 800));
compteur++;
}
First, try calling frame.getContentPane().removeAll() to remove anything that was previously added to it. Obviously do this before you add anything new to it.
Second, try and devise a solution where you don't need to do this, but maintain a single view which can be updated via setters and getters if possible.
If you are literally changing views (show the user something complete different), consider using a CardLayout or JTabbedPane instead
What I am trying to do is add two X by 2 grid panels in the first row of a 2x2 grid content panel, leaving the bottom row of the content panel blank.
To populate the cells on the top row I want to use a function which uses a loop to generate a text field and a slider. the text field calling it's input from textList[n].
So this breaks down into two primary questions.
If I have a function:
public static void makeTop(String textName) {
JTextField textBox = new JTextField(textName);
textBox.setPreferredSize(new Dimension(100,50));
textBox.setHorizontalAlignment(JTextField.CENTER);
textBox.setEditable(false);
SpinnerNumberModel numSpinner = new SpinnerNumberModel(10,0,100,1);
JSpinner spinner = new JSpinner(numSpinner);
spinner.setPreferredSize(new Dimension(100,50));
}
And a frame w/ panel:
public static void main(String[] args) {
JFrame frame = new JFrame("Frame");
frame.getContentPane().setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel cPane = new JPanel((new GridLayout(2,2)));
frame.add(cPane, BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
How could I add the text field and spinner created in makeTop to cPane?
cPane.add() doesn't like function calls, and making cPane public didn't seem to help when trying to add the content in makeTop().
Secondly, let's say makeTop is called as follows, with N being arbitrary and textList[] being populated with Strings:
for(i=N;i>0;i--){
makeTop(textList[i]);
}
How could I get the text fields and sliders to be unique instances when creating them in such a way?
cPane.add doesn't like function calls, and making cPane public didn't
seem to help when trying to add the content in makeTop()
It won't work, indeed, because by contract makeTop(String textName) is returning void. But if you make this change:
public static JPanel makeTop(String textName){
JTextField textBox = new JTextField(textName);
textBox.setPreferredSize(new Dimension(100,50));
textBox.setHorizontalAlignment(JTextField.CENTER);
textBox.setEditable(false);
SpinnerNumberModel numSpinner = new SpinnerNumberModel(10,0,100,1);
JSpinner spinner = new JSpinner(numSpinner);
spinner.setPreferredSize(new Dimension(100,50));
JPanel panel = new JPanel(new FlowLayout());
panel.add(textBox);
panel.add(spinner);
return panel;
}
Then cPane.add(makeTop("Whatever")); will work like a charm.