I am trying to make a GUI application in Java but I am having trouble in adding/updating components dynamically in JScrollPane. I have two JPanels (P1 and P2) in which P1 has a form to set parameters for application and the P2 contains some GUI components, which are updated dynamically based on the values in the P1. I need a JScrollPane on P2 to scroll, so I added JScrollPane in P2. I added both P1 and P2 to a main panel "main" and then added the main panel to a frame. But the components are not updated in P2. Can someone suggest what is the problem? I have called revalidate(), repaint() and some other methods but GUI is not updated. Below is a sample code I have written just to illustrate my problem. I need GroupLayout in my application so here I also used GroupLayout
import java.awt.event.ActionEvent;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class JframeExample extends JFrame {
private final JPanel P1;
private final JPanel P2;
private final JPanel main;
private final JScrollPane scrol;
private final JButton jButton;
private final JButton jButton2;
public JframeExample() {
P1 = new JPanel();
P2 = new JPanel();
main = new JPanel();
jButton = new JButton("Add");
jButton2 = new JButton("Remove");
scrol = new JScrollPane();
initialize();
this.add(main);
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.setSize(400, 400);
this.setVisible(true);
}
public static void main(String[] args) {
JframeExample jframeExample = new JframeExample();
}
private void addPressed(ActionEvent evt) {
System.out.println("Add Pressed");
scrol.add(new JButton());
revalidate();
}
private void removePressed(ActionEvent evt) {
System.out.println("Remove Pressed");
scrol.removeAll();
revalidate();
}
private void initialize() {
GroupLayout layout = new GroupLayout(P1);
P1.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
hGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
.addComponent(jButton).addComponent(jButton2));
layout.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
vGroup.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(jButton))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(jButton2));
layout.setVerticalGroup(vGroup);
P2.add(scrol);
jButton.addActionListener((ActionEvent evt) -> {
addPressed(evt);
});
jButton2.addActionListener((ActionEvent evt) -> {
removePressed(evt);
});
GroupLayout layoutMain = new GroupLayout(main);
main.setLayout(layoutMain);
layoutMain.setAutoCreateGaps(true);
layoutMain.setAutoCreateContainerGaps(true);
layoutMain.setHorizontalGroup(layoutMain.createSequentialGroup()
.addComponent(P1).addComponent(P2));
layoutMain.setVerticalGroup(layoutMain
.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(P1)
.addComponent(P2));
}
}
Wrapping P2 inside JScrollPane also does not work.
Yes it does, because that's the way it work. If you take the time to read through the How to use scroll panes, examine the examples and maybe even consult the JavaDocs it would provide you with the basic information you'd need to get you UI up and running.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class JframeExample extends JFrame {
private final JPanel P1;
private final JPanel P2;
private final JPanel main;
private final JScrollPane scrol;
private final JButton jButton;
private final JButton jButton2;
public JframeExample() {
P1 = new JPanel();
P2 = new JPanel();
main = new JPanel();
jButton = new JButton("Add");
jButton2 = new JButton("Remove");
scrol = new JScrollPane(P2);
initialize();
this.add(main);
this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.setSize(400, 400);
this.setVisible(true);
}
public static void main(String[] args) {
JframeExample jframeExample = new JframeExample();
}
private void addPressed(ActionEvent evt) {
System.out.println("Add Pressed");
P2.add(new JButton());
revalidate();
}
private void removePressed(ActionEvent evt) {
System.out.println("Remove Pressed");
P2.removeAll();
revalidate();
}
private void initialize() {
main.setLayout(new GridLayout(1, 2));
main.add(P1);
main.add(scrol);
jButton.addActionListener((ActionEvent evt) -> {
addPressed(evt);
});
jButton2.addActionListener((ActionEvent evt) -> {
removePressed(evt);
});
P1.add(jButton);
P1.add(jButton2);
}
}
Word of warning GroupLayout really isn't meant for hand coding, it's really designed for UI editors.
Related
I am trying to understand implemented ActionListener. I couldn't find a way out to add it to JButtons in an othor method. I simply trying to add show and hide action to buttons but I could't. Any help? My code is here. There are 3 colored JPanel and every button should hide or show related color JPanel.
import java.awt.Color;
import java.awt.GridLayout;
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.JPanel;
import javax.swing.border.Border;
public class ShowHidePanels implements ActionListener {
public static void main(String[] args) {
new ShowHidePanels();
}
public ShowHidePanels() {
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(1, 2));
frame.add(bluePanel());
frame.add(greenPanel());
frame.add(redPanel());
frame.add(buttonPanel());
frame.setSize(950, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static JPanel greenPanel() {
String greenTitle = "Green Panel";
Border greenBorder = BorderFactory.createTitledBorder(greenTitle);
JPanel greenPanel = new JPanel();
greenPanel.setBorder(greenBorder);
greenPanel.setBackground(new Color(165, 195, 70));
return greenPanel;
}
public static JPanel bluePanel() {
String blueTitle = "Blue Panel";
Border blueBorder = BorderFactory.createTitledBorder(blueTitle);
JPanel bluePanel = new JPanel();
bluePanel.setBorder(blueBorder);
bluePanel.setBackground(new Color(80, 105, 212));
return bluePanel;
}
public static JPanel redPanel() {
String redTitle = "Kirmizi Panel";
Border redBorder = BorderFactory.createTitledBorder(redTitle);
JPanel redPanel = new JPanel();
redPanel.setBorder(redBorder);
redPanel.setBackground(new Color(255, 100, 90));
return redPanel;
}
public static JPanel buttonPanel() {
Border greyBorder = BorderFactory.createTitledBorder("Grey Panel");
JButton b_BlueHide = new JButton("Hide Blue");
JButton b_BlueShow = new JButton("Show Blue");
JButton b_RedHide = new JButton("Hide Red");
JButton b_RedShow = new JButton("Show Red");
JButton b_GreenHide = new JButton("Hide Green");
JButton b_GreenShow = new JButton("Show Green");
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 1));
buttonPanel.setBorder(greyBorder);
buttonPanel.setBackground(new Color(200, 200, 200));
buttonPanel.add(b_BlueHide);
buttonPanel.add(b_BlueShow);
buttonPanel.add(b_GreenHide);
buttonPanel.add(b_GreenShow);
buttonPanel.add(b_RedHide);
buttonPanel.add(b_RedShow);
return buttonPanel;
}
#Override
public void actionPerformed(ActionEvent event) {
}
}
static is not your friend. It has its place and purpose, but this is not one of them. Learn to live without it.
Instead, your methods and components should be instance based (that is, obviously, not static and reliant on a instance of the parent class).
The following example is slightly modified and makes use of a CardLayout to switch the panels, which is a lot more fun then trying to handle z-order issues ;)
Take a look at How to Use CardLayout
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
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.JPanel;
import javax.swing.border.Border;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel implements ActionListener {
private CardLayout cardLayout;
private JPanel contentPane;
public TestPane() {
cardLayout = new CardLayout();
setLayout(new BorderLayout());
contentPane = new JPanel(cardLayout);
contentPane.add(bluePanel(), "blue");
contentPane.add(greenPanel(), "green");
contentPane.add(redPanel(), "red");
add(contentPane);
add(buttonPanel(), BorderLayout.SOUTH);
}
public JPanel greenPanel() {
String greenTitle = "Green Panel";
Border greenBorder = BorderFactory.createTitledBorder(greenTitle);
JPanel greenPanel = new JPanel();
// Demonstration purposes only -----//
greenPanel.setPreferredSize(new Dimension(200, 200));
// ----- Demonstration purposes only //
greenPanel.setBorder(greenBorder);
greenPanel.setBackground(new Color(165, 195, 70));
return greenPanel;
}
public JPanel bluePanel() {
String blueTitle = "Blue Panel";
Border blueBorder = BorderFactory.createTitledBorder(blueTitle);
JPanel bluePanel = new JPanel();
// Demonstration purposes only -----//
bluePanel.setPreferredSize(new Dimension(200, 200));
// ----- Demonstration purposes only //
bluePanel.setBorder(blueBorder);
bluePanel.setBackground(new Color(80, 105, 212));
return bluePanel;
}
public JPanel redPanel() {
String redTitle = "Kirmizi Panel";
Border redBorder = BorderFactory.createTitledBorder(redTitle);
JPanel redPanel = new JPanel();
// Demonstration purposes only -----//
redPanel.setPreferredSize(new Dimension(200, 200));
// ----- Demonstration purposes only //
redPanel.setBorder(redBorder);
redPanel.setBackground(new Color(255, 100, 90));
return redPanel;
}
public JPanel buttonPanel() {
Border greyBorder = BorderFactory.createTitledBorder("Grey Panel");
JButton blue = new JButton("Blue");
JButton red = new JButton("Red");
JButton green = new JButton("Green");
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 1));
buttonPanel.setBorder(greyBorder);
buttonPanel.setBackground(new Color(200, 200, 200));
buttonPanel.add(blue);
buttonPanel.add(green);
buttonPanel.add(red);
blue.addActionListener(this);
green.addActionListener(this);
red.addActionListener(this);
return buttonPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("blue".equalsIgnoreCase(cmd)) {
cardLayout.show(contentPane, "blue");
} else if ("red".equalsIgnoreCase(cmd)) {
cardLayout.show(contentPane, "red");
} else if ("green".equalsIgnoreCase(cmd)) {
cardLayout.show(contentPane, "green");
}
}
}
}
There's a lot of room for simplification and reduction of duplicate workflows, but I'll leave that for you to figure out ;)
So i have three panels that i have three different buttons for to change them each to their respective colors. I need to add a fourth button that will return all three panels to their original default light gray color. I add this "reset" button and it only changes the first panel back. What am i doing wrong?
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class PanelDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
private JPanel redPanel;
private JPanel whitePanel;
private JPanel bluePanel;
public static void main(String[] args)
{
PanelDemo gui = new PanelDemo();
gui.setVisible(true);
}
public PanelDemo()
{
super("Panel Demonstration");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel biggerPanel = new JPanel();
biggerPanel.setLayout(new GridLayout(1, 3));
redPanel = new JPanel();
redPanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(redPanel);
whitePanel = new JPanel();
whitePanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(whitePanel);
bluePanel = new JPanel();
bluePanel.setBackground(Color.LIGHT_GRAY);
biggerPanel.add(bluePanel);
add(biggerPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.LIGHT_GRAY);
buttonPanel.setLayout(new FlowLayout());
JButton redButton = new JButton("Red");
redButton.setBackground(Color.RED);
redButton.addActionListener(this);
buttonPanel.add(redButton);
JButton whiteButton = new JButton("White");
whiteButton.setBackground(Color.WHITE);
whiteButton.addActionListener(this);
buttonPanel.add(whiteButton);
JButton blueButton = new JButton("Blue");
blueButton.setBackground(Color.BLUE);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
JButton resetButton = new JButton("Reset");
resetButton.setBackground(Color.LIGHT_GRAY);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
add(buttonPanel, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand();
if (buttonString.equals("Red"))
redPanel.setBackground(Color.RED);
else if (buttonString.equals("White"))
whitePanel.setBackground(Color.WHITE);
else if (buttonString.equals("Blue"))
bluePanel.setBackground(Color.BLUE);
else if (buttonString.equals("Reset"))
redPanel.setBackground(Color.LIGHT_GRAY);
else if (buttonString.equals("Reset"))
bluePanel.setBackground(Color.LIGHT_GRAY);
else if (buttonString.equals("Reset"))
whitePanel.setBackground(Color.LIGHT_GRAY);
else
System.out.println("Unexpected error.");
}
}
Here was your problem. You had if else's on each panel for the reset. Compare the code below to what you have. It was just a simple logic issue.
public void actionPerformed(ActionEvent e) {
String buttonString = e.getActionCommand();
if (buttonString.equals("Red"))
redPanel.setBackground(Color.RED);
else if (buttonString.equals("White"))
whitePanel.setBackground(Color.WHITE);
else if (buttonString.equals("Blue"))
bluePanel.setBackground(Color.BLUE);
else if (buttonString.equals("Reset")) {
redPanel.setBackground(Color.LIGHT_GRAY);
bluePanel.setBackground(Color.LIGHT_GRAY);
whitePanel.setBackground(Color.LIGHT_GRAY);
}
else
System.out.println("Unexpected error.");
And a couple of suggestions.
Don't extend JFrame. Just use an instance of it. It's better technique.
Put the following as the last statement in your constructor. It will center the panel on your screen.
setLocationRelativeTo(null);
// or when using a frame instance.
frame.setLocationRelativeTo(null);
I'm trying to make a program that can add name and address.
I'm trying to use the GridLayout but there is no buttons that shows up.
What did I do wrong here?
Thanks
Hello. I'm trying to make a program that can add name and address.
I'm trying to use the GridLayout but there is no buttons that shows up.
What did I do wrong here?
Thanks
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class AddressBookProgram extends JFrame {
public AddressBookProgram() {
super("Test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(new GridPanel());
setSize(300, 300);
setVisible(true);
}
private final class GridPanel extends JPanel {
private JPanel bookPanel;
private JPanel buttonPanel;
private JButton add;
private JButton delete;
private JButton search;
private JButton displayAll;
private JButton exit;
private ActionListener buttons = new ButtonListener();
private GridPanel() {
setLayout(new GridLayout(2, 3));
setBackground(Color.green);
bookPanel = new JPanel();
bookPanel.setBackground(Color.white);
buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
add = new JButton("Add");
delete = new JButton("Delete");
search = new JButton("Search");
displayAll = new JButton("Display All");
exit = new JButton("Exit");
add.addActionListener(buttons);
delete.addActionListener(buttons);
search.addActionListener(buttons);
displayAll.addActionListener(buttons);
exit.addActionListener(buttons);
buttonPanel.add(add);
buttonPanel.add(delete);
buttonPanel.add(search);
buttonPanel.add(displayAll);
buttonPanel.add(exit);
}
private class ButtonListener implements ActionListener {
/**
* <p>Updates the watchLabel label when button is pushed.</p>
* #param event a button is pushed
*/
public void actionPerformed(ActionEvent event) {
if (event.getSource() == add) {
}
if (event.getSource() == delete) {
}
if (event.getSource() == search) {
}
if (event.getSource() == displayAll) {
}
if (event.getSource() == exit) {
}
}
}
}
public static void main(String[] args) {
new AddressBookProgram();
}
}
This is because you create buttonPanel but you don't add it. Just write this line:
add(buttonPanel);
This would make your code:
buttonPanel.add(add);
buttonPanel.add(delete);
buttonPanel.add(search);
buttonPanel.add(displayAll);
buttonPanel.add(exit);
add(buttonPanel);
I want to open a new JFrame by clicking a button (btnAdd); I have tried to create an actionlistener but I am having no luck; the code runs but nothing happens when the button is clicked. The methods in question are the last two in the following code. Any help is much appreciated!
package AdvancedWeatherApp;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionListener;
import weatherforecast.FetchWeatherForecast;
public class MainFrame extends JFrame implements ListSelectionListener {
private boolean initialized = false;
private Actions actions = new Actions();
private javax.swing.JScrollPane jspFavouritesList = new javax.swing.JScrollPane();
private javax.swing.DefaultListModel<String> listModel = new javax.swing.DefaultListModel<String>();
private javax.swing.JList<String> favouritesList = new javax.swing.JList<String>(
listModel);
private javax.swing.JLabel lblAcknowledgement = new javax.swing.JLabel();
private javax.swing.JLabel lblTitle = new javax.swing.JLabel();
private javax.swing.JButton btnAdd = new javax.swing.JButton();
private javax.swing.JButton btnRemove = new javax.swing.JButton();
public void initialize() {
initializeGui();
initializeEvents();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
/**
*
*/
private void initializeGui() {
if (initialized)
return;
initialized = true;
this.setSize(500, 400);
Dimension windowSize = this.getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(screenSize.width / 2 - windowSize.width / 2,
screenSize.height / 2 - windowSize.height / 2);
Container pane = this.getContentPane();
pane.setLayout(new BorderLayout());
setLayout(new BorderLayout());
setTitle("Favourite Weather Locations");
JPanel jpSouth = new JPanel();
jpSouth.setLayout(new FlowLayout());
JPanel jpNorth = new JPanel();
jpNorth.setLayout(new FlowLayout());
JPanel jpCenter = new JPanel();
jpCenter.setLayout(new BoxLayout(jpCenter, BoxLayout.PAGE_AXIS));
JPanel jpEast = new JPanel();
JPanel jpWest = new JPanel();
getContentPane().setBackground(Color.WHITE);
jpEast.setBackground(Color.WHITE);
jpWest.setBackground(Color.WHITE);
jpCenter.setBackground(Color.WHITE);
getContentPane().add(jspFavouritesList);
jpCenter.add(jspFavouritesList);
jspFavouritesList.setViewportView(favouritesList);
favouritesList
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
favouritesList.addListSelectionListener(this);
jpCenter.add(btnAdd);
jpCenter.add(btnRemove);
jpCenter.setAlignmentY(CENTER_ALIGNMENT);
btnAdd.setText("Add Location");
btnAdd.setAlignmentX(Component.CENTER_ALIGNMENT);
btnAdd.setFont(new Font("Calibri", Font.PLAIN, 18));
jpCenter.add(btnRemove);
btnRemove.setText("Remove Location");
btnRemove.setAlignmentX(Component.CENTER_ALIGNMENT);
btnRemove.setFont(new Font("Calibri", Font.PLAIN, 18));
getContentPane().add(jpEast, BorderLayout.EAST);
getContentPane().add(jpWest, BorderLayout.WEST);
getContentPane().add(jpSouth);
jpSouth.add(lblAcknowledgement);
add(lblAcknowledgement, BorderLayout.SOUTH);
lblAcknowledgement.setText(FetchWeatherForecast.getAcknowledgement());
lblAcknowledgement.setHorizontalAlignment(SwingConstants.CENTER);
lblAcknowledgement.setFont(new Font("Tahoma", Font.ITALIC, 12));
getContentPane().add(jpNorth);
jpNorth.add(lblTitle);
add(lblTitle, BorderLayout.NORTH);
lblTitle.setText("Your Favourite Locations");
lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
lblTitle.setFont(new Font("Calibri", Font.PLAIN, 32));
lblTitle.setForeground(Color.DARK_GRAY);
getContentPane().add(jpCenter);
}
private void initializeEvents() {
// TODO: Add action listeners, etc
}
public class Actions implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
command = command == null ? "" : command;
// TODO: add if...if else... for action commands
}
}
public void dispose() {
// TODO: Save settings
// super.dispose();
System.exit(0);
}
public void setVisible(boolean b) {
initialize();
super.setVisible(b);
}
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
public void actionPerformed(ActionEvent evt){
if (evt.getSource() == btnAdd) {
showNewFrame();
//OPEN THE SEARCH WINDOW
}
}
private void showNewFrame() {
JFrame frame = new JFrame("Search Window" );
frame.setSize( 500,120 );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
Although you have implemented the actionPerformed method as per the ActionListener interface, you class is not of that that type as you haven't implemented the interface. Once you implement that interface and register it with the JButton btnAdd,
btnAdd.addActionListener(this);
the method will be called.
A more compact alternative might be to use an anonymous interface:
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle button ActionEvent & display dialog...
}
});
Side notes:
Using more than one JFrame in an application creates a lot of overhead for managing updates that may need to exist between frames. The preferred approach is to
use a modal JDialog if another window is required. This is discussed more here.
Use this :
btnAdd.addActionListener(this);
#Override
public void actionPerformed(ActionEvent e)
{
MainFrame frame = new MainFrame();
frame.setVisible(true);
}
Type this inside the button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
ActionListener ActList = new ActionListener();
ActList.setVisible(true);
}
see my last line
{
ActList.setVisible(true);
}
As i am new to java swing, i am finding a little difficulty in integrating the JFileChooser with JList. My goal is to select a file from the dialog-box(JFileChooser) and click 'add' so that it gets added to the JList automatically and the same mechanism with 'remove'. I tried going through a few tutorials and a few hints but it dint work. It would be really great if any of you could help me with this step.
Thanks in advance..!!
package examples;
import java.awt.BorderLayout;
import java.awt.Color;
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.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JSplitPane;
//import javax.swing.SwingConstants;
class SplitPane extends JFrame
{
private static final long serialVersionUID = 1L;
private JSplitPane splitPaneV;
private JSplitPane splitPaneH;
private JLayeredPane panel1;
private JPanel panel2;
private JPanel panel3;
private JButton add;
private JButton remove;
private JScrollBar scrollBar;
private JList list;
public SplitPane()
{
setTitle("AdditionalLoaderInformation");
setBackground(Color.blue);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
topPanel.setPreferredSize(new Dimension(700, 500));
getContentPane().add(topPanel);
// Create the panels
createPanel1();
createPanel2();
createPanel3();
// Create a splitter pane
splitPaneV = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
topPanel.add(splitPaneV, BorderLayout.CENTER);
splitPaneH = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPaneH.setLeftComponent(panel1);
splitPaneH.setRightComponent(panel2);
splitPaneV.setLeftComponent(splitPaneH);
splitPaneV.setRightComponent(panel3);
scrollBar = new JScrollBar();
scrollBar.setOrientation(JScrollBar.HORIZONTAL);
panel3.add(scrollBar, BorderLayout.SOUTH);
list = new JList();
panel3.add(list, BorderLayout.CENTER);
}
public void createPanel1()
{
panel1 = new JLayeredPane();
panel1.setLayout(new BorderLayout());
}
public void createPanel2()
{
panel2 = new JPanel();
add = new JButton("ADD");
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
************************************
}
});
panel2.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
panel2.add(add);
remove = new JButton("REMOVE");
remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
removeActionPerformed(e);
}
private void removeActionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
panel2.add(remove);
}
public void createPanel3()
{
panel3 = new JPanel();
panel3.setLayout(new BorderLayout());
panel3.setPreferredSize(new Dimension(400, 100));
panel3.setMinimumSize(new Dimension(100, 50));
final JFileChooser fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(true);
//fileChooser.showOpenDialog(fileChooser);
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fileChooser .setDialogTitle("OPEN");
panel3.add(fileChooser, BorderLayout.NORTH);
//fileChooser.addActionListener(new ActionListener()
// {
// public void actionPerformed(ActionEvent e)
//{
// }
//});
}
public static void main(String args[]) {
// Create an instance of the test application
SplitPane mainFrame = new SplitPane();
mainFrame.pack();
mainFrame.setVisible(true);
}
}
When you get a new file name in your chooser's action listener, shown here, add it to (or remove it from) the list's models, as shown in this example.
Addendum: To display the file's content in the JList, you'll need to create a suitable renderer using one of the text components.
Read the JFileChooser tutorial
If the above step is not sufficient, take a look at the class javadoc of JFileChooser and note the APPROVE_OPTION and the getSelectedFile method. This should allow you to obtain the file
Read the JList tutorial
If the above step is not sufficient, take a look at the available API of JList and ListModel, and more in particular the default implementation DefaultListModel which contains add and remove methods