JTabbedPane not switching tab contents - java

I'm having an issue with JTabbedPane, in that the contents of individual tabs aren't showing up (Every time I click a new tab, the active tab changes but the contents do not, so I see the same content no matter which tab is selected.).
I'm trying to write an IDE for my own programming language, but have never worked with JTabbedPane before. My tabbed pane consists of JEditTextArea's (user-written component) housed in JScrollPanes. Here is the responsible class
package tide.editor;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.Toolkit;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import org.syntax.jedit.*;
import org.syntax.jedit.tokenmarker.*;
#SuppressWarnings("serial")
public class Editor extends JFrame implements ActionListener {
//Version ID
final static String VERSION = "0.01a";
//The editor pane houses the JTabbedPane that allows for code editing
//JPanel editorPane;
JTabbedPane tabbedPanel;
//The JTextPanes hold the source for currently open programs
ArrayList<JEditTextArea> textPanes;
//The toolbar that allows for quick opening, saving, compiling etc
JToolBar toolBar;
//Buttons for the toolbar
JButton newButton, openButton, saveButton, compileButton, runButton;
public Editor()
{
super("tIDE v" + VERSION);
setSize(Toolkit.getDefaultToolkit().getScreenSize());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
init();
setVisible(true);
textPanes.get(0).requestFocus();
}
public void init()
{
//Initialise toolbar
toolBar = new JToolBar();
toolBar.setFloatable(false);
newButton = new JButton("New");
newButton.addActionListener(this);
openButton = new JButton("Open");
openButton.addActionListener(this);
saveButton = new JButton("Save");
saveButton.addActionListener(this);
compileButton = new JButton("Compile");
compileButton.addActionListener(this);
runButton = new JButton("Run");
runButton.addActionListener(this);
toolBar.add(newButton);
toolBar.add(openButton);
toolBar.add(saveButton);
toolBar.add(compileButton);
toolBar.add(runButton);
tabbedPanel = new JTabbedPane();
textPanes = new ArrayList<JEditTextArea>();
JEditTextArea initialProgram = createTextArea("program.t");
tabbedPanel.addTab(initialProgram.getName(), new JScrollPane(initialProgram));
getContentPane().add(tabbedPanel, BorderLayout.CENTER);
add(toolBar, BorderLayout.NORTH);
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Editor();
}
});
}
JEditTextArea createTextArea(String name)
{
JEditTextArea editPane = new JEditTextArea(name);
editPane.setTokenMarker(new TTokenMarker());
textPanes.add(editPane);
return editPane;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newButton)
{
String filename = "program2";
boolean fileExists = true;
//Ensures that no duplicate files are created
while (fileExists)
{
fileExists = false;
//Get new file name from user
filename = JOptionPane.showInputDialog(null, "Enter a name for the file", "program.t");
//Cancel was clicked in the new file dialog
if (filename == null)
return;
for (JEditTextArea panes: textPanes)
{
if (panes.getName().equals(filename) || panes.getName().equals(filename.concat(".t")) || panes.getName().concat(".t").equals(filename))
fileExists = true;
}
}
//add extension if it is missing
if(!filename.endsWith(".t"))
filename = filename.concat(".t");
//Add the new "file" to the editor window in a new tab
tabbedPanel.addTab(filename, new JScrollPane(createTextArea(filename)));
tabbedPanel.setSelectedIndex(tabbedPanel.getSelectedIndex()+1);
}
if (e.getSource() == openButton)
{
File f = null;
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Choose target file location");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"t source or bytecode(.t, .tbc)", "t", "tbc");
fileChooser.setFileFilter(filter);
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
f = fileChooser.getSelectedFile();
}
//Cancel button was clicked on the open file dialog
if (f == null)
return;
//Load the contents of the selected file into the editor
else
{
JEditTextArea textArea = null;
StringBuilder inputText = null;
try {
Scanner sc = new Scanner(f);
//Add a new text area to the editor
textArea = createTextArea(f.getName());
tabbedPanel.add(new JScrollPane(textArea), textArea.getName());
//The newly added tab is set as the active tab
tabbedPanel.setSelectedIndex(tabbedPanel.getTabCount()-1);
textArea.requestFocus();
inputText = new StringBuilder();
while (sc.hasNext())
{
inputText.append(sc.nextLine() + "\n");
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
//Set the contents of the current text area to that of the opened file
textArea.setText(inputText.toString());
}
}
}
}

