In java, when I use a TitledBorder around a JTextField, part of the JTextField spills over the TitledBorder in all directions. Is there a way to prevent this?
If you replace the border of the textfield with a TitledBorder you lose the natural border of the field. The solution is to create a CompoundBorderthat combines the TitledBorder with the border of the field:
JTextField field = new JTextField(10);
field.setBorder(new CompoundBorder(BorderFactory.createTitledBorder("Title"), field.getBorder()));
However the TitledBorder still inherits the background color of the textfield.
Another solution is to embed the textfield in a JPanel and put the TitledBorder on the panel:
JTextField field = new JTextField(10);
JPanel borderPanel = new JPanel();
borderPanel.setBorder(BorderFactory.createTitledBorder("Title"));
borderPanel.add(field);
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AA
{
public static void main(String[] args)
{
FrameCreator Frame= new FrameCreator();
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setVisible(true);
}
}
class FrameCreator extends JFrame
{
public FrameCreator()
{
int height=100;
int width=300;
setSize(width,height);
setLocation(0,0);
setTitle("TextField example");
showPanel=new JPanel();
textFieldPanel=new JPanel();
label=new JLabel("Sentence");
label.setFont(new Font("Serif",Font.PLAIN,12));
showPanel.add(label);
add(showPanel, BorderLayout.CENTER);
textfield=new JTextField("Sentence", 20);
textfield.setBorder(BorderFactory.createTitledBorder("Name"));
textfield.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent evento1)
{
String sentence=textfield.getText();
label.setText(sentence);
}
});
textFieldPanel.add(textfield);
add(textFieldPanel, BorderLayout.SOUTH);
}
JLabel label;
JPanel showPanel, textFieldPanel;
String sentence;
JTextField textfield;
}
I have used textfield.setBorder(BorderFactory.createTitledBorder("Name"));
Related
I have been trying to pass the info of my JTextField that is in a JDialog into my JFrame. Both the JDialog and JFrame are in separate classes. I have tried to store the JTextField into a JLable using the .setText and .getText and then passing the JLable into the JFrame but with no luck.
I know there are many similar questions but I have tried many different approaches but still no luck. I am relatively new to Java and do not know all the in's and out's. Any help is very appreciated!
My code for the JFrame:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JPanel;
public class StockApp extends JFrame implements PropertyChangeListener {
private JPanel main = new JPanel();
private JPanel north = new JPanel();
private JPanel center = new JPanel();
private JPanel south = new JPanel();
private JButton buyStock = new JButton("Buy Stock");
private JButton sellStock = new JButton("Sell Stock");
public TestTest variables = new TestTest();
private JLabel stockNameNorth = new JLabel("Stock Name");
private JLabel stockPriceNorth = new JLabel("Stock Price");
String stockName = variables.getStockName();
String stockPrice = variables.getStockPrice();
public StockApp() {
setTitle("StockApp");
getContentPane().setBackground(Color.white);
setSize(400,400);
setLocation(500,200);
setVisible(true);
main.setLayout(new BorderLayout());
north.setLayout(new FlowLayout());
center.setLayout(new FlowLayout());
south.setLayout(new FlowLayout());
stockNameNorth.setText(stockName);
stockPriceNorth.setText(stockPrice);
add(main);
north.add(stockNameNorth);
north.add(stockPriceNorth);
south.add(buyStock);
south.add(sellStock);
main.add(north, BorderLayout.NORTH);
main.add(center, BorderLayout.CENTER);
main.add(south, BorderLayout.SOUTH);
}
}
And Dialog:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestTest extends JDialog implements ActionListener {
private JPanel main = new JPanel();
private JPanel north = new JPanel();
private JPanel center = new JPanel();
private JPanel south = new JPanel();
private JLabel stockNameLabel = new JLabel("Stock name: ");
private JLabel stockPriceLabel = new JLabel("Stock price(£): ");
private JTextField stockNameIn = new JTextField(5);
private JTextField stockPriceIn = new JTextField(5);
private JButton buttonOK = new JButton("OK");
public JLabel stockPrice = new JLabel();
public JLabel stockName = new JLabel();
public TestTest() {
getContentPane().setBackground(Color.white);
setSize(400,400);
setLocation(500,200);
setModal(false);
setVisible(true);
getRootPane().setDefaultButton(buttonOK);
main.setLayout(new BorderLayout());
north.setLayout(new FlowLayout());
center.setLayout(new FlowLayout());
south.setLayout(new FlowLayout());
add(main);
north.add(stockNameLabel);
north.add(stockNameIn);
center.add(stockPriceLabel);
center.add(stockPriceIn);
south.add(buttonOK);
main.add(north, BorderLayout.NORTH);
main.add(center, BorderLayout.CENTER);
main.add(south, BorderLayout.SOUTH);
buttonOK.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonOK){
stockName.setText(stockNameIn.getText());
stockPrice.setText(stockPriceIn.getText());
dispose();
new StockApp();
}
}
public String getStockName() {
return stockNameIn.getText();
}
public String getStockPrice() {
return stockPriceIn.getText();
}
}
I am trying to pass the stockName and stockPrice variables from the JDialog into the JFrame. I then want the name and price to display at the top of the JFrame.
For demonstration, what the problem is, we need less Fields and Buttons.
So far, no component of StockApp needs to be accessed from different methods, so there is no need to make them visible outside of the ctor.
More explanations in the code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
public class StockApp extends JFrame {
public StockApp() {
// move those unreferenced panels here, so we don't have to reason about them:
JPanel main = new JPanel();
JPanel north = new JPanel();
JPanel center = new JPanel();
JPanel south = new JPanel();
// add price later, when name works
JButton buyStock = new JButton("Buy Stock");
JLabel stockNameNorth = new JLabel("Stock Name");
// critical change: Make the label, which you like to update,
// accessible by whom it should be updated:
TestTest variables = new TestTest (stockNameNorth);
setTitle ("StockApp");
getContentPane().setBackground(Color.white);
setSize (600,400);
setLocation (500,200);
setVisible (true);
// make the close-frame action terminate the program:
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
main.setLayout (new BorderLayout());
north.setLayout (new FlowLayout());
center.setLayout (new FlowLayout());
south.setLayout (new FlowLayout());
add (main);
north.add (stockNameNorth);
south.add (buyStock);
main.add (north, BorderLayout.NORTH);
main.add (center, BorderLayout.CENTER);
main.add (south, BorderLayout.SOUTH);
}
// Main method to start the damn thing
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new StockApp ();
}
});
}
}
// no need to make this class public in a short test:
class TestTest extends JDialog implements ActionListener {
// this are elements, visible outside the construction phase,
// we need to have access to from more than one method.
// Make this important distinction visible to the reader:
JLabel name;
JTextField stockNameIn = new JTextField (5);
JButton buttonOK = new JButton ("OK");
// add the JLabel to update to the ctor, so that it can't be forgotten
// to be set
public TestTest (JLabel pname) {
// we copy the reference to the label, to have access to it in
// the actionPerformed method.
name = pname;
JPanel main = new JPanel();
JPanel north = new JPanel();
JPanel center = new JPanel();
JPanel south = new JPanel();
JLabel stockNameLabel = new JLabel ("Stock name: ");
getContentPane().setBackground(Color.white);
// different size/location than frame, so that they don't hide
// each other completly
setSize (400,600);
setLocation (700,300);
setModal (false);
setVisible (true);
getRootPane().setDefaultButton(buttonOK);
main.setLayout (new BorderLayout());
north.setLayout (new FlowLayout());
center.setLayout (new FlowLayout());
south.setLayout (new FlowLayout());
add (main);
north.add (stockNameLabel);
north.add (stockNameIn);
south.add (buttonOK);
main.add (north, BorderLayout.NORTH);
main.add (center, BorderLayout.CENTER);
main.add (south, BorderLayout.SOUTH);
buttonOK.addActionListener(this);
}
// here we need access to the button - was it the OK-Button, clicked?
// and the textfield stockNameIn, to read the text
// and the name field from the frame, to set the text
public void actionPerformed(ActionEvent e) {
if (e.getSource () == buttonOK) {
name.setText (stockNameIn.getText());
dispose();
}
}
}
I'm trying to create a simple 500x500 applet with a button, 2-label, and textfield. The applet opens up but it is just blank no components are displaying nor will the color change. Not sure what is happening or what I'm missing exactly.
import java.applet.*;
import java.awt.Color;
import javax.swing.*;
public class Greeting {
private JFrame frame;
private JPanel panel;
private JLabel label1;
private JTextField textbox1;
private JButton button1;
private JLabel label2;
public Greeting(){
gui();
}
public void gui(){
frame = new JFrame("Greeting");
frame.setVisible(true);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel = new JPanel();
panel.setBackground(Color.YELLOW);
label1 = new JLabel ("Please enter your name");
textbox1 = new JTextField(20);
button1 = new JButton ("Greet");
panel.add(label1);
panel.add(button1);
panel.add(textbox1);
frame.getContentPane().add(panel);
frame.add(panel);
}
public static void main(String[] args) {
new Greeting();
}
}
If you are planning on displaying frame with all the components, then move the frame.setVisible(true) line to the end of the method:
public void gui() {
...
frame.add(panel);
frame.setVisible(true);
}
This allows for all the components to be added to the JFrame before it is displayed on the screen.
I am using the following code for placing labels inside a JPanel, but the JPanel is not appearing (instead, only a blank JFrame is appearing).
Below is the class creating a JFrame instance.
import java.awt.FlowLayout;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args){
WindowContents window = new WindowContents();
window.setSize(600, 400);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Below is the class for setting the contents of the JFrame.
import javax.swing.*;
import java.awt.*;
public class WindowContents extends JFrame {
JLabel label1;
JLabel label2;
JLabel label3;
JPanel panel1;
public WindowContents(){
super("Label Display 2.0");
panel1 = new JPanel();
panel1.setLayout(new FlowLayout(FlowLayout.CENTER, 40, 40));
panel1.setVisible(true);
label1 = new JLabel("Label1");
panel1.add(label1);
label2 = new JLabel("Label2");
panel1.add(label2);
label3 = new JLabel("Label3");
panel1.add(label3);
}
}
Are there any ideas how to make the JPanel contents appear? Thank you.
how to make the JPanel contents appear?
Add panel in the frame.
public WindowContents(){
super("Label Display 2.0");
panel1 = new JPanel();
...
add(panel1);
}
Note:
Use frame.pack() instead of frame.setSize() that fits the components as per component's preferred size.
There is no need to call panel1.setVisible(true);
Just call frame.setVisible(true) in the end after adding all the component.
Favor Composition over inheritance. Instead of extending JFrame make it as member of WindowContents class.
Use SwingUtilities.invokeLater() or EventQueue.invokeLater() to make sure that EDT is initialized properly.
you haven't added the panel to the frame, here's how your class WindowsContents end:
class WindowContents extends JFrame {
JLabel label1;
JLabel label2;
JLabel label3;
JPanel panel1;
public WindowContents(){
super("Label Display 2.0");
panel1 = new JPanel(new FlowLayout(FlowLayout.CENTER, 40, 40));
label1 = new JLabel("Label1");
panel1.add(label1);
label2 = new JLabel("Label2");
panel1.add(label2);
label3 = new JLabel("Label3");
panel1.add(label3);
add(panel1);
}
}
Cheers
I am making a program that includes a GUI. For some reason, the JButton objects that I have created are not showing up onto my JFrame when I run the program. Here is the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ReverseAStringMain extends JPanel {
private JButton enterButton, exitButton;
private JTextField textField;
private JPanel buttonPanel;
private JTextArea textArea;
public ReverseAStringMain(){
JButton enterButton = new JButton("Enter");
JButton exitButton = new JButton("Exit");
enterButton.setPreferredSize(new Dimension(60,60));
exitButton.setPreferredSize(new Dimension(60,60));
ButtonListener listener = new ButtonListener();
enterButton.addActionListener(listener);
exitButton.addActionListener(listener);
buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(200,50));
buttonPanel.setBackground(Color.black);
buttonPanel.add(enterButton);
buttonPanel.add(exitButton);
textField = new JTextField();
textField.setSize(200, 100);
textArea = new JTextArea();
textArea.add(textField);
add(buttonPanel);
add(textField);
}
//Creating a ButtonListener class that implements the ActionListener interface
private class ButtonListener implements ActionListener{
#Override
//Overriding the ActionPerformed method of ActionListener
public void actionPerformed(ActionEvent action) {
if(action.getSource()== enterButton)
enterButton();
if(action.getSource()== exitButton)
System.exit(0);
}
}
private void enterButton() {
// TODO Auto-generated method stub
}
public static void main (String[] args){
JFrame frame = new JFrame("Raj's Reverse a String Program");
frame.setBackground(Color.white);
frame.setVisible(true);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setSize(new Dimension(600,600));
//frame.pack();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReverseAStringMain());
}
}
If there are any problems or improvements I can make in my code, please let me know!
You're adding the components to your JFrame after it's visible. You should either add them to the JFrame before it's visible, or revalidate the JFrame after you add the components.
When I load your code (after making it a lot shorter in height), this is what I see:
I suspect this is more along the lines of what you expect to see.
Here is how I did it. Look carefully at:
The numbers provided to the BorderLayout constructor for white space between the panels.
The EmptyBorder for white space around the controls.
The use of pack() to shrink the GUI to the natural size.
The use of size hints in the construction of the text field and text area.
The use of a second layout - commonly known as a combined, or nested, layout.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ReverseAStringMain extends JPanel {
private JButton enterButton, exitButton;
private JTextField textField;
private JPanel pageTopPanel;
private JTextArea textArea;
public ReverseAStringMain(){
super(new BorderLayout(10,10));
setBorder(new EmptyBorder(5,15,5,15));
JButton enterButton = new JButton("Enter");
JButton exitButton = new JButton("Exit");
pageTopPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
pageTopPanel.setBackground(Color.black);
pageTopPanel.add(enterButton);
pageTopPanel.add(exitButton);
textField = new JTextField(5);
pageTopPanel.add(textField);
textArea = new JTextArea(4,40);
add(pageTopPanel, BorderLayout.PAGE_START);
add(textArea); // defaults to CENTER
}
public static void main (String[] args){
Runnable r = new Runnable() {
public void run() {
JFrame frame = new JFrame("XXX's Laid out Program");
frame.setBackground(Color.white);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReverseAStringMain());
frame.pack();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
General Tips
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.
Generally, you want to set the frame visible After adding components
JFrame frame = new JFrame("Raj's Reverse a String Program");
frame.setBackground(Color.white);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setSize(new Dimension(600,600));
//frame.pack();
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ReverseAStringMain());
frame.setVisible(true); <<------
Also, it is better practice to use .pack() insteack of .setSize(), so you had it right in the commented out //.pack()
If you wanted to set a size to the panel, you would override the getPreferredSize() like this
public Dimension getPreferredSize() {
return new Dimension(300, 300); // or whatever size you want
}
When you .pack(), this preferred size will be respected by the frame.
Also, not, setting the size of the JTextField won't work. What you want to do is pass it an integer value for the number of character spaces, like this
textField = new JTextField(20);
See an edited version of your program, with all the above mentioned points. One thing I also did was get rid of all your .setPreferredSizes. You will see the difference
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ReverseAStringMain extends JPanel {
private JButton enterButton, exitButton;
private JTextField textField;
private JPanel buttonPanel;
private JTextArea textArea;
public ReverseAStringMain() {
JButton enterButton = new JButton("Enter");
JButton exitButton = new JButton("Exit");
//enterButton.setPreferredSize(new Dimension(60, 60));
//exitButton.setPreferredSize(new Dimension(60, 60));
ButtonListener listener = new ButtonListener();
enterButton.addActionListener(listener);
exitButton.addActionListener(listener);
buttonPanel = new JPanel();
//buttonPanel.setPreferredSize(new Dimension(200, 50));
buttonPanel.setBackground(Color.black);
buttonPanel.add(enterButton);
buttonPanel.add(exitButton);
textField = new JTextField(20);
//textField.setSize(200, 100); /// <<-----------
textArea = new JTextArea();
textArea.add(textField);
add(buttonPanel);
add(textField);
}
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
// Creating a ButtonListener class that implements the ActionListener
// interface
private class ButtonListener implements ActionListener {
#Override
// Overriding the ActionPerformed method of ActionListener
public void actionPerformed(ActionEvent action) {
if (action.getSource() == enterButton)
enterButton();
if (action.getSource() == exitButton)
System.exit(0);
}
}
private void enterButton() {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
JFrame frame = new JFrame("Raj's Reverse a String Program");
frame.setBackground(Color.white);
frame.getContentPane().add(new ReverseAStringMain());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Have a look at the Swing tutorial trail for more information on creating GUIs with Swing.
Try to add the buttonPanel to a Container, like this. And extend JFrame instead
Container contentpane = getContentPane();
contentPane.add(buttonPanel);
I am creating a GUI using Netbeans and my question is "how to remove the jpanel"...the hierarchical order as it is present Jframe->Jscrollpane->Jpanel->Jbutton. By clicking on the Jbutton I want to remove all components of the jpanel including the Jbutton(on which I am clicking) and the panel itself. Please do help.Urgent.THanks in advance
-Sayantan
private void b4ActionPerformed(java.awt.event.ActionEvent evt) {
final JPanel jp;
JTextField tf,of1,of2,xf,yf;
int i=1;
int m=(int)sp3.getValue();
JButton jb;
jp=new JPanel();
//jp.setLayout(new GridBagLayout());
DesignGridLayout layout = new DesignGridLayout(jp);
jsp2.getViewport().add(jp);
while(i<=m){
tf=new JTextField(5);
of1=new JTextField(5);
of2=new JTextField(5);
layout.row().grid(new JLabel("Type:")).indent(9).add(tf).grid(new JLabel("Length:")).indent().add(of1).grid(new JLabel("Breadth:")).indent().add(of2).empty();
fields1.add(tf);
fields1.add(of1);
fields1.add(of2);
xf=new JTextField(5);
yf=new JTextField(5);
layout.row().grid(new JLabel("X-axis:")).indent(9).add(xf).grid(new JLabel("Y-axis:")).indent().add(yf).empty(2);
fields1.add(xf);
fields1.add(yf);
i++;
}
jb=new JButton("Submit");
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
for(JTextField field: fields1){
String s=field.getText();
lbr.setText(lbr.getText()+s);
}
lb3.setVisible(false);
sp3.setVisible(false);
b4.setVisible(false);
//jp.setVisible(false);
//jp.removeAll();
// jp.revalidate();
//jp.repaint();
// jsp2.remove(jp);
//jsp2.revalidate();
//jsp2.repaint();
}
});
layout.emptyRow();
layout.row().right().add(jb);
jp.revalidate();
jp.repaint();
// jsp2.revalidate();
//jsp2.repaint();
}
Note: I am using DesignGridLayout package.
This works:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ScratchSpace {
public static void main(String[] args) {
final JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.YELLOW);
panel.add(new JButton(new AbstractAction("Kill me") {
#Override
public void actionPerformed(ActionEvent e) {
panel.removeAll();
panel.revalidate();
panel.repaint();
}
}));
final JFrame frame = new JFrame();
frame.setContentPane(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I want to remove all components of the jpanel including the Jbutton(on which I am clicking) and the panel itself.
Then you need code something like:
JButton button = (JButtton)event.getSource();
JPanel grandparent = button.getParent().getParent();
grandparent.removeAll();
grandparent.revalidate();
grandparent.repaint();
Although I question any code where I see a removeAll(). You might look into using a Card Layout.