I've to resize few elements like JTable on window resize. I've been trying this code, but it doesn't work correctly:
table.setLocation(0, 23);
Dimension siz = contentPane.getMaximumSize();
table.setSize(siz.height, siz.width - 46);
It resizing my table, but it making it endless, what i don't want. Also I would like to connent scrollbar to this table, and if it's possible - set column width in precentage
Your main problem (with resizing) has more to do with your reliance on form editors then anything to do with Swing or Java
Have a look at Laying Out Components Within a Container for more details.
You're also don't seem to be utilising a JScrollPane to house the JTable in. Have a look at How to Use Tables and How to Use Scroll Panes for more details
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class ResizeTest {
public static void main(String[] args) {
new ResizeTest();
}
public ResizeTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTable table;
private JButton historyButton;
private JButton otherButton;
public TestPane() {
table = new JTable(new DefaultTableModel(10, 10));
historyButton = new JButton("History");
otherButton = new JButton("Other");
setLayout(new BorderLayout());
JPanel buttons = new JPanel(new FlowLayout(FlowLayout.LEFT));
buttons.add(historyButton);
buttons.add(otherButton);
add(buttons, BorderLayout.NORTH);
add(new JScrollPane(table));
JPanel footers = new JPanel(new GridLayout(1, 2));
JLabel left = new JLabel("Left");
left.setHorizontalAlignment(JLabel.LEFT);
JLabel right = new JLabel("Right");
right.setHorizontalAlignment(JLabel.LEFT);
footers.add(left);
footers.add(right);
add(footers, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Related
I am trying to display a background image on the JFrame using a JLabel. The code runs and the buttons appear, but the image does not. I have researched for solutions, yet I have not found one for my code specifically. Any help would be greatly appreciated.
/**
* Adds details to interface and programs buttons
*
* Imani Davis
* Final Project
*/
import java.awt.*;
import java.awt.GridBagLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.border.EmptyBorder;
public class Use_PF_Interface extends JFrame implements Pet_Fish_Interface
{
// instance variables - replace the example below with your own
private JFrame window;
private JPanel panel1, panel2, panel3;
private JLabel lblBackgroundImage = new JLabel();
private JButton feedButton = new JButton("Feed Fish");
private JButton playGamesButton = new JButton("Play Game");
/**
* Constructor for objects of class Use_PF_Interface
*/
public Use_PF_Interface()
{
setTitle("Virtual Pet Fish");
setSize(650, 650);
//initializes panels and panel layout
panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
panel1.setLayout(new FlowLayout());
panel2.setLayout(new FlowLayout());
panel3.setLayout(new FlowLayout());
lblBackgroundImage.setLayout(new FlowLayout());
//sets background image of panel
lblBackgroundImage.setIcon(new ImageIcon("C:\\Users\\This PC\\Desktop\\OCEAN2.JPEG"));
panel1.add(lblBackgroundImage);
validate();
//adds button to panels
panel2.add(feedButton);
panel2.add(playGamesButton);
//add panels to frame
add(panel1);
add(panel2);
}
}
JFrame uses a BorderLayout by default, a BorderLayout can only manage a single component within any of the five available positions it provides, this means that panel2 is most likely the only component getting shown.
An alternative is to add you components to the JLabel, but remember, JLabel doesn't have a default layout manager. Also, remember, JLabel only uses the icon and text properties to calculate its preferred size, so if the contents require more space, they will be clipped.
Start by having a look at How to Use BorderLayout for more details
Also, remember, most Swing components are opaque generally, so you need to set them transparent when you want to do something like this
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Use_PF_Interface extends JFrame {
// instance variables - replace the example below with your own
private JPanel panel2;
private JLabel lblBackgroundImage = new JLabel();
private JButton feedButton = new JButton("Feed Fish");
private JButton playGamesButton = new JButton("Play Game");
/**
* Constructor for objects of class Use_PF_Interface
*/
public Use_PF_Interface() {
setTitle("Virtual Pet Fish");
setSize(650, 650);
//initializes panels and panel layout
panel2 = new JPanel();
panel2.setOpaque(false);
panel2.setLayout(new FlowLayout());
lblBackgroundImage.setLayout(new FlowLayout());
//sets background image of panel
lblBackgroundImage.setIcon(new ImageIcon("..."));
lblBackgroundImage.setLayout(new BorderLayout());
//adds button to panels
panel2.add(feedButton);
panel2.add(playGamesButton);
lblBackgroundImage.add(panel2);
add(lblBackgroundImage);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new Use_PF_Interface();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Try this,
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageInFrame {
public static void main(String[] args) throws IOException {
String path = "Image1.jpg";
File file = new File(path);
BufferedImage image = ImageIO.read(file);
JLabel label = new JLabel(new ImageIcon(image));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.pack();
f.setLocation(200,200);
f.setVisible(true);
}
}
list is to accept input from Action1 this works, however, whenever a new element is added to the list, the list's position moves back to the default top-middle position.
This also occurs when the frame is resized, so as a temporary fix I the line frame.setResizable(false) but I do not want that to be permanent.
How would I fix both of these issues?
import static java.lang.String.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
public class lists
{
static String newUrl;
static DefaultListModel<String> model = new DefaultListModel<String>();
static int listXCoord = 650;
static int listYCoord = 10;
public static void createGUI()
{
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setSize(800,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
JPanel panel = new JPanel();
frame.add(panel);
JButton addurl = new JButton("Add URL");
panel.add(addurl);
addurl.addActionListener(new Action1());
JButton remurl = new JButton("Remove URL");
panel.add(remurl);
//model.addElement("one");
//model.addElement("two");
//model.addElement("three");
JList list = new JList<String>(model);
list.setCellRenderer(new DefaultListCellRenderer());
list.setVisible(true);
list.setLocation(listXCoord, listYCoord);
list.setBackground(new Color(186, 203, 250));
//list.setLocation(650, 10);
panel.add(list);
list.setSize(130, 540);
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
newUrl = JOptionPane.showInputDialog("Enter the URL to be Launched");
model.addElement(newUrl);
}
}
public static void main(String[] args)
{
createGUI();
}
}
Basically, you're fighting the layout manager (Flowlayout) and losing. When you add a new element to the JList, the container hierarchy is been revalidated which is causing the layout managers to re-layout the contents of their containers
The basic solution would be to use a different layout, but, JFrame uses a BorderLayout, so instead of adding the JList to the JPanel, you could simply add it to the EAST position of the frame instead
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Lists {
static String newUrl;
static DefaultListModel<String> model = new DefaultListModel<String>();
static int listXCoord = 650;
static int listYCoord = 10;
public static void createGUI() {
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton addurl = new JButton("Add URL");
panel.add(addurl);
addurl.addActionListener(new Action1());
JButton remurl = new JButton("Remove URL");
panel.add(remurl);
//model.addElement("one");
//model.addElement("two");
//model.addElement("three");
JList list = new JList<String>(model);
list.setCellRenderer(new DefaultListCellRenderer());
list.setVisible(true);
list.setLocation(listXCoord, listYCoord);
list.setBackground(new Color(186, 203, 250));
//list.setLocation(650, 10);
frame.add(new JScrollPane(list), BorderLayout.EAST);
frame.setVisible(true);
}
static class Action1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
newUrl = JOptionPane.showInputDialog("Enter the URL to be Launched");
model.addElement(newUrl);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
createGUI();
}
});
}
}
See Laying Out Components Within a Container, How to Use BorderLayout and How to use FlowLayout for more details.
You should also be calling setVisible last, after all the components have been added to the frame, this reduces the possibilities that some of your components won't be displayed when you think they should be.
JList will also benefit from been contained within a JScrollPane. See How to Use Lists and How to Use Scroll Panes for more details
When I set the outpanel into a BoxLayout then the panel disappears. However the scrollbar shows that indicates my panel in ArrayList are in the right position.
I am totally new to Java so I'll appreciate any comments.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.*;
import javax.swing.*;
public class gui extends JFrame{
int ctr=0, top=5;
public List<JPanel> o_panels = new ArrayList<JPanel>(); //Your List
public gui(){
super("MCC");
setLayout(null);
//Output panel for the results
JPanel outpanel = new JPanel();
outpanel.setBackground(Color.blue);
outpanel.setVisible(true);
outpanel.setLayout(new BoxLayout(outpanel, BoxLayout.PAGE_AXIS));
//Scroll pane
JScrollPane scrollPane = new JScrollPane(outpanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(0,0,780,400);
add(scrollPane);
//result panel
//creating and adding panels in to the array list
while(ctr<=4){
JPanel label1 = new JPanel();
label1.setPreferredSize(new Dimension(600,100));
o_panels.add(label1);
outpanel.add(o_panels.get(ctr));
ctr++;
}
}
public void runGui(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
this.setVisible(true);
this.setResizable(false);
//i call this on the other class
}
}
There is, not much, wrong with your code, the problem is, you've not established any means by which you can see what you've been adding
Have a look at this...
while (ctr <= 4) {
JPanel label1 = new JPanel();
label1.setPreferredSize(new Dimension(600, 100));
o_panels.add(label1);
outpanel.add(o_panels.get(ctr));
ctr++;
}
All the panels are the same color and you've added nothing to them, so how could you possible know if they were been added or layout correctly...
I simple added label1.setBorder(new LineBorder(Color.RED)); and got this result...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class Test extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
Test test = new Test();
test.runGui();
}
});
}
int ctr = 0, top = 5;
public List<JPanel> o_panels = new ArrayList<JPanel>(); //Your List
public Test() {
super("MCC");
//Output panel for the results
JPanel outpanel = new JPanel();
outpanel.setBackground(Color.blue);
outpanel.setVisible(true);
outpanel.setLayout(new BoxLayout(outpanel, BoxLayout.PAGE_AXIS));
//Scroll pane
JScrollPane scrollPane = new JScrollPane(outpanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(0, 0, 780, 400);
add(scrollPane);
//result panel
//creating and adding panels in to the array list
while (ctr <= 4) {
JPanel label1 = new JPanel();
label1.setPreferredSize(new Dimension(600, 100));
label1.setBorder(new LineBorder(Color.RED));
o_panels.add(label1);
outpanel.add(o_panels.get(ctr));
ctr++;
}
}
public void runGui() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
this.setVisible(true);
// this.setResizable(false);
setLocationRelativeTo(null);
}
}
Also have a look at Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
And you really should avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
I want to set the Border height,width of JTextField and want to put it on the center of the JFrame in java.
I tried those ideas but those ideas does not work.
setSize(),SetPrefferedSize(),SetMaximumSize();
Need Help. Thanks in advance.
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class P{
public static void main(String [] args){
JFrame frame = new JFrame();
JTextField field = new JTextField();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.NORTH,field);
frame.setSize(350,300);
frame.setVisible(true);
}
}
You could try using a LineBorder on the JTextField and place it within a container using GridBagLayout
For example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class BorderText {
public static void main(String[] args) {
new BorderText();
}
public BorderText() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JTextField field = new JTextField(10);
field.setBorder(new LineBorder(Color.RED, 10));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Take a look at How to Use Borders and A Visual Guide to Layout Managers for more details
how to stick JLabel in GlassPane to rellative, floating coordinates from JProgressBar without using ComponentListener or another listener,
is there built_in notifiers in Standard LayoutManagers that can notify about its internal state, and can be accesible for override, instead my attempt with ComponentListener and NullLayout
.
SSCCE about ComponentListener and with NullLayout
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
//http://stackoverflow.com/questions/14560680/jprogressbar-low-values-will-not-be-displayed
public class ProgressSample {
private JFrame frame = new JFrame("GlassPane instead of JLayer");
private JLabel label;
private GridBagConstraints gbc = new GridBagConstraints();
private JProgressBar progressSeven;
public ProgressSample() {
frame.setLayout(new FlowLayout());
frame.add(new JButton("test"));
frame.add(new JCheckBox("test"));
frame.add(new JRadioButton("test"));
// Nothing is displayed if value is lover that 6
JProgressBar progressSix = new JProgressBar(0, 100);
progressSix.setValue(2);
frame.add(progressSix);
// but this works value is higher that 6
progressSeven = new JProgressBar(0, 100);
progressSeven.addComponentListener(new ComponentAdapter() {
#Override
public void componentMoved(ComponentEvent e) {
label.setBounds(
(int) progressSeven.getBounds().getX(),
(int) progressSeven.getBounds().getY(),
progressSeven.getPreferredSize().width,
label.getPreferredSize().height);
}
});
progressSeven.setValue(7);
frame.add(progressSeven);
label = new JLabel();
label.setText("<html>Blablabla, Blablablabla<br>"
+ "Blablabla, Blablablabla<br>"
+ "Blablabla, Blablablabla</html>");
label.setPreferredSize(new Dimension(
progressSeven.getPreferredSize().width,
label.getPreferredSize().height));
Container glassPane = (Container) frame.getRootPane().getGlassPane();
glassPane.setVisible(true);
glassPane.setLayout(null);
glassPane.add(label, gbc);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
ProgressSample dialogTest = new ProgressSample();
}
}
how to stick JLabel in GlassPane to rellative, floating coordinates
from JProgressBar without using ComponentListener or another listener
My idea would be to wrap the two components in a container with the OverlayLayout and "play" with AlignementX/AlignementY for the relative coordinates. Then just put the wrapping container in the original hierarchy. (See my SSCCE below)
is there built_in notifiers in Standard LayoutManagers that can notify
about its internal state, and can be accesible for override, instead
my attempt with ComponentListener and NullLayout
There is no such contract in the LayoutManager API, hence you can't rely safely on any such mechanism. Moreover, you will face issues with standard LayoutManager because they will take your extra JLabel into account in the layout.
Imagine you use FlowLayout and you put 1 component, then your extra JLabel, then another component. When you move the extra JLabel the last component will remain "away" from the first component and you will see a gap between these two.
If this last issue is not a problem, you could simply extend FlowLayout (or any other LayoutManager), override layoutContainer and place the extra JLabel wherever you would like.
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.OverlayLayout;
import javax.swing.UIManager;
//http://stackoverflow.com/questions/14560680/jprogressbar-low-values-will-not-be-displayed
public class ProgressSample {
private JFrame frame = new JFrame("GlassPane instead of JLayer");
private JLabel label;
private GridBagConstraints gbc = new GridBagConstraints();
private JProgressBar progressSeven;
public ProgressSample() {
frame.setLayout(new FlowLayout());
frame.add(new JButton("test"));
frame.add(new JCheckBox("test"));
frame.add(new JRadioButton("test"));
// Nothing is displayed if value is lover that 6
JProgressBar progressSix = new JProgressBar(0, 100);
progressSix.setValue(2);
frame.add(progressSix);
JPanel wrappingPanel = new JPanel();
OverlayLayout mgr = new OverlayLayout(wrappingPanel);
wrappingPanel.setLayout(mgr);
progressSeven = new JProgressBar(0, 100);
progressSeven.setAlignmentX(0.0f);
progressSeven.setAlignmentY(0.0f);
frame.add(wrappingPanel);
label = new JLabel();
label.setText("<html>Blablabla, Blablablabla<br>" + "Blablabla, Blablablabla<br>" + "Blablabla, Blablablabla</html>");
label.setAlignmentX(0.0f);
label.setAlignmentY(0.0f);
wrappingPanel.add(label);
wrappingPanel.add(progressSeven);
Container glassPane = (Container) frame.getRootPane().getGlassPane();
glassPane.setVisible(true);
glassPane.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
ProgressSample dialogTest = new ProgressSample();
}
}