Well I have a JPanel and I'm trying to put a picture onto that JPanel. To do that I made a JLabel but i seem to be having some problems. (I'm really not used to pictures in Java)
this.setLayout(null);
final JPanel panel = new JPanel();
panel.add(new JButton("OK"));
panel.add(new JButton("Cancel"));
ImageIcon icon = new ImageIcon("res/paypal.png");
JLabel label = new JLabel(icon);
panel.add(label);
jl.setIcon(new ImageIcon("C:\\Users\\Scr3am\\Desktop\\l.jpg"));
panel.add(jl);
Thanks, its taken me forever and I've given up.
FULL CODE:
public class Password extends JFrame {
JButton leftbutton;
JButton centerbutton;
JButton rightbutton;
FlowLayout layout;
Container container;
JLabel jl;
Password(){
super("PayPal Money Generator");
layout = new FlowLayout();
//get bulk of window, so it knows where to put the stuff
container = getContentPane();
setLayout(layout);
this.setLayout(null);
final JPanel panel = new JPanel();
panel.add(new JButton("OK"));
panel.add(new JButton("Cancel"));
try {
JLabel label = new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("res/paypal.png"))));
} catch (IOException e) {
e.printStackTrace();
}
//left stuff in here
leftbutton = new JButton("$25");
add(leftbutton);
leftbutton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
//what do we want to happen when we
//click the button
layout.setAlignment(FlowLayout.LEFT);
}
}
);
//center stuff in here
centerbutton = new JButton("$50");
centerbutton.setBounds(250, 100, 35, 35);
add(centerbutton);
centerbutton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
//what do we want to happen when we
//click the button
try {
final ImageIcon icon = new ImageIcon(ImageIO.read(getClass().getResource("/res/paypal.png")));
JOptionPane.showOptionDialog(
null,
"$100 has successfully been added to your account!",
"",
JOptionPane.OK_OPTION,
JOptionPane.PLAIN_MESSAGE,
icon,
new Object[]{"OK"},
"");
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
);
//right stuff in here
rightbutton = new JButton("$100");
rightbutton.setBounds(450, 50, 50, 50);
add(rightbutton);
rightbutton.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
//what do we want to happen when we
//click the button
try {
final ImageIcon icon = new ImageIcon(ImageIO.read(getClass().getResource("/res/paypal.png")));
JOptionPane.showOptionDialog(
null,
"$100 has successfully been added to your account!",
"",
JOptionPane.OK_OPTION,
JOptionPane.PLAIN_MESSAGE,
icon,
new Object[]{"OK"},
"");
} catch (IOException exp) {
exp.printStackTrace();
}
}
}
);
}
}
Don't use a null layout!!! Swing was designed to be used with layout managers. You panel doesn't have a 0 size so there is nothing to display.
Start with the working examples form the Swing tutorial on How to Use Icons.
Two basic problems, with many satellite issues...
First:
You're using a null layout, this means that when you add something to the container, it's default size and position are 0x0. null layouts are generally discouraged as they are troublesome to manage, diagnose and maintain across diverse platforms and Swing was designed to be used with layout managers
Since you've not provided a full code snippet, I have no idea how panel is been added to the parent container, but at the moment, it's not, which could be another problem
Updated
Based on updated code, no where does panel get added to anything and even if it did, it's size and position remain 0x0
Second:
ImageIcon(String) treats the String reference as a File, so it is looking for a file named paypal.png in the folder res which resides at the same location that the program is executed.
From the looks of it, this is an embedded resource, which should be loaded via Class#getResource, for example...
JLabel label = new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("res/paypal.png))));
Note, ImageIO.read will throw an IOException, which can be very handy in diagnosing these issues.
I'd also discourage you from using absolute path references (like "C:\Users\Scr3am\Desktop\l.jpg"), as they become irrelevant once the program is run else where
Updated with a working example
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.IOException;
import javax.imageio.ImageIO;
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 Password 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) {
}
try {
Password frame = new Password();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException exp) {
exp.printStackTrace();
}
}
});
}
JButton leftbutton;
JButton centerbutton;
JButton rightbutton;
FlowLayout layout;
Container container;
JLabel jl;
public Password() throws IOException {
super("PayPal Money Generator");
JPanel content = new JPanel(new GridBagLayout());
JLabel label = new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/res/paypal.gif"))));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
content.add(label, gbc);
gbc.gridx++;
//left stuff in here
leftbutton = new JButton("$25");
content.add(leftbutton, gbc);
//center stuff in here
gbc.gridx++;
centerbutton = new JButton("$50");
content.add(centerbutton, gbc);
//right stuff in here
gbc.gridx++;
rightbutton = new JButton("$100");
content.add(rightbutton, gbc);
JPanel buttons = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.EAST;
buttons.add(new JButton("OK"), gbc);
gbc.weightx = 0;
gbc.anchor = GridBagConstraints.CENTER;
buttons.add(new JButton("Cancel"), gbc);
add(content);
add(buttons, BorderLayout.SOUTH);
}
}
Related
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI_Borrower extends JFrame implements ActionListener {
JPanel panel = new JPanel();
JLabel lblName = new JLabel("Name:");
JLabel lblProg = new JLabel("Program:");
JLabel lblId = new JLabel("Library ID: ");
JLabel lblTitle = new JLabel("Add Borrower");
JTextField txtName = new JTextField(10);
JTextField txtProg = new JTextField(10);
JTextField txtId = new JTextField(10);
static int counter = 19000;
JButton btnSubmit = new JButton("Submit");
public GUI_Borrower() {
super("Add Borrower");
makeFrame();
showFrame();
}
public void makeFrame() {
lblTitle.setFont(new Font("Forte", Font.PLAIN, 40));
lblTitle.setForeground(Color.BLUE);
add(lblTitle);
add(lblName);
add(txtName);
add(lblProg);
add(txtProg);
add(lblId);
add(txtId);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(btnSubmit);
btnSubmit.addActionListener(this);
}
public void showFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (ae.getActionCommand().equals("Confirm")) {
txtName.setText("");
txtProg.setText("");
btnSubmit.setText("Submit");
} else if (source == btnSubmit) {
if (txtName.getText().equals("") && txtProg.getText().equals("")) {
txtId.setText("No entry of both");
} else if (txtName.getText().equals("")) {
txtId.setText("No entry of Name");
} else if (txtProg.getText().equals("")) {
txtId.setText("No entry of Program");
} else {
counter++;
txtId.setText("" + counter);
btnSubmit.setText("Confirm");
}
}
}
public static void main(String[] args) {
new GUI_Borrower();
}
}
I tried adding BoxLayout because all the text fields and labels are on one line. So I tried box Layout and failed.
Can anyone show me how to make it like the title one line, label Different line, button different line?
Like this:
As camickr says in his comment, you generally use a GridBagLayout to create a form.
I reworked your code because I hope to show a better way to code a GUI panel.
Here's the GUI.
The major changes I made include:
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that all Swing components are created and executed on the Event Dispatch Thread.
I organized the GUI code into three methods so I could focus on one part of the GUI at a time. The JFrame is created in the run method. The title JPanel is created in the createTitlePanel method. The form JPanel is created in the createFormPanel method. The code for the JFrame will rarely change from Swing application to Swing application.
I use Swing components. I don't extend Swing components, or any Java class, unless I intend to override one of the class methods.
The createFormPanel class uses the GridBagLayout to organize the labels and text fields in columns. You can think of the GridBagLayout as a flexible grid. The cells of the grid don't have to be the same size. The Oracle tutorial, How to Use GridBagLayout, has another example.
I put the ActionListener in a separate class. I made it an inner class in this example so I could paste the code as one file. Generally, you should put separate classes in separate files. It makes each class shorter and easier to understand.
Here's the runnable, example code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class BorrowerGUI implements Runnable {
private static int ID_COUNTER = 19000;
public static void main(String[] args) {
SwingUtilities.invokeLater(new BorrowerGUI());
}
private JButton btnSubmit;
private JTextField txtName;
private JTextField txtProg;
private JTextField txtId;
#Override
public void run() {
JFrame frame = new JFrame("Add Borrower");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTitlePanel(), BorderLayout.BEFORE_FIRST_LINE);
frame.add(createFormPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel(new FlowLayout());
JLabel lblTitle = new JLabel("Add Borrower");
lblTitle.setFont(new Font("Forte", Font.PLAIN, 40));
lblTitle.setForeground(Color.BLUE);
panel.add(lblTitle);
return panel;
}
private JPanel createFormPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridx = 0;
gbc.gridy = 0;
JLabel lblName = new JLabel("Name:");
panel.add(lblName, gbc);
gbc.gridx++;
txtName = new JTextField(20);
panel.add(txtName, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel lblProg = new JLabel("Program:");
panel.add(lblProg, gbc);
gbc.gridx++;
txtProg = new JTextField(20);
panel.add(txtProg, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel lblId = new JLabel("Library ID:");
panel.add(lblId, gbc);
gbc.gridx++;
txtId = new JTextField(20);
txtId.setEditable(false);
panel.add(txtId, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 2;
btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new SubmitListener());
panel.add(btnSubmit, gbc);
return panel;
}
public class SubmitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (ae.getActionCommand().equals("Confirm")) {
txtName.setText("");
txtName.requestFocus();
txtProg.setText("");
txtId.setText("");
btnSubmit.setText("Submit");
} else if (source == btnSubmit) {
if (txtName.getText().equals("") &&
txtProg.getText().equals("")) {
txtId.setText("No entry of both");
} else if (txtName.getText().equals("")) {
txtId.setText("No entry of Name");
} else if (txtProg.getText().equals("")) {
txtId.setText("No entry of Program");
} else {
ID_COUNTER++;
txtId.setText("" + ID_COUNTER);
btnSubmit.setText("Confirm");
}
}
}
}
}
Edited to add: If you want the title JLabel to be right-justified, you'll have to switch to a BorderLayout. I added an empty border so the text wouldn't be on the right edge of the JFrame.
Here's the changed method.
private JPanel createTitlePanel(String title) {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10));
JLabel lblTitle = new JLabel(title);
lblTitle.setFont(new Font("Forte", Font.PLAIN, 40));
lblTitle.setForeground(Color.BLUE);
panel.add(lblTitle, BorderLayout.AFTER_LINE_ENDS);
return panel;
}
From my code I expect my JTextArea to fill the top left border seen below:
But as you can see its taking up a tiny section in the middle.
I am using GridBagConstraints on the panel which contains the components.
There is a main class which calles up a class called frame. This class creates the JFrame and sets the size as well as other things. This is then called from the MainFrame.java which has extended the jframe which creates 3 panels and sets their layout. this is seen below
import javax.swing.*;
import java.awt.*;
public class MainFrame extends JFrame
{
private Panel1 storyPanel;
private Panel2 statsPanel;
private Panel3 commandsPanel;
public MainFrame(String title)
{
super(title);
// Setting Layout
GridBagConstraints gbc = new GridBagConstraints();
storyPanel = new Panel1();
storyPanel.setLayout(new GridBagLayout());
statsPanel = new Panel2();
commandsPanel = new Panel3();
Container p = getContentPane();
p.add(storyPanel, BorderLayout.WEST);
p.add(statsPanel, BorderLayout.EAST);
p.add(commandsPanel, BorderLayout.SOUTH);
}
}
The panel in questions is Panel1 or storyPanel. I have set the layout and the code calls the Panel1.java as seen below:
import javax.swing.*;
import java.awt.*;
public class Panel1 extends JPanel
{
public Panel1()
{
GridBagConstraints gbc = new GridBagConstraints();
//Set size of Panel1
int xsizeP1 = (Frame.xsize() / 2);
int ysizeP1 = (Frame.ysize() / 3 * 2);
setPreferredSize(new Dimension(xsizeP1, ysizeP1));
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(" test ");
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//GridBagConstraints setup for components
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.fill = GridBagConstraints.VERTICAL;
add(scroll, gbc);
}
}
I don't understand why my gbc.fill isnt making the JTextArea fill the top left border of the screen shot.
Thanks in advance for any reply's
-Tom T
changing the layout to border layout
import javax.swing.*;
import java.awt.*;
public class Panel1 extends JPanel
{
public Panel1()
{
//GridBagConstraints gbc = new GridBagConstraints();
//gbc.weightx = 0.1;
//gbc.weighty = 0.1;
BorderLayout b = new BorderLayout();
//Set size of Panel1
int xsizeP1 = (Frame.xsize() / 2);
int ysizeP1 = (Frame.ysize() / 3 * 2);
setPreferredSize(new Dimension(xsizeP1, ysizeP1));
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(" test ");
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//gbc.gridx = 0;
//gbc.gridy = 0;
//gbc.weightx = 1;
//gbc.weighty = 1;
//gbc.fill = GridBagConstraints.BOTH;
add(scroll, b.CENTER);
}
}
Don't set the layout of storyPanel, as it's contents have already been added and laid out, so changing the layout manager here will discard any properties you applied. Instead, set the layout in Panel1's constructor before you add any components.
Use GridBagConstraints.BOTH for the fill property. The fill property can only have one specified value
Use weightx and weighty to specify how much of the available space the component should use
For example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MainFrame 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) {
ex.printStackTrace();
}
JFrame frame = new MainFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private Panel1 storyPanel;
// private Panel2 statsPanel;
// private Panel3 commandsPanel;
public MainFrame(String title) {
super(title);
storyPanel = new Panel1();
Container p = getContentPane();
p.add(storyPanel, BorderLayout.WEST);
p.add(new JLabel("East"), BorderLayout.EAST);
p.add(new JLabel("South"), BorderLayout.SOUTH);
}
public class Panel1 extends JPanel {
public Panel1() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//Set size of Panel1
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(20, 20);
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//GridBagConstraints setup for components
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
add(scroll, gbc);
}
}
}
Having said all that, a BorderLayout would be simpler
public class Panel1 extends JPanel {
public Panel1() {
setLayout(new BorderLayout());
//Set size of Panel1
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(20, 20);
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add(scroll);
}
}
i tried a border layout and set it to center expecting it to resize but that failed as well
Would suggest that you're making a fundamental mistake some where, as it works fine for me. Remember, set the layout BEFORE you add any components to the container
I'm coding a GUI by hand and I've run into difficulty positioning a JLabel on a JPanel. I'm trying to put it in the top left hand side above the JTextField but it's defaulting to the middle even though I'm settings the bounds:
Relevant code:
JPanel mainPanel = new JPanel();
JLabel myFleetLabel = new JLabel("My Fleet");
myFleetLabel.setBounds(1,1, 10, 10);
mainPanel.add(myFleetLabel);
add(mainPanel);
Here's what it looks like:
There are a few ways you might be able achieve this, one might be to use a GridBagLayout as the primary layout manager, for example
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
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 {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
JLabel label = new JLabel("My Fleet: ");
add(label, gbc);
JTextArea ta = new JTextArea(10, 20);
gbc.gridx++;
add(new JScrollPane(ta), gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(new JScrollPane(new JTextArea(5, 10)), gbc);
JPanel actions = new JPanel();
actions.add(new JButton("Create Ship"));
actions.add(new JButton("Flip Coins"));
gbc.gridy++;
add(actions, gbc);
}
}
}
See Laying Out Components Within a Container and How to Use GridBagLayout for more details.
Remember, it's unlikely that a single layout manager will solve all your problems and some times you will need to use two or more to accomplish the overall effect
Typically you need to use layouts to place objects in a containter. You should get acquainted with layouts to really code properly in swing.
The being said, the reason your code isn't working as is, is because containers have a layout by default. You CAN remove the layout as follows
mainPanel.setLayout(null);
but this is very bad practice and should be avoided always.
Reference to the given code..i can access the print statement inside the if statement in for-loop(inside try-catch block) but the checkboxes are not adding.
I am using the revalidating and repaint function but still its not working.
The for loop inside the try-catch block is running except for the adding jscrollpane. Where am i wrong?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.anurag;
import com.anurag.HttpURLConnectionExample;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
/**
*
* #author Anurag
*/
public class MainGui {
static JFrame frame = new JFrame("Rest Testing");
public static void main(String args[]) {
frame.setLayout(new FlowLayout());
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField path = new JTextField("getresponse.xls");
frame.add(path);
JButton upload = new JButton("Upload");
frame.add(upload);
upload.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
JScrollPane jscrlpLabel = new JScrollPane(new JLabel(
"<HTML>A<br>B<br>C<br>D<br>E<br>F<br>G<br>H<br></HTML>"));
jscrlpLabel.setPreferredSize(new Dimension(200, 100));
frame.add(jscrlpLabel);
frame.revalidate();
frame.repaint();
try{
System.out.println(path.getText());
HttpURLConnectionExample http = new HttpURLConnectionExample();
int noOfRows = http.setPath(path.getText());
Workbook workbook = Workbook.getWorkbook(new File(path.getText()));
Sheet sheet = workbook.getSheet(0);
Cell cell= sheet.findCell("S. No.");
int col=cell.getColumn();
int row=cell.getRow();
row=row+2;
//System.out.println("row="+row+"col="+col);
for(int i=row;i<noOfRows;i++,row++)
{
int p=http.readFile(col,row);
if(p==1){
JCheckBox cb = new JCheckBox("CheckBox");
JScrollPane jscrlp = new JScrollPane(cb);
jscrlp.setPreferredSize(new Dimension(140, 95));
frame.add(jscrlp);
frame.revalidate();
frame.repaint();
System.out.println("Checkbox created");
}
else if(p==2){
JCheckBox cb1 = new JCheckBox("CheckBox ");
Box box = Box.createVerticalBox();
box.add(cb1);
JScrollPane jScrollPane1 = new JScrollPane(box);
jScrollPane1.setPreferredSize(new Dimension(140, 95));
frame.add(jScrollPane1);
frame.revalidate();
frame.repaint();
System.out.println("Checkbox created with textfield");
}
}
http.getData();
}catch(Exception e){System.out.println("Exception is "+e);}
}
});
//JOptionPane.showMessageDialog(null, "Done", "Alert", WIDTH);
JCheckBox a = new JCheckBox("A");
JCheckBox b = new JCheckBox("B");
JLabel label = new JLabel("Option");
Box box = Box.createVerticalBox();
box.add(label);
box.add(a);
box.add(b);
JScrollPane jscrlpBox = new JScrollPane(box);
jscrlpBox.setPreferredSize(new Dimension(240, 150));
//f.add(jscrlpLabel);
frame.add(jscrlpBox);
frame.setVisible(true);
}
}
Start by having a read through Creating a GUI With JFC/Swing, Laying Out Components Within a Container, Concurrency in Swing and How to Use Scroll Panes
Box is not really a "visible" component, it's meant as a feature to be used with BoxLayout
You're adding multiple JScrollPanes to the single view, which kind of feels weird to me
Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
You're updating the UI from within the Event Dispatching Thread, but the process by which you're making your decisions may take time to run, this could make the UI look like it's doing nothing until the actionPerformed method exist
There's little point in calling revaldiate all the time, leave it until you have finished updating the whole UI, it will provide better performance in the long run
Start by creating a JPanel which you then wrap a JScrollPane around, add the JScrollPane to the base UI
As required, add and remove components from this JPanel, for example...
public class MainGui {
public static void main(String args[]) {
new MainGui();
}
private JFrame frame = new JFrame("Rest Testing");
private JPanel checkboxes;
public MainGui() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField path = new JTextField("getresponse.xls");
JPanel fields = new JPanel();
fields.add(path);
JButton upload = new JButton("Upload");
fields.add(upload);
frame.add(fields, BorderLayout.NORTH);
checkboxes = new JPanel(new GridBagLayout());
JScrollPane scrollPane = new JScrollPane(checkboxes);
frame.add(scrollPane);
upload.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1;
checkboxes.add(new JLabel("<HTML>A<br>B<br>C<br>D<br>E<br>F<br>G<br>H<br></HTML>"), gbc);
try {
int noOfRows = 100;
for (int row = 0; row < noOfRows; row++, row++) {
int p = (int) ((Math.random() * 2) + 1);
System.out.println(p);
if (p == 1) {
JCheckBox cb = new JCheckBox("CheckBox");
checkboxes.add(cb, gbc);
} else if (p == 2) {
JCheckBox cb1 = new JCheckBox("CheckBox ");
JPanel stuff = new JPanel();
stuff.add(cb1);
stuff.add(new JTextField(10));
checkboxes.add(stuff, gbc);
}
}
} catch (Exception e) {
System.out.println("Exception is " + e);
}
checkboxes.revalidate();
checkboxes.repaint();
}
});
//JOptionPane.showMessageDialog(null, "Done", "Alert", WIDTH);
JCheckBox a = new JCheckBox("A");
JCheckBox b = new JCheckBox("B");
JLabel label = new JLabel("Option");
JPanel stuff = new JPanel();
stuff.add(label);
stuff.add(a);
stuff.add(b);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1;
checkboxes.add(stuff, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Now, I'm not 100% sure, but you might find using a JTable produces the look you're after. How to Use Tables
You can't add the checkboxes directly to the scroll pane, you need to make a list model. You will need a Scroll Pane, a list renderer, a model, and a custom JCheckboxList class. See the following questions:
How do I make a list with checkboxes in Java Swing?
Also, you might run into a problem that I did where the JScrollPane's viewport:
Components in JList are Hidden by White Square Thing Until Clicked
I'm trying to do as the title says.
I've got an efficient way for posting several of the same swing objects to a frame by storing them in an array and adding them using a for loop like so:
JLabel[] contrllabels= new JLabel[8];
contrllabels[0] = new JLabel("SCF Type: ");
contrllabels[1] = new JLabel("Units: ");
contrllabels[2] = new JLabel("Spherical Harmonics: ");
contrllabels[3] = new JLabel("Molecular Charge: ");
contrllabels[4] = new JLabel("PP: ");
contrllabels[5] = new JLabel("DFT Type: ");
contrllabels[6] = new JLabel("Max Iterations: ");
contrllabels[7] = new JLabel("Mult: ");
for(int i = 0;i<contrllabels.length;i++){
c.gridy = i;
frame.add(contrllabels[i],c);
}
But what if there are several swing objects of different types? I've got several combo boxes and textfields which I'd like to be added to the frame in a similar manner. I use gridbaglayout so if I don't use a for loop, I end up with lots of unnecessary code due to giving the constraints new values every time I want a different object added.
Is there such thing as an array of references which point to these different objects which I can then iterate through to add to the frame? Something like
JTextField tf = new JTextField(5);
JComboBox cb = new JComboBox("example");
Swing[] array = {tf,cb}
for(int i = 0;i<array.length;i++){
c.gridy = i;
frame.add(array[i],c);
}
I know such an array doesn't exist, but is there some way of implementing such a thing? It would greatly reduce the number of lines in my code and make it less confusing.
Thank you
You could use an array or collection of a common super type such as an array or ArrayList of JComponent. I'm curious if you're using a parallel array of GridBagConstraints to go with each component that is being added -- ugh. I often use arrays of components but usually if they are like components such as JLabel/JTextField pairs or a cluster of JRadioButtons.
As an aside, for my money, I try to avoid GridBagLayout as much as possible and instead nest containers that use the more coder-friendly layouts.
For instance this small GUI was made with a combination of FlowLayout, BoxLayout, BorderLayout and GridLayout:
The large JPanel that holds the whole GUI uses BorderLayout, The JTextArea in the center is placed BorderLayout.CENTER, the Provider JLabel and JTextField at the top are in a FlowLayout JPanel that is placed overall BorderLayout.NORTH, the bottom buttons are in a JPanel that uses GridLayout(1, 0, 5, 0) which is held in another JPanel that uses FlowLayout which is placed in the GUI BorderLayout.SOUTH, and the stuff on the right are in a BoxLayout using JPanel.
For example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
#SuppressWarnings("serial")
public class GetLetterTextGui extends JPanel {
private static final int TA_ROWS = 20;
private static final int TA_COLS = 35;
private static final int PROVIDER_FIELD_COLS = 10;
private static final String GUI_TITLE = "Get Letter Text";
private JList letterList;
private JTextArea textarea = new JTextArea(TA_ROWS, TA_COLS);
private JTextField providerField = new JTextField(PROVIDER_FIELD_COLS);
private JCheckBox addValedictionChkBox = new JCheckBox("Add Valediction", true);
public GetLetterTextGui() {
letterList = new JList(new String[]{"Fe", "Fi", "Fo", "Fum"});
providerField.setText("John Smith, MD");
textarea.setWrapStyleWord(true);
textarea.setLineWrap(true);
JPanel northPanel = new JPanel();
northPanel.add(new JLabel("Provider:"));
northPanel.add(providerField);
JPanel southPanel = new JPanel();
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 0));
btnPanel.add(new JButton("Copy to Clipboard"));
btnPanel.add(new JButton("Clear"));
btnPanel.add(new JButton(new ExitAction()));
southPanel.add(btnPanel);
JPanel eastPanel = new JPanel();
eastPanel.setLayout(new BoxLayout(eastPanel, BoxLayout.PAGE_AXIS));
eastPanel.add(new JScrollPane(letterList));
eastPanel.add(new JPanel() {{add(addValedictionChkBox);}});
int eb = 0;
setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
setLayout(new BorderLayout(eb, eb));
add(northPanel, BorderLayout.PAGE_START);
add(eastPanel, BorderLayout.LINE_END);
add(new JScrollPane(textarea), BorderLayout.CENTER);
add(southPanel, BorderLayout.PAGE_END);
}
private class ExitAction extends AbstractAction {
private final Object MNEMONIC = new Integer(KeyEvent.VK_X);
public ExitAction() {
super("Exit");
putValue(MNEMONIC_KEY, MNEMONIC);
}
#Override
public void actionPerformed(ActionEvent evt) {
Window win = SwingUtilities.getWindowAncestor(GetLetterTextGui.this);
win.dispose();
}
}
private static void createAndShowGui() {
GetLetterTextGui mainPanel = new GetLetterTextGui();
JFrame frame = new JFrame(GUI_TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
}
}
All GUI components are JComponent objects. ArrayList<JComponent> can hold references to all of them. Give it a try:
JFrame frame = new JFrame("test");
ArrayList<JComponent> cps = new ArrayList<JComponent>();
cps.add(new JLabel("Hello"));
cps.add(new JPanel());
cps.add(new JButton("OK"));
for (JComponent widget : cps) {
frame.add(widget);
}