1) remove code lines from FileIO related try - catch blok
textArea = createTextArea(f.getName());
tabbedPanel.add(new JScrollPane(textArea), textArea.getName());
//The newly added tab is set as the active tab
tabbedPanel.setSelectedIndex(tabbedPanel.getTabCount()-1);
textArea.requestFocus();
prepare those Object before of after Input / OutputStreams
2) close() all Objects from Input / OutputStreams, in the finally block (try - catch - finally)
3) JTextComponets implements read() and write(), accepting all separators, then there no reason programatically call for "\n"
4) use SwingWorker code for FileIO

This might not be solution for the root cause, but there might be some inconsistency in your code which is causing paint issues on the TestAreas, So I would suggest you to register a TabChageListener and then repaint the ScrollPane for that specific tab, this should work:
tabbedPanel.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int selectedIndex = tabbedPane.getSelectedIndex();
// get the ScrollPane for this selectedIndex and then repaint it.
}
});

I've been struggling with this very problem for the last couple of hours.
In fact, it doesn't matter how many JEditTextArea you instantiate, they all rely on the same SyntaxDocument, thus the same text. That's just the way it's coded in JEditTextArea.
In constructor public JEditTextArea(TextAreaDefaults defaults) you will need to find the line:
setDocument(defaults.document);
and replace it with:
setDocument(new SyntaxDocument());
and it will instantiate a brand new Document every time you make a new JEditTextArea.

Related

How to prevent that closing a JDialog closes the entire application

