I'm trying to set the height of a JTextField. At present its the full size of the displayed JFrame. Any ideas how I set the height to 50?
Edit: Here is the amended code along with screenshot thanks!
public class Display extends JFrame {
private DrawCanvas canvas;
private JTextField Altitude;
private JTextField TASpeed;
private JLabel altButton;
private int countA = 0;
private int countS = 0;
private int Bcount1 = 0;
public String Ccount = Integer.toString(Bcount1);
public Display() {
canvas = new DrawCanvas();
canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
canvas.setLayout(new BorderLayout());
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
cp.add(canvas, BorderLayout.LINE_START);
//here are the 2 side fields![enter image description here][2]
Altitude = new JTextField("0", 5);
Altitude.setHorizontalAlignment(JTextField.CENTER);
Altitude.setEditable(false);
Altitude.setOpaque(false);
Altitude.setFont(Altitude.getFont().deriveFont(25f));
TASpeed = new JTextField("0", 5);
TASpeed.setHorizontalAlignment(JTextField.CENTER);
TASpeed.setEditable(false);
TASpeed.setOpaque(false);
TASpeed.setFont(Altitude.getFont().deriveFont(25f));
altButton = new JLabel();
altButton.setText(Ccount);
canvas.add(altButton, BorderLayout.SOUTH);
canvas.add(Altitude, BorderLayout.LINE_END);
canvas.add(TASpeed, BorderLayout.LINE_START);
canvas.add(new JLabel(Ccount), BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("FLIGHT DISPLAY");
pack();
setVisible(true);
requestFocus();
}
class DrawCanvas extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(CANVAS_BACKGROUND);
g.setColor(GROUND_COLOR);
g.drawString(Ccount, 100, 100);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Display();
}
});
}
}
As #kleopatra correctly comments, the JTextField can calculate it's own preferred size based on the platform designer's choice of Font. This example changes the size.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
/** #see http://stackoverflow.com/a/14734937/230513 */
public class Test {
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField tfCount = new JTextField("42", 8);
tfCount.setHorizontalAlignment(JTextField.CENTER);
tfCount.setFont(tfCount.getFont().deriveFont(50f));
f.add(tfCount, BorderLayout.NORTH);
f.add(new JPanel() { //placeholder
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
}, BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
}
Related
I am building a Java Swing app, which I want it will work this way:
When you resize the window, the JScrollPane object (which is within a JSplitPane) should redimension its minimum, maximum and preferred size taking as reference the current window width.
I fixed this settings on the method componentResized() of ComponentAdapter class, however, it doesn't work as suppose must do.
This is the code. I wish you test it on your pc and can help me.
Thanks a lot for your time payed.
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
public class ComVisor extends JFrame
{
private JList imagesList;
private JPanel imagePanel;
private JSplitPane mainPanel;
private JScrollPane scrollPanelRight;
private int width;
public ComVisor(String nameApplication)
{
setFrame(nameApplication);
setComponents();
}
private void setFrame(String nameApplication)
{
setLayout(new BorderLayout(1, 3));
setTitle(nameApplication);
setMinimumSize(new Dimension(400, 200));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(new Dimension(Toolkit.getDefaultToolkit().getScreenSize()));
setLocationRelativeTo(null);
this.addWindowListener(
new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
JOptionPane.showMessageDialog(ComVisor.this, nameApplication + "-Salida");
return;
}
}
);
this.addComponentListener(
new ComponentAdapter()
{
#Override
public void componentResized(ComponentEvent E)
{
width = getWidth();
scrollPanelRight.setPreferredSize(new Dimension(width / 3, 0));
scrollPanelRight.setMinimumSize(new Dimension(width / 7, 0));
scrollPanelRight.setMaximumSize(new Dimension(width / 5 * 4, 0));
return;
}
}
);
}
private void setComponents()
{
String[] a = {"dsdsdsd", "dsdsdkkhskj", "dskhkjdhskjdhksdh", "sdskdhskjhds"};
JButton b = new JButton("Soy un boton xD");
JPanel p = new JPanel();
imagesList = new JList(a);
p.add(b);
imagesList.setVisibleRowCount(100);
scrollPanelRight = new JScrollPane(imagesList);
mainPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scrollPanelRight, p);
add(mainPanel, BorderLayout.CENTER);
return;
}
private class Manejador implements ActionListener
{
#Override
public void actionPerformed(ActionEvent listener)
{
return;
}
}
}
and this is the main class, which calls a Comvisor object
import static javax.swing.SwingUtilities.invokeLater;
public class Principal
{
public static void main(String[] args)
{
invokeLater(
new Runnable()
{
#Override
public void run()
{
new ComVisor("ComVisor").setVisible(true);
return;
}
}
);
return;
}
}
I have 4 panels which are added to a frame.
JFrame is set to GridLayout
setLayout(new GridLayout(2, 2));
add(panel1);
add(panel2);
add(panel3);
add(panel4);
When I click on a panel, I want this panel is zoom out and fit to frame's size.
getContentPane().removeAll();
setLayout(new BorderLayout());
panel1.setPreferredSize(new Dimension(getWidth(), getHeight()));
add(panel1, BorderLayout.CENTER);
revalidate();
repaint();
But It didn't work. I think that I cannot set BorderLayout for this frame, it is still GridLayout.
How can I repair it? Thanks
When I click on a panel, I want this panel is zoom out and fit to frame's size.
to use CardLayout
direct answer to the question
.
.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
public class SwitchLayoutManager {
private JFrame frame = new JFrame();
private JPanel panel1 = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 50);
}
#Override
public Border getBorder() {
return new LineBorder(Color.BLACK, 1);
}
};
private JPanel panel2 = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 50);
}
#Override
public Border getBorder() {
return new LineBorder(Color.RED, 1);
}
};
private JPanel panel3 = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 50);
}
#Override
public Border getBorder() {
return new LineBorder(Color.BLUE, 1);
}
};
private JPanel panel4 = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 50);
}
#Override
public Border getBorder() {
return new LineBorder(Color.ORANGE, 1);
}
};
private JPanel panel5 = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
public Border getBorder() {
return new LineBorder(Color.GREEN, 1);
}
};
private GridLayout gridLayout = new GridLayout(2, 2);
private BorderLayout borderLayout = new BorderLayout();
public SwitchLayoutManager() {
frame.setLayout(gridLayout);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
frame.add(panel4);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
Timer t = new Timer(2500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (frame.getContentPane().getLayout() == borderLayout) {
frame.getContentPane().removeAll();
frame.setLayout(gridLayout);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
frame.add(panel4);
frame.pack();
//frame.revalidate();
//frame.repaint();
} else if (frame.getContentPane().getLayout() == gridLayout) {
frame.getContentPane().removeAll();
frame.setLayout(borderLayout);
frame.add(panel5);
frame.pack();
//frame.revalidate();
//frame.repaint();
}
}
});
t.setInitialDelay(2500);
t.setRepeats(true);
t.start();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SwitchLayoutManager();
}
});
}
}
I created a simple frame program that includes a image. But the image don't have the same size as the frame. If i enlarge the frame the image size stays the same?
How can i make the image the same size as the frame?
Here is my current code:
JPanel panel1 = new JPanel();
ImageIcon image1 = new ImageIcon("C:\\Users\\Dark Mangetsu\\Downloads\\Ceng102_Lab10.1\\image\\flower.jpg");
JLabel label1 = new JLabel(image1);
panel1.add(label1);
Color color1 = new Color (200, 0 ,100);
panel1.setBorder(BorderFactory.createLineBorder(color1, 3));
JFrame f = new JFrame("Frame");
f.setLayout(new BorderLayout(5,5));
f.add((panel1),BorderLayout.WEST);
f.setSize(320,200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
You can paint the image instead of using a label.
ImageIcon icon = new ImageIcon("C:\\Users\\Dark Mangetsu\\Downloads\\Ceng102_Lab10.1\\image\\flower.jpg");
Image image = icon.getImage();
JPanel panel1 = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight());
}
};
Also not sure, but I think you may want to add the panel to the CENTER and not the west (if you want the image to be centered in the frame).
Also not, if you want a preferredSize for the panel, you will have to override the getPreferredSize() of the panel also.
JPanel panel1 = new JPanel() {
...
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 200);
}
};
Then you can just pack() the frame, which is preferred, instead of setting the size
f.pack();
//f.setSize(320, 200);
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestBackgroundResize {
public TestBackgroundResize() {
JFrame frame = new JFrame();
frame.setContentPane(createBackgroundPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createBackgroundPanel() {
return new JPanel() {
BufferedImage image;
{
try {
image = ImageIO.read(getClass().getResource("/marioblobs/mario.png"));
} catch (IOException ex) {
Logger.getLogger(TestBackgroundResize.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 200);
}
};
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestBackgroundResize();
}
});
}
}
I think the code is missing call to pack() method.
Here is a sample code:
public class ImageToPanel {
public static void main(String[] args) {
ImageToPanel itp = new ImageToPanel();
itp.go();
}
private void go() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() { createAndShowGUI(); }
});
}
private void createAndShowGUI() {
JFrame f =new JFrame();
f.setLayout(new BorderLayout());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setPreferredSize(new Dimension(640,400));
JLabel label = new JLabel( new ImageIcon("wallpaper.jpg") );
f.add(label, BorderLayout.CENTER);
JButton button = new JButton("Quit");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
f.add(button, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
}
SCREENSHOT
In the screenshot below, a 1920x1200 wallpaper is constrained seamlessly in a 640x400 frame.
Tested on
Windows 7
Java 7
EDIT:
ImageIcon image1 = new ImageIcon("wallpaper.jpg");
JLabel label1 = new JLabel(image1);
Color color1 = new Color (200, 0 ,100);
label1.setBorder(BorderFactory.createLineBorder(color1, 3));
JFrame f = new JFrame("Frame");
f.setLayout(new BorderLayout(5,5));
f.add(label1,BorderLayout.WEST);
f.setSize(320,200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Before resize
After resize
When the addComponents() method is run once, I get the desired layout of my JPanel. However, when the code in addComponents() is executed more than once, the layout of the JPanel is completely wrong. Is there anything that I seem to be doing wrong?
public class DeleteStudent extends JPanel {
public SearchPanel search = new SearchPanel();
private final JButton deleteButton = new JButton("Delete from database");
private GridBagConstraints cons = new GridBagConstraints();
private final GridBagLayout gridBag = new GridBagLayout();
public DeleteStudent() {
super();
setLayout(gridBag);
setPreferredSize(new Dimension(400, 300));
addComponents();
addComponents(); //Method fails when run more than once!
}
public void addComponents() {
cons.gridy = 1;
cons.insets = new Insets(50, 0, 0, 0);
gridBag.setConstraints(deleteButton, cons);
removeAll();
add(search);
add(deleteButton);
update();
}
private void update() {
revalidate();
repaint();
}
Screenshots:
JPanel after 1 method call: http://img402.imageshack.us/img402/6409/oncer.png
JPanel after 2 method calls: http://imageshack.us/scaled/landing/254/twiced.png
Adding to my comment:
Seems problem is you set the JPanels GridBagLayout constraints before calling removeAll() it should be done after calling removeAll(); so that when we add the new components the LayoutManager is still in effect and hasnt been reset to its defaults values.
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public Test() {
createAndShowGui();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
private void createAndShowGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DeleteStudent());
frame.pack();
frame.setVisible(true);
}
}
class DeleteStudent extends JPanel {
public JPanel search = new JPanel() {//for testing
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
};
private final JButton deleteButton = new JButton("Delete from database");
private GridBagConstraints cons = new GridBagConstraints();
private final GridBagLayout gridBag = new GridBagLayout();
public DeleteStudent() {
super();
setLayout(gridBag);
addComponents();
addComponents(); //Method fails when run more than once!
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
public void addComponents() {
removeAll();//must call this before resetting Layout and adding new components
cons.gridy = 1;
cons.insets = new Insets(50, 0, 0, 0);
gridBag.setConstraints(deleteButton, cons);
add(search);
add(deleteButton);
update();
}
private void update() {
revalidate();
repaint();
}
}
I am trying to remove a JPanel not hide it but i can't find anything that works.
This is the code in the panel that needs to remove itself when a button is pressed:
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Frame frame = new Frame(); //referencing to my JFrame class (this class is a JPanel)
//need to remove this panel on this line
frame.ThreeD(); // adds a new panel
}
});
UPDATED
This is the full code:
package ThreeD;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.UIManager;
import Run.Frame;
public class Launcher extends JPanel{
private JButton play, options, help, mainMenu;
private Rectangle rplay, roptions, rhelp, rmainMenu;
private int buttonWidthLocation, buttonWidth, buttonHeight;
private int width = 1280;
public Launcher() {
this.setLayout(null);
drawButtons();
}
private void drawButtons() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
e.printStackTrace();
}
play = new JButton("Play");
options = new JButton("Options");
help = new JButton("Help");
mainMenu = new JButton("Main Menu");
buttonWidthLocation = (width / 2) - (buttonWidth / 2);
buttonWidth = 80;
buttonHeight = 40;
rplay = new Rectangle(buttonWidthLocation, 150, buttonWidth, buttonHeight);
roptions = new Rectangle(buttonWidthLocation, 300, buttonWidth, buttonHeight);
rhelp = new Rectangle(buttonWidthLocation, 450, buttonWidth, buttonHeight);
rmainMenu = new Rectangle(buttonWidthLocation, 600, buttonWidth, buttonHeight);
play.setBounds(rplay);
options.setBounds(roptions);
help.setBounds(rhelp);
mainMenu.setBounds(rmainMenu);
add(play);
add(options);
add(help);
add(mainMenu);
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Frame frame = new Frame();
//need to remove this panel here
frame.ThreeD();
}
});
options.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("options");
}
});
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("help");
}
});
mainMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("mainMenu");
}
});
}
}
And this is my Frame class:
package Run;
import javax.swing.*;
import ThreeD.Display;
import ThreeD.Launcher;
import TowerDefence.Window;
import java.awt.*;
import java.awt.image.BufferedImage;
public class Frame extends JFrame{
public static String title = "Game";
/*public static int GetScreenWorkingWidth() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width;
}*/
/*public static int GetScreenWorkingHeight() {
return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height;
}*/
//public static Dimension size = new Dimension(GetScreenWorkingWidth(), GetScreenWorkingHeight());
public static Dimension size = new Dimension(1280, 774);
public static void main(String args[]) {
Frame frame = new Frame();
System.out.println("Width of the Frame Size is "+size.width+" pixels");
System.out.println("Height of the Frame Size is "+size.height+" pixels");
}
public Frame() {
setTitle(title);
setSize(size);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ThreeDLauncher();
}
public void ThreeDLauncher() {
Launcher launcher = new Launcher();
add(launcher);
setVisible(true);
}
public void TowerDefence() {
setLayout(new GridLayout(1, 1, 0, 0));
Window window = new Window(this);
add(window);
setVisible(true);
}
public void ThreeD() {
BufferedImage cursor = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Cursor blank = Toolkit.getDefaultToolkit().createCustomCursor(cursor, new Point(0, 0), "blank");
getContentPane().setCursor(blank);
Display display = new Display();
add(display);
setVisible(true);
display.start();
}
}
Basically - you are creating new instance of Frame in line:
Frame frame = new Frame(); //referencing to my JFrame class (this class is a JPanel)
New instance of Frame is not visible, and you're try to remove your Launcher from not visible new Frame. But this is wrong - you should remove Launcher from Frame that you created previously in main function (that is: parent of Launcher component).
Here goes an example:
public class TestFrame extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestFrame frame = new TestFrame();
frame.getContentPane().add(new MyPanel(frame));
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
And MyPanel class:
public class MyPanel extends JPanel {
public MyPanel(final TestFrame frame) {
JButton b = new JButton("Play");
add(b);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Container pane = frame.getContentPane();
pane.remove(MyPanel.this);
JPanel otherPanel = new JPanel();
otherPanel.add(new JLabel("OtherPanel"));
pane.add(otherPanel);
pane.revalidate();
}
});
}
}
In your example you should add a reference to Frame in your Launcher constructor:
public Launcher(Frame frame) {
this.frame = frame;
...
Init Launcher:
public void ThreeDLauncher() {
Launcher launcher = new Launcher(this);
and use:
play.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//need to remove this panel here
frame.getContentPane().remove(Launcher.this);
frame.ThreeD();
}
});
Say your panel is myPanel you can remove it from the main frame by:
frame.getContentPane().remove(myPanel);