So I am a having a problem regarding my JTextField.
What I'm trying to do is to put the JTextField box below the picture(map of a certain town).
Yeah, I used .setBounds and it was already below the image, but what I want to happen is that if I do .pack();, it must be still visible. Unfortunately, it wasn't.
I tried using the .setBorder(BorderFactory.createEmptyBorder(5,50,0,50)); and I saw that the box is below the picture but it is no longer available for putting a text.
And to conclude, I want the JTextField below the picture and still must be visible whenever I pack it.
Please Help. Thank you.
I am still on the stage of discovering new things about GUI.
Sorry for the noob question.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
class ProgDraftMain {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
ProgDraft gui = new ProgDraft();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setResizable(false);
gui.pack();
//gui.setSize(1000 , 1000);
gui.setVisible(true);
}
});
}
}
class ProgDraft extends JFrame {
private ImageIcon image1;
private JLabel label1;
private JTextField textField1;
ProgDraft() {
/***Panel**/
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.LEADING));
/***Title***/
JLabel title = new JLabel("Perimeter Check", JLabel.CENTER);
Font font = new Font("Gigi", Font.BOLD, 50);
title.setFont(font);
/***Image***/
ImageIcon pics = new ImageIcon(getClass().getResource("antipolo.png"));
JLabel logo = new JLabel(pics);
logo.setBorder(BorderFactory.createEmptyBorder(10, 70, 0, 50));
logo.setToolTipText("Ito raw kunware yung barangay.");
panel.add(logo);
/***Info ANtipolo***/
String text = "Ito kunware ang ANtipolo" + "<br>" +
"Marami ditong landslide areas" + "<br>" + "<br>" +
"Take care and stay safe!" + "<br>" +
"I love my dogs" + "<br>" + "<br>" +"<br>" +
"Please help!";
JLabel dog = new JLabel("<html><div style=\"text-align: center;\">" + text + "</html>");
dog.setBorder(BorderFactory.createEmptyBorder(5,50,0,50));
panel.add(dog);
/***JTextFieldski**/
JTextField textField = new JTextField(6);
textField.setBorder(BorderFactory.createEmptyBorder(5,50,0,50));
textField.setBounds(210,470,100,25);
panel.add(textField);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(textField, BorderLayout.SOUTH);
getContentPane().add(dog, BorderLayout.CENTER);
getContentPane().add(panel, BorderLayout.SOUTH);
getContentPane().add(title, BorderLayout.NORTH);
}
}
I think you took my advice yesterday about using EmptyBorder a little too far. You are trying to use it for pixel perfect position. That's not what they're meant for. Don't worry about pixel perfect positioning. Like I said yesterday, learn the layout managers and make use of them. Also you can wrap components in panels with different layout managers and nest the panels. You don't have to try and get everything perfect on one panel. Different layout managers have different features and qualities.
For instance What you are trying to do is add two different components to the BorderLayout.SOUTH. The thing about BorderLayout is each position can only have one components. The last one added wins. So what can we do? How about wrapping the two in a panel, then adding that panel to the SOUTH :-) Easy right?
Also in regards to the EmptyBorders, Make use the the JLabel api. You can setHorizontalAlignment to JLabel.CENTER. The default is JLabel.LEADING, so all the text is to the left. If you set it to the center, then it will be centered.
Also just FYI, setBounds will not work unless you are using null layouts, which I advise against. You don't use it.
Here is the refactor (using NO Empty Borders, letting the layout managers do the job we pay them to do)
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
class ProgDraftMain {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ProgDraft gui = new ProgDraft();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setResizable(false);
gui.pack();
//gui.setSize(1000 , 1000);
gui.setVisible(true);
}
});
}
}
class ProgDraft extends JFrame {
private ImageIcon image1;
private JLabel label1;
private JTextField textField1;
ProgDraft() {
/**
* Main Panel
*/
JPanel mainPanel = new JPanel(new BorderLayout());
/**
* *Title**
*/
JLabel title = new JLabel("Perimeter Check", JLabel.CENTER);
Font font = new Font("Gigi", Font.BOLD, 50);
title.setFont(font);
mainPanel.add(title, BorderLayout.PAGE_START); // add title to top
/**
* *Info ANtipolo**
*/
String text = "Ito kunware ang ANtipolo" + "<br>"
+ "Marami ditong landslide areas" + "<br>" + "<br>"
+ "Take care and stay safe!" + "<br>"
+ "I love my dogs" + "<br>" + "<br>" + "<br>"
+ "Please help!";
JLabel dog = new JLabel("<html><div style=\"text-align: center;\">" + text + "</html>");
dog.setHorizontalAlignment(JLabel.CENTER);
mainPanel.add(dog); // add dog to center
/**
* *Image** ==========>>>>>> Make sure to change the image name back.
*/
ImageIcon pics = new ImageIcon(getClass().getResource("stackoverflow.png"));
JLabel logo = new JLabel(pics);
logo.setHorizontalAlignment(JLabel.CENTER);
//logo.setBorder(BorderFactory.createEmptyBorder(10, 70, 0, 50));
logo.setToolTipText("Ito raw kunware yung barangay.");
/**
* Wrapper for text field and icon
*/
JPanel iconFieldPanel = new JPanel(new BorderLayout());
JTextField textField = new JTextField(10);
iconFieldPanel.add(logo);
iconFieldPanel.add(textField, BorderLayout.PAGE_END);
JPanel iconFieldWrapper = new JPanel();
iconFieldWrapper.add(iconFieldPanel);
mainPanel.add(iconFieldWrapper, BorderLayout.PAGE_END); // add icon and field to bottom
getContentPane().add(mainPanel);
}
}
And pleeease do take some time to go over the link I provided for using layout managers. Study one at a time and get the hang of each. It's an art, so it'll take time, just like anything else.
Related
In my code i transfer the JPanel (Bestellpanel) from frame to frame1. After that, everytime i use the frame1 scrollbar it repaints frame1and my JPanel (Bestellpanel) is gone. That means I need a way to stop my JPanel getting overpainted. I read something about super.paint(); and other methods but I have major problems understanding them.
Here is a code example of my problem:
import java.awt.Color;
import javax.swing.JPanel;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class weqe {
private static JFrame frame = new JFrame("First Frame");
private static JFrame frame1 = new JFrame("Second Frame");
private static JPanel Bestellpanel = new JPanel();
private static int kunde = 1;
public static void addComponentsToPane(final Container pane) {
pane.setLayout(null);
final Insets insets1 = pane.getInsets();
// Mitn Button
JButton MitnIcon = new JButton("Mitnehmen");
MitnIcon.setFocusPainted(false);
MitnIcon.setVisible(true);
Dimension size2 = MitnIcon.getPreferredSize();
MitnIcon.setBounds(1010 + insets1.left, 700 + insets1.top,
size2.width + 27, size2.height + 50);
pane.add(MitnIcon);
MitnIcon.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (kunde == 1) {
frame.getContentPane().remove(Bestellpanel);
Bestellpanel.setLocation(0, 0);
frame1.getContentPane().add(Bestellpanel);
Bestellpanel.repaint();
frame.repaint();
}
}});
// ScrollPane
JPanel panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(2000,800));
panel1.setVisible(false);
JScrollPane scrollPane = new JScrollPane (panel1,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
frame1.add(scrollPane);
Bestellpanel.setBounds(930 + insets1.left, 50 + insets1.top,size2.width
+ 30, size2.height + 400);
Bestellpanel.setVisible(true);pane.add(Bestellpanel);
Bestellpanel.setBackground(Color.green);
}
private static void createAndShowGUI() {
//Create and set up the window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
//Size and display the window.
Insets insets = frame.getInsets();
Insets insets1 = frame1.getInsets();
frame.setSize(1200 + insets.left + insets.right,
900 + insets.top + insets.bottom);
frame.setVisible(true);
frame1.setSize(800 + insets1.left + insets1.right,
600 + insets1.top + insets1.bottom);
frame1.setVisible(true);
frame.add(Bestellpanel);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
meinJDialog.setSize(800,800); and panel1.setPreferredSize(new Dimension(2000,800)); most likely are part of your problem, see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? (The general consensus says yes and to override getPreferred|Maximum|MinimumSize() methods instead)
Instead of removing/adding the JComponents yourself, try out Card Layout
You don't need to manually change component's visibility, again, check the link in point number 2, for this line: Bestellpanel2.setVisible(true);
Please follow the Java naming conventions: FirstWordUpperCaseClass, firstWordLowerCaseVariable, firstWordLowerCaseMethod() and ALL_WORDS_UPPER_CASE_CONSTANT), so, your code is easier to read and understand for you and for us.
If all the above points don't work, then consider posting a valid Minimal, Complete and Verifiable Example (MCVE) or Short, Self Contained, Correct Example (SSCCE) that demonstrates your issue, has no external dependencies or customizations such as background color / image, etc. It should be indented correctly, as said in the comments above.
I am writing some Java code that allows the user to see a frame with JLabel, JTextField and JButton.
I want the JLabel to be called "Count" and I have a problem with FlowLayout.
I want the interface to look like this:
Instead, I have this:
This is my code:
package modul1_Interfate_Grafice;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Exercitiu04 implements ActionListener {
private JFrame frame;
private JLabel labelCount;
private JTextField tfCount;
private JButton buttonCount;
private int count = 0;
public void go() {
frame = new JFrame("Java Counter");
labelCount = new JLabel("Counter");
labelCount.setLayout(new FlowLayout());
frame.getContentPane().add(BorderLayout.CENTER, labelCount);
tfCount = new JTextField(count + " ", 10);
tfCount.setEditable(false);
labelCount.add(tfCount);
buttonCount = new JButton("Count");
labelCount.add(buttonCount);
buttonCount.addActionListener(this);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(350, 150);
frame.setLocation(400, 200);
}
#Override
public void actionPerformed(ActionEvent event) {
count++;
tfCount.setText(count + "");
}
public static void main(String[] args) {
Exercitiu04 a = new Exercitiu04();
a.go();
}
}
Solve it.
Instead of labelCount.setLayout(new FlowLayout());` i should have had
frame.setLayout(new FlowLayout());
From description of JLabel class,
JLabel is:
A display area for a short text string or an image, or both.
But here: labelCount.add(tfCount) and here labelCount.add(buttonCount) you're trying to put a textfield and a button into a label. In this case, positions of button and textfield are controlled by FlowLayout but position of the text in the label is not.
Instead of this, you should put all of your elements in common JPanel, like this:
...
frame = new JFrame("Java Counter");
frame.setLayout(new BorderLayout());
JPanel wrapper = new JPanel(); // JPanel has FlowLayout by default
labelCount = new JLabel("Counter");
labelCount.setLayout(new FlowLayout());
wrapper.add(labelCount);
tfCount = new JTextField(count + " ", 10);
tfCount.setEditable(false);
wrapper.add(tfCount);
buttonCount = new JButton("Count");
buttonCount.addActionListener(this);
wrapper.add(buttonCount);
frame.add(BorderLayout.CENTER, wrapper);
...
And, like MasterBlaster said, you should put swing methods in EDT.
There are only two things you should know about FlowLayout:
a) It is a default layout manager of the JPanel component
b) It is good for nothing.
This trivial layout cannot be achieved with FlowLayout.
When doing layouts in Swing, you should familiarize yourself
with some powerful layout managers. I recommend MigLayout and
GroupLayout.
package com.zetcode;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
/*
Simple UI with a MigLayout manager.
Author Jan Bodnar
Website zetcode.com
*/
public class MigLayoutCounterEx extends JFrame {
public MigLayoutCounterEx() {
initUI();
}
private void initUI() {
JLabel lbl = new JLabel("Counter");
JTextField field = new JTextField(10);
JButton btn = new JButton("Count");
createLayout(lbl, field, btn);
setTitle("Java Counter");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
setLayout(new MigLayout());
add(arg[0]);
add(arg[1]);
add(arg[2]);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MigLayoutCounterEx ex = new MigLayoutCounterEx();
ex.setVisible(true);
});
}
}
The example is trivial. You just put the three components into the
cells.
Screenshot:
You shouldn't use setSize when dealing with FlowLayout. Instead use pack(). It makes the window just about big enough to fit all your components in. That should tidy things up for you
Hi this is a bit of a basic question. In my code I create a gui in a constructor then nest a ActionListener class to handle button changes. This code will create the gui and the action listener runs through the actionPerformed method correctly. However, I've tried multiple ways to change the panel in the gui but I feel like the way I have the program set up it is not possible for this to work. Sorry if this is a repeat but after searching for a while on S.O. I haven't found a good example that would help me with my problem.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import org.math.plot.Plot2DPanel;
import org.math.plot.plotObjects.BaseLabel;
public class GraphGui extends JFrame {
//default width and height of the GUI
private static final int WIDTH = 1200;
private static final int HEIGHT = 700;
GraphPlot gp = new GraphPlot();
Plot2DPanel plotPanel =gp.determinePlotToPlot("duration");
/**
* This is the constructor that initializes the JFrame and the layout of the GUI.
* The radio buttons are also created here and grouped accordingly.
*/
public GraphGui() {
//title of GUI
setTitle("VibeTech Graph Gui");
//First JRadioButton for date vs duration
JRadioButton durToDate = new JRadioButton("Duration vs. Date");
durToDate.addActionListener(new RadioButtonListener());
durToDate.setActionCommand("duration");
durToDate.setSelected(true);
//JRadioButton for weight vs date
JRadioButton weightToDate = new JRadioButton("Weight vs. Date");
weightToDate.addActionListener(new RadioButtonListener());
weightToDate.setActionCommand("weight");
//JRadioButton for plan type vs date
JRadioButton planToDate = new JRadioButton("Plan vs. Date");
planToDate.addActionListener(new RadioButtonListener());
planToDate.setActionCommand("level");
//button group of the buttons to display them as one group
ButtonGroup group = new ButtonGroup();
group.add(planToDate);
group.add(weightToDate);
group.add(durToDate);
//create JPanel to add objects to
JPanel jplRadio = new JPanel();
jplRadio.setLayout(new GridLayout(0, 1));
//add radio buttons
jplRadio.add(planToDate);
jplRadio.add(weightToDate);
jplRadio.add(durToDate);
Plot2DPanel dvt = new Plot2DPanel();
dvt.addLinePlot("Duration over Time", gp.getDate(), gp.getDuration());
BaseLabel title = new BaseLabel("Duration over Time", Color.RED,
0.5, 1.1);
title.setFont(new Font("Courier", Font.BOLD, 20));
dvt.addPlotable(title);
dvt.setAxisLabels("Time", "Duration");
setLayout(new BorderLayout());
add(jplRadio, BorderLayout.WEST);
add(plotPanel, BorderLayout.EAST);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//main method to run program
public static void main(String [ ] args)
{
//create new GUI
#SuppressWarnings("unused")
GraphGui test = new GraphGui();
}
//create a radio button listener to switch graphs on button press
class RadioButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("duration")) {
plotPanel = gp.determinePlotToPlot("duration");
} else if (e.getActionCommand().equals("weight")) {
plotPanel = gp.determinePlotToPlot("weight");
} else if (e.getActionCommand().equals("level")) {
plotPanel = gp.determinePlotToPlot("level");
}
//here is where I tried to do removes, adds, and validates but
//I have trouble getting to the frame itself to remove the JPanel
//component. I think this is a setup problem.
}
}
}
You would need to add the panel and revalidate/repaint the JFrame for it to appear:
add(plotPanel, BorderLayout.EAST);
revalidate();
repaint();
Better to use CardLayout to manage this type of functionality.
Try using CardLayout for switching between panels. Here is my solution for a similar question: https://stackoverflow.com/a/9377623/544983
I am creating a JApplet MadLibs game, but the image I add fills up the entire page so that my Labels and JTextFields are being blocked. I only want the logo to be centered at the top of the applet.
My code:
import java.awt.*;
import javax.swing.*;
import javax.swing.JApplet;
import java.awt.event.*;
import java.net.URL;
public class MadLibs extends JApplet implements ActionListener {
JLabel label1 = new JLabel("A Proper First Name: ");
JLabel label2 = new JLabel("A Pet: ");
JLabel label3 = new JLabel("A Personal Attribute: ");
JLabel label4 = new JLabel("An Adjective: ");
JLabel label5 = new JLabel("A Verb: ");
JTextField jtf1 = new JTextField();
JTextField jtf2 = new JTextField();
JTextField jtf3 = new JTextField();
JTextField jtf4 = new JTextField();
JTextField jtf5 = new JTextField();
JButton jb = new JButton("Create!");
JLabel madlib = new JLabel("");
Container con = getContentPane();
private Image image;
public void init() {
image = getImage(getDocumentBase(), "MadLibsLogo.gif");
jb.addActionListener(this);
con.add(label1);
con.add(jtf1);
con.add(label2);
con.add(jtf2);
con.add(label3);
con.add(jtf3);
con.add(label4);
con.add(jtf4);
con.add(label5);
con.add(jtf5);
con.add(jb);
con.add(madlib);
}
public void actionPerformed(ActionEvent e) {
madlib.setText(jtf1.getText() + " had a little " + jtf2.getText() + "/nIts " + jtf3.getText() + " was " + jtf4.getText() +
" as snow/nAnd everywhere that " + jtf1.getText() + jtf5.getText() + "/nThe " + jtf2.getText() + " was sure to go.");
repaint();
}
public void paint(Graphics g)
{
g.drawImage(image, 0, 0, 229, 73, this);
}
}
Don't override a JApplet's paint method, and in fact it is usually a bad idea to override the paint method of any top-level window unless you're sure that you need to do this, don't care about or need the double buffering offered with Swing graphics, and understand that this may effect the GUI's borders and child components.
Why not simply put the Image in an ImageIcon and that in a JLabel, and then place the JLabel where you desire to display the image?
Edit: you appear to be adding many components to the contentPane without regard for layout. Have you changed it's layout from the default BorderLayout somewhere in code not posted?
Edit 2 You state:
No I haven't...I still haven't gotten to the layout. How would I change the BorderLayout so that everything is aligned?
If you haven't changed the layout, then in all likelihood the only thing you are seeing is the last component added to the contentPane, the madLib JLabel. What you will want to is to layer JPanels on top of each other, each with its own layout manager. For instance, continue leaving the contentPane with a BorderLayout, adding the logo JLabel with the image in the BorderLayout.NORTH or PAGE_START position. Then add most of the body of the GUI into a JPanel that's placed BorderLayout.CENTER. Read up on the various layout managers and play with them as that's the best way to learn how to use them.
I am working with the JTextPane and am trying to make the text move sideways instead of a newline like the JTextField. I have tried searching and looking through the JTextPane's API but I haven't found anything useful. Could someone show me some type of method or process (that can be used in a main class) that could help me? Thanks you!
P.S.
I am aware of using the JScrollPane, but I would like to avoid that since I would like the JTextPane to look like a JTextField as much as possible.
JTextPane textPane = new JTextPane();
JPanel noWrapPanel = new JPanel( new BorderLayout() );
noWrapPanel.add( textPane );
JScrollPane scrollPane = new JScrollPane( noWrapPanel );
Solution Source
Plus:
JScrollPane.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_NEVER);
JScrollPane.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
EDIT:
Solution without JScrollPane
import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.plaf.ComponentUI;
import javax.swing.text.StyledDocument;
public class NonWrappingTextPane extends JTextPane {
public NonWrappingTextPane() {
super();
}
public NonWrappingTextPane(StyledDocument doc) {
super(doc);
}
// Override getScrollableTracksViewportWidth
// to preserve the full width of the text
#Override
public boolean getScrollableTracksViewportWidth() {
Component parent = getParent();
ComponentUI ui = this.getUI();
return parent != null ? (ui.getPreferredSize(this).width <= parent.getSize().width) : true;
}
// Test method
public static void main(String[] args) {
String content = "The plaque on the Apollo 11 Lunar Module\n"
+ "\"Eagle\" reads:\n\n"
+ "\"Here men from the planet Earth first\n"
+ "set foot upon the Moon, July, 1969 AD\n"
+ "We came in peace for all mankind.\"\n\n"
+ "It is signed by the astronauts and the\n"
+ "President of the United States.";
JFrame f = new JFrame("Non-wrapping Text Pane Example");
JPanel p = new JPanel();
NonWrappingTextPane nwtp = new NonWrappingTextPane();
nwtp.setText(content);
p.add(nwtp);
f.getContentPane().setLayout(new GridLayout(2, 1));
f.getContentPane().add(p);
f.setSize(300, 200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}