I have a main(screen) gui window and need to open a few "multi input" windows (jdialog or when not possible jframe), for example to add preferences (4 textfields with 2 filechoosers and 2 radiobuttons).
When pressing OK/Cancel in these JDialogs (or JFrames), my entire application closes.
I don't want that. How can I prevent that?
First try: I tried the intelliJ option "New -> Create Dialog class", which gives me a JDialog with OK/Cancel button. Pressing one of the buttons closes the JDialog and my entire application.
Second try: I wrote a class "by hand" which creates a JDialog (and also tried JFrame). Again: Pressing one of the buttons closes the JDialog and my entire application.
I removed "dispose()" and "setVisible(false)" options from theJDialog (JFrame), but still my entire application is closed.
main class method
public class mainScreen {
// Menu action listener (only relevant options)
class MenuActionListener implements ActionListener {
// menuListener
public void actionPerformed(ActionEvent ev) {
//myVariables myVars = new myVariables();
String[] dummy = null;
System.out.println("Selected: " + ev.getActionCommand());
switch(ev.getActionCommand()) {
case "Preferences":
showPreferencesDialog();
case "Exit":
System.exit(0);
break;
}
// method that opens the external class (see below in following code block)
private void showPreferencesDialog() {
prefJDialog myprefs = new prefJDialog(prefsPanel);
myprefs.showDialog();
boolean okPressed = myprefs.isOkPressed();
if (okPressed) {
JOptionPane.showMessageDialog(mainScreen.this.rootPanel,"OK pressed","About jExifToolGUI",JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(mainScreen.this.rootPanel,"Cancel pressed","About jExifToolGUI",JOptionPane.INFORMATION_MESSAGE);
}
}
// This is the class which is mention in the manifest
public mainScreen(JFrame frame) {
boolean preferences = false;
Preferences prefs = Preferences.userRoot();
createmyMenuBar(frame);
groupRadiobuttonsandListen();
fileNamesTableListener();
try {
myUtils.DisplayLogo(mainScreen.this.iconLabel);
} catch(IOException ex) {
System.out.println("Error reading Logo");
}
preferences = check_preferences();
if (!preferences) {
myUtils.checkExifTool(mainScreen.this.rootPanel);
}
programButtonListeners();
}
// main method in my main class for my project
public static void main(String[] args) {
JFrame frame = new JFrame("jExifToolGUI");
frame.setContentPane(new mainScreen(frame).rootPanel);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
The JDialog class/method that is called from the main class
package org.hvdw.jexiftoolgui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class prefJDialog extends JDialog {
private JButton okButton;
private JButton cancelButton;
private JPanel prefsPanel;
private boolean okPressed;
public prefJDialog(JPanel prefsPanel) {
super(JOptionPane.getFrameForComponent(prefsPanel), true);
this.prefsPanel = prefsPanel;
setTitle("Preferences");
initDialog();
}
public void showDialog() {
setSize(800, 768);
double x = getParent().getBounds().getCenterX();
double y = getParent().getBounds().getCenterY();
setLocation((int) x - getWidth() / 2, (int) y - getHeight() / 2);
setVisible(true);
}
private void initDialog() {
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
pane.setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));
add(pane);
pane.add(Box.createVerticalGlue());
FlowLayout l = new FlowLayout(FlowLayout.RIGHT);
JPanel buttonsPane = new JPanel(l);
okButton = new JButton("Save"); //$NON-NLS-1$
buttonsPane.add(okButton);
pane.getRootPane().setDefaultButton(okButton);
cancelButton = new JButton("CANCEL"); //$NON-NLS-1$
buttonsPane.add(cancelButton);
buttonsPane.setMaximumSize(new Dimension(Short.MAX_VALUE, (int) l.preferredLayoutSize(buttonsPane).getHeight()));
pane.add(buttonsPane);
addListeners();
}
private void addListeners() {
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//saveProperties();
setVisible(false);
okPressed = true;
//close();
// dispose();
}
});
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
//dispose();
//close();
okPressed = false;
}
});
}
public boolean isOkPressed() {
return okPressed;
}
/*public void close() {
WindowEvent winClosingEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}*/
}
So how do I prevent that upon clicking OK or Cancel in the JDialog, the entire application closes. That needs to stay open until the user clicks the "window close" X in the top-right, or from the menu "File -> Exit"
I have searched Google for several days, but can't find a solution (and one same question without answer).
Edit:
After Patrick's answer I changed the close method to
public void close() {
this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
}
And removed the /* and */.
I also activated the close(); in the listeners again, but it doesn't make a difference. My main app is still closed.
switch(ev.getActionCommand()) {
case "Preferences":
showPreferencesDialog();
case "Exit":
System.exit(0);
break;
And the problem is that you don't have a break statement in your switch case so the code falls through to the "Exit" logic and does a System.exit(0)
This is why we need a proper "MCVE" with every question. When you post random pieces of code we can't see the entire logic flow.

JFrame, trying to make button run another class

Pretty much what I'm trying to do is make a custom installer, I have buttons and that working fine but I want to run another class called CopyDir.java when I click on the button so that it copies the necessary files to the correct directory. Problem is, is that I'm a bit stumped on how to do this.
public class Frame extends JFrame implements ActionListener {
JPanel pane = new JPanel();
JButton PC = new JButton("Install Mod (PC)");
JButton Steam = new JButton("Install Mod (Steam)");
JLabel Text = new JLabel("Welcome to the BTD 5 Mod Installer");
JLabel Text2 = new JLabel("Click on the button that matches your version of BTD 5");
JLabel Text3 = new JLabel("To install it for the version that you are using");
JLabel Text4 = new JLabel("© Nixxx60/Nanikos");
Frame() {
super("BTD 5 Mod Installer");
setBounds(100, 100, 400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
con.add(pane);
PC.setMnemonic('P');
PC.addActionListener(this);
pane.add(PC);
PC.requestFocus();
con.add(pane);
Steam.setMnemonic('P');
Steam.addActionListener(this);
pane.add(Steam);
Steam.requestFocus();
setVisible(true);
pane.add(Text);
pane.add(Text2);
pane.add(Text3);
pane.add(Text4);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == PC) {
JOptionPane.showMessageDialog(null, "Mod has been installed on PC/Cracked Edition!", "BTD 5 Installer",
JOptionPane.PLAIN_MESSAGE);
setVisible(true);
}
if (source == Steam) {
JOptionPane.showMessageDialog(null, "Mod has been installed for Steam Edition!", "BTD 5 Installer",
JOptionPane.PLAIN_MESSAGE);
setVisible(true);
}
}
public static void main(String args[]) {
new Frame();
}
}
Also, here is the code for the "CopyDir.java" Class.
package Nanikos.BTD5.Main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class CopyDir {
public static void main(String args[]) throws Exception
{
copyFiles(new File("C:\\Users\\User\\Desktop\\BTD5 Mod Installer\\Mod Files\\PC Assets"),new File("C:\\Program Files (x86)\\Steam\\steamapps\\common\\BloonsTD5"));
System.out.println("Files Copied");
}
public static void copyFiles(File src,File des) throws Exception
{
if(src.isDirectory())
{
if(!des.exists()) des.mkdir();
String [] filePaths=src.list();
for(String filePath: filePaths)
{
File srcFile =new File(src, filePath);
File desFile =new File(des, filePath);
copyFiles(srcFile,desFile);
}
}
else
{
FileInputStream from =null;
FileOutputStream to =null;
from = new FileInputStream(src);
to = new FileOutputStream(des);
byte [] buffer=new byte[4096];
int byteReads;
while( (byteReads=from.read(buffer))!=-1 )
{
to.write(buffer,0,byteReads);
}
from.close();
to.close();
}
}
}
What you want is to launch your class as a Thread
To launch your class CopyDir as a thread, make it implement Thread, change your main method signature to this :
public void run() {
//Your code
}
Also, to pass parameters to your thread, add a constructor in your CopyDir class that takes the parameters you have and stores them as attributes, to be able to get it from your method.
Then, to launch the thread from your event listeners :
CopyDir myCopyThread = new CopyDir(inputPath,outputPath);
myCopyThread.start();
This code will create a thread that starts running CopyDir in the run() method

JFileChooser confusion

I have to write a program that essentially makes a report card, but it cannot do so until until it reads in a file either through command line arguments or by the user picking one from their browser, which means I need to use JFileChooser. I have the GUI set-up for the JFileChooser but that's all I can figure out. The dialog window opens when I click open but after picking a file the window I created (GUI) does not close. Also the program runs through all of my other methods before a file is even loaded causing other problems. I tried using a do-while loop but it just runs through the loop before I can ever open a file.
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MP1 extends JFrame implements java.awt.event.ActionListener{
static StudentAssignments geen165 = new StudentAssignments();
static boolean fileReady = false;
/**
* #param args the command line arguments
*/
public static void main(String [] args) {
do{
if(args.length == 0 || args[0].isEmpty()){//reads in input from file
//select
MP1 doIt = new MP1();
doIt.setVisible(true);
}
else{
geen165.readGradeFile(args[0]);//reads in input file from command
//argument
}
}while(!fileReady);
//test methods
JOptionPane.showMessageDialog(null, geen165.getGradeReport());
geen165.addAssignments(3, 98, 100);
geen165.saveGradeFile("NewGrades.txt");
JOptionPane.showMessageDialog(null, geen165.getGradeReport());
geen165.removeAssignment(0, 2);
JOptionPane.showMessageDialog(null, geen165.getGradeReport());
}
//JFile Chooser GUI
public MP1(){
prepareGui();
}
private void prepareGui(){
setSize(500,500);
Container window = getContentPane();
window.setLayout(new FlowLayout());
JButton open = new JButton("Open");
JButton cancel = new JButton("Cancel");
JLabel status = new JLabel("You've selected: ");
//sets file when open is pressed
open.addActionListener((ActionEvent e) -> {
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(window);
if(returnVal == JFileChooser.APPROVE_OPTION){
File fileName = chooser.getSelectedFile();
status.setText("You've selected: " + fileName.getName());
geen165.readGradeFile(fileName.getName());
fileReady=true;
}
});
//exits program if cancel is pressed
cancel.addActionListener((ActionEvent e) -> {
System.exit(1);
});
window.add(open);
window.add(cancel);
window.add(status);
setDefaultCloseOperation(HIDE_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change
//body of generated methods, choose Tools | Templates.
}
}
Any suggestions?
You are complicating a simple issue. There is no need for you to build a window and everything only to use JFileChooser. A simple solution that works is
import javax.swing.*;
public class MP1 extends JFrame {
public static void main(String[] args) {
String myFile="";
if (args.length == 0 || args[0].isEmpty()) {//reads in input from file
//select
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showOpenDialog(null);
if (returnVal!=JOptionPane.CANCEL_OPTION) {
myFile = chooser.getSelectedFile().getPath();
} else {
JOptionPane.showMessageDialog(null, "Thanks for playing!");
System.exit(0);
}
} else {
myFile = args[0];
}
JOptionPane.showMessageDialog(null, "You have selected "+myFile+". Go play!");
}
}
Notice that I check whether there is a parameter. If not, I immediately go and execute the JFileChooser. There is no need for overhead.
I removed all your class activity, because I do not have the files.
BTW, I have not tested it, but I believe that your problem comes from your new frame not being modal. Hence, the boolean variable is changed before you can do anything. But that is just an idea.
I think you need to know how JFileChooser works.
JFileChooser fc = new JFileChooser();
int optionSelected = fc.showOpenDialog(YourClassName.this);
if (optionSelected == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
... // Do what you want with the file
}
JFileChooser

JTextArea.append not displaying

I'm trying to write the contents of an array to a JTextArea. I've tried everything I can think of, and I can't understand what isn't working here. I've stripped the unnecessary stuff out of my code, here's the two relevant classfiles:
Main class:
package irclogtest;
public class BriBotMain {
public static void main(String args[]) throws Exception {
boolean startup = true;
//frame test launch
BriDisplayGUI data = new BriDisplayGUI(startup);
data.irclog.append("BriBot Startup Successful!" + "\n");
//example access through function when startup is false (only in main class for sample code to demonstrate issue)
try {
BriDisplayGUI data2 = new BriDisplayGUI(false); //tells us which class we're accessing
String[] textForGUI = new String[2]; //tells us the array has 2 lines
textForGUI[0] = "this is the first line"; //set the first line of the array to this text
textForGUI[1] = "this is the second";
data2.arrayToDisplay(textForGUI); //appends contents of array to text window
}
catch(Exception e) {
System.out.println(e);
}
}
}
GUI display class:
package irclogtest;
import java.awt.event.*;
import java.io.IOException;
import javax.swing.*;
public class BriDisplayGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = -7811223081379421773L;
String file_name = "C:/Bribot/logfile.txt";
//these lines create the objects we use
JFrame frame = new JFrame();
JPanel pane = new JPanel();
JButton pressme = new JButton("Click here");
JButton pressme2 = new JButton("Also here");
JTextArea irclog = new JTextArea( 20, 70);
JScrollPane scrollirc = new JScrollPane(irclog);
public BriDisplayGUI(boolean startup) { //startup function, opens and sets up the window
if(startup == true){
frame.setTitle("Bribot Test Frame"); frame.setBounds(100,100,840,420); //sets title of window, sets position and size of window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //tells program to end on window close
frame.add(pane); //adds the main display pane to the window
//panel customization goes here
pressme.addActionListener(this);
pane.add(pressme);
pressme2.addActionListener(this);
pane.add(pressme2);
pressme.requestFocusInWindow();
irclog.setEditable(false);
scrollirc.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
pane.add(scrollirc);
irclog.setLineWrap(true);
irclog.setWrapStyleWord(true);
//pane.add(inputthing);
frame.setVisible(true);
} else {
System.out.println("Display Class Called");
}
}
public void arrayToDisplay(String[] text) throws IOException {
int i;
for ( i=0; i < text.length; i++) {
irclog.append( text[i] + "\n");
System.out.println( i + ": " + text[i]);
}
}
public void singleToDisplay(String text) throws IOException {
irclog.append(text + "\n");
System.out.println(text);
}
//basic event handler
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == pressme) {
} else if(source == pressme2) {
}
}
}
The first append works fine, but the second doesn't, and I can't figure out why (although the for loop does, as the contents of the array get written to console). I've searched quite a bit and nothing I've tried works. Can anyone point out the inevitable obvious oversight here? I'm the definition of a novice, so any advice is appreciated.
Thanks!
The default constructor doesn't do anything, meaning it doesn't construct any kind of UI or display, what would be, an empty frame.
You seem to be thinking the text will appear in data when you are appending it to data1
Try calling this(false) within the default constructor
A better solution would be to construct the core UI from the default constructor and from the "startup" constructor call this() and then modify the UI in what ever way this constructor needs
It seems like you write a new program. Why do you use Swing? Did you take a look at JavaFX?
I am not sure if that is going to fix your problem but you could try a foreach
for(String s : text){
irclog.append(s+"\n");
}

how to close visibility of "create new folder" in jfilechooser

I have aimed to close "create new folder" button on the file chooser. Is it possible to set visibility of "create new folder" button on the file chooser ? I can set visibility of first component which row start with "look in" words to off but I want set visibility of only "create new folder" not all of them. How can I do that ?
Two suggestions:
You can make the button disabled by accessing the default Action and disabling the Action:
Action folder = fileChooser.getActionMap().get("New Folder");
folder.setEnabled( false );
Or you can use reflection to access the button and make the button invisible:
//JButton button = SwingUtils.getDescendantOfType(
// JButton.class, fileChooser, "ToolTipText", "Create New Folder");
//button.setVisible(false);
For this approach you will need to use the Swing Utils class.
Here is a quick demo showing both approaches:
import java.awt.*;
import javax.swing.*;
public class Main
{
public static void main(String[] args)
{
JFileChooser fileChooser = new JFileChooser();
Action folder = fileChooser.getActionMap().get("New Folder");
folder.setEnabled( false );
// Make the button invisible
//JButton button = SwingUtils.getDescendantOfType(
// JButton.class, fileChooser, "ToolTipText", "Create New Folder");
//button.setVisible(false);
fileChooser.showOpenDialog(null);
}
}
I have used icon name to close buttons. My implementation is ;
JFileChooser fileChooser = new JFileChooser();
// operations related with adjusting JFileChooser user interface
closeButton(fileChooser, "FileChooser.newFolderIcon");
closeButton(fileChooser, "FileChooser.upFolderIcon");
Main function which is going to be called to dis-appear buttons on user interface
void closeButton(JFileChooser fileChooser, String label){
Icon icon = UIManager.getIcon(label);
closeButtonHelper(fileChooser.getComponents(), icon);
}
void closeButtonHelper(Component[] containers, Icon icon) {
for(Object iterator:containers){
if(iterator instanceof JButton){
Icon temp = icon.getIcon();
if(temp != null && temp == icon){
(JButton.class.cast(iterator)).setVisible(false);
}
} else
if(iterator instanceof Container){
doVisibleHelper(Container.class.cast(iterator).getComponents(), icon);
}
}
}
For toggle button, just add new if-then-else statement, like;
if(iterator instanceof JToggleButton){
Icon temp = icon.getIcon();
if(temp != null && temp == icon){
(JToggleButton.class.cast(iterator)).setVisible(false);
}
} else

Categories

Resources