In my software I am using card layout to create a "wizard-based" interface. In panel, user chooses a file, in the other one get information regarding the chosen file in previous panel.
The problem is that CardLayout loads all panels all together. So panels deals with predefined data. But I would like to update the next panel with the information given in the current panel.
each panel has 'next' and 'back' buttons, so I think that is the point where next panels can get updated somehow. I thought using setters and getters methods but could not implement it correctly.
Here is a sample code with two sub-panels:
BASE CLASS:
public Base(){
frame.setLayout(bl);
frame.setSize(800, 600);
frame.add(new MainPanel(), BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
// TODO code application logic here
new Base();
}
}
MainPanel (sub-panels holder)
class MainPanel extends JPanel{
private CardLayout cl = new CardLayout();
private JPanel panelHolder = new JPanel(cl);
public MainPanel() {
ChooseFile chooseFile = new ChooseFile(this);
ShowResult showResult = new ShowResult(this);
panelHolder.add(showResult, "showResult");
panelHolder.add(chooseFile, "chooseFile");
cl.show(panelHolder, "chooseFile");
add(panelHolder);
}
public void showPanel(String panelIdentifier){
cl.show(panelHolder, panelIdentifier);
}
}
Sub-Panel 1:
class ChooseFile extends JPanel{
MainPanel ob2;
JPanel directoryChooserPanel, bottomPanel;
JButton btn, localSourceBack, localSourceNext;
JTextField field;
public ChooseFile(MainPanel mainPanel){
this.ob2 = mainPanel;
ShowResult showResult = new ShowResult();
setLayout(new BorderLayout());
directoryChooserPanel = new JPanel(new GridLayout(0,2));
btn = new JButton("Browse");
btn.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JFileChooser chooser = new JFileChooser("D:\\Desktop");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION){
File myFile = chooser.getSelectedFile();
String text = myFile + "";
field.setText(text);
}
}
});
directoryChooserPanel.add(btn);
field = new JTextField(20);
directoryChooserPanel.add(field);
localSourceNext = new JButton("Next");
localSourceNext.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
ob2.showPanel("showResult");
showResult.setRoot(getPath());
}
});
add(directoryChooserPanel, BorderLayout.NORTH);
add(localSourceNext, BorderLayout.EAST);
}
public String getPath(){
return field.getText();
}
}
Sub Panel 2:
class ShowResult extends JPanel{
MainPanel ob2;
JPanel bottomPanel, labelsPanel;
JButton srcLocalBTN, srcFtpBTN, sourceLocationBack;
JLabel result;
File directory;
String root;
ArrayList<String> myFiles = new ArrayList<String>();
public ShowResult(MainPanel mainPanel){
this.ob2 = mainPanel;
setLayout(new BorderLayout());
result = new JLabel();
root = "No ADDRESS";
directory = new File(root);
listFiles(directory, myFiles);
String filesNumber = "It contains " + myFiles.size() + " files.";
result.setText(filesNumber);
add(result, BorderLayout.NORTH);
}
public void listFiles(File directory, ArrayList<String> list){
for(File file : directory.listFiles()){
list.add(file.getName());
if(file.isDirectory()){
listFiles(file.getAbsoluteFile(), list);
}
}
}
public ShowResult(){
}
public void setRoot(String chosenPath){
root = chosenPath;
}
}
So it firsts loads 'sub panel 1' so user chooses a directory by jFileChooser and then I need to transfer this data to 'sub panel 2'. So it can calculate how many files it is containing.
I tried to transfer data by getting the chosen directory and assigning to a variable in the second variable. But doesn't work.
Any idea?
You're creating more than one ShowResult object, displaying one but then passing information to the other, the non-displayed one, but this is not how Java works (this is easy to discover by simply searching this page for number of new ShowResult() matches). You need to be sure that the ShowResult object that is displayed is the exact same as the one you pass information to, meaning you'll have to pass the reference of the displayed object into your ChooseFile class via a constructor or method parameter.
Better option: use an MVC design pattern, make, have your controls change the state of the model and your views display the state of your model. This may reduce the cyclomatic complexity of your code.
Related
I'm working on an assignment for class where we need to create a JComboBox and each option opens a new window where you can do whatever you want on those new windows. Please keep in mind I'm very new to GUI and new to Java in general, in case my questions are dumb.
I have a question and an issue...
My question:
When the user selects "The Matrix" option a new window pops up with a quote and two buttons. Right now I have two JPanels (panel and panel2) panel adds the quote to the NORTH position and then panel2 adds the two buttons to the CENTER position both using BorderLayout. My question is am I doing this correctly...Could I use just panel to add the quote and the buttons or is it necessary to create separate panels for separate items being added to the JFrame? When I had them both added to the same panel the quote was not on the window when I ran the program.
panel.add(matrixQuote);
newFrame.add(panel, BorderLayout.NORTH);
That's how I had it when it wasn't showing up ^^^
I GOT THE ISSUE WITH CLEARING THE JFRAME FIXED
I am trying to add an ActionListener to the bluePill button and instead of opening another new window I thought I could clear everything from the existing window when the button is pressed and then display something new on said window. The only info I could find on this is how I have it in the actionPerformed method below. I'll post a snippet of what I'm talking about directly below and then all my code below that just in case.
All my code...
public class MultiForm extends JFrame{
private JComboBox menu;
private JButton bluePill;
private JButton redPill;
private JLabel matrixQuote;
private int matrixSelection;
private JFrame newFrame;
private JPanel panel;
private JPanel panel2;
private static String[] fileName = {"", "The Matrix", "Another Option"};
public MultiForm() {
super("Multi Form Program");
setLayout(new FlowLayout());
menu = new JComboBox(fileName);
add(menu);
TheHandler handler = new TheHandler();
menu.addItemListener(handler);
}
public void matrixPanel() {
TheHandler handler = new TheHandler();
//Create a new window when "The Matrix" is clicked in the JCB
newFrame = new JFrame();
panel = new JPanel();
panel2 = new JPanel();
newFrame.setLayout(new FlowLayout());
newFrame.setSize(500, 300);
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
matrixQuote = new JLabel("<html>After this, there is no turning back. "
+ "<br>You take the blue pill—the story ends, you wake up "
+ "<br>in your bed and believe whatever you want to believe."
+ "<br>You take the red pill—you stay in Wonderland, and I show"
+ "<br>you how deep the rabbit hole goes. Remember: all I'm "
+ "<br>offering is the truth. Nothing more.</html>");
panel2.add(matrixQuote);
newFrame.add(panel2, BorderLayout.NORTH);
//Blue pill button and picture.
Icon bp = new ImageIcon(getClass().getResource("Blue Pill.png"));
bluePill = new JButton("Blue Pill", bp);
panel2.add(bluePill);
bluePill.addActionListener(handler);
//Red pill button and picture
Icon rp = new ImageIcon(getClass().getResource("Red Pill.png"));
redPill = new JButton("Red Pill", rp);
panel2.add(redPill);
newFrame.add(panel2, BorderLayout.CENTER);
newFrame.setVisible(true);
}
private class TheHandler implements ItemListener, ActionListener{
public void itemStateChanged(ItemEvent IE) {
//listen for an item to be selected.
if(IE.getStateChange() == ItemEvent.SELECTED) {
Object selection = menu.getSelectedItem();
if("The Matrix".equals(selection)) {
matrixPanel();
}
else if("Another Option".equals(selection)) {
}
}
}
public void actionPerformed(ActionEvent AE) {
if(AE.getSource() == bluePill) {
newFrame.remove(panel);
newFrame.remove(panel2);
newFrame.repaint();
}
}
}
//MAIN
public static void main(String[] args) {
MultiForm go = new MultiForm();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(400, 200);
go.setVisible(true);
}
}
Use a Card Layout. You can swap panels as required.
The tutorial has a working example.
You can use:
jpanel.removeAll();
Either to delete a certain JComponent by using the JComponent itself like:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
frame.remove(panel);
panel.getGraphics().clearRect(0, 0, panel.getWidth(), panel.getHeight());
I am working on a little project and want to display the Name of the opened File.
The problem is, the JLabel who should display the File Name is not repainting, I had read that it should be repainted by itself..
here is my code for the FileChooser and to get the File Name ( I know that i get the path of the file, I will format it later..
/**
* Opens a window where the user can select a file.
*
* #return Scanner in
*/
public Scanner openFile() {
JFileChooser chooser = new JFileChooser();
Scanner in = null;
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedInFile = chooser.getSelectedFile();
try {
absolutePathOfFile = selectedInFile.getAbsolutePath();
FileReader fileReader = new FileReader(selectedInFile.getAbsolutePath());
in = new Scanner(fileReader);
} catch (FileNotFoundException ex) {
// File not found
System.out.println("File not found!!");
}
}
return in;
}
public List getList() {
return listOfEveryVariable;
}
#Override
public String getFileName() {
return absolutePathOfFile;
}
And here is the code for my Label
public Component createInfoPanel() {
infoPanel = new JPanel(new BorderLayout());
infoPanel.setBackground(Color.LIGHT_GRAY);
fileInfoPanel = new JPanel(new GridLayout(1,2));
fileInfoPanel.setBackground(Color.LIGHT_GRAY);
infoPanel.add(fileInfoPanel, BorderLayout.WEST);
JLabel fileInfo_1 = new JLabel();
fileInfo_1.setText("File: ");
fileInfoPanel.add(fileInfo_1);
JLabel fileInfo_2 = new JLabel();
FileName fn = new Datahandler();
fileInfo_2.setText(fn.getFileName());
fileInfoPanel.add(fileInfo_2);
return infoPanel;
}
The GuiInfoPanel is created and added in and to an Frame..
If I set a name to the getFileName() class and let it return it works and the name is displayed.
Greetings
The createInfoPanel is called here:
public class GuiFrame extends JFrame {
private static final int FRAME_WIDTH = 800;
private static final int FRAME_HIGHT = 600;
/**
* The variables for the panels
*/
private JPanel mainPanel, menuPanel, plotPanel, scatterplotPanel,
histogramPanel, histogram1, histogram2;
public GuiFrame() {
setSize(FRAME_WIDTH, FRAME_HIGHT);
/**
* Create Objects
*/
GuiMenuBar mb = new GuiMenuBar();
GuiInfoPanel ip = new GuiInfoPanel();
GuiOptionPanel op = new GuiOptionPanel();
JComponent sp = new Scatterplot();
/**
* Create Panels
*/
createMainPanel();
mb.createMenuBar();
ip.createInfoPanel();
op.createOptionPanel();
/**
* Add Panels
*/
this.add(mainPanel);
this.setJMenuBar(mb);
this.add(ip.infoPanel, BorderLayout.SOUTH);
menuPanel.add(op.optionPanel, BorderLayout.NORTH);
scatterplotPanel.add(sp, BorderLayout.CENTER);
}
private Component createMainPanel(){
mainPanel = new JPanel(new BorderLayout());
menuPanel = new JPanel(new BorderLayout());
mainPanel.add(menuPanel, BorderLayout.WEST);
plotPanel = new JPanel(new GridLayout(2,1));
plotPanel.setBorder(BorderFactory.createLineBorder(Color.black));
mainPanel.add(plotPanel, BorderLayout.CENTER);
scatterplotPanel = new JPanel(new BorderLayout());
scatterplotPanel.setBorder(BorderFactory.createLineBorder(Color.black));
plotPanel.add(scatterplotPanel);
histogramPanel = new JPanel(new GridLayout(1,2));
plotPanel.add(histogramPanel);
histogram1 = new JPanel(new BorderLayout());
histogram1.setBorder(BorderFactory.createLineBorder(Color.black));
histogramPanel.add(histogram1);
histogram2 = new JPanel(new BorderLayout());
histogram2.setBorder(BorderFactory.createLineBorder(Color.black));
histogramPanel.add(histogram2);
return mainPanel;
}
}
I think that the panel being called only once is be the problem.
It looks like the problem is that createInfoPanel() is only ever called once, at the point where you create the screen. At this point, setText() is doing what you'd expect it to, but the user hasn't chosen a file yet. I am basing this on the fact that if createInfoPanel() were called multiple times, you would end up adding more labels to the screen than desired.
When you select a file from your file chooser, createInfoPanel() doesn't magically get called again and so the text never gets updated on the JLabel. It would be useful to see the code that calls createInfoPanel() and the code that calls openFile() to verify this is the case.
Regarding your second question - you can't reference the JLabel outside of where it is declared. As you are declaring the JLabel within createInfoPanel() it is a local variable to this method only. If you want it to be accessed by other methods you need to make it a class variable, similar to the "absolutePathOfFile" variable. So you might do something like:
public class GuiInfoPanel {
private final JPanel infoPanel;
private final JLabel fileInfo = new JLabel();
public Component createInfoPanel() {
infoPanel = new JPanel(new BorderLayout());
infoPanel.setBackground(Color.LIGHT_GRAY);
fileInfo.setText("File: ");
infoPanel.add(fileInfo, BorderLayout.WEST);
return infoPanel;
}
/**
* Call this whenever the user picks a new file
*/
public void setFileInfoText(String filePath){
fileInfo.setText("File: " + filePath);
}
}
EDIT: Your latest code confirms my suspicions - createInfoPanel() is only called by the constructor, so will only be called once. Try something like my code snippet above to get the behaviour you're after. And a side-note: You should edit your original post to include more information rather than posting updates as 'answers'!
EDIT 2: See below for a self-contained 'toy' example that should help you to get the behaviour you're after.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FileSelectionDemo extends JFrame
implements ActionListener
{
public static void main(String[] args)
{
FileSelectionDemo demoScreen = new FileSelectionDemo();
demoScreen.setSize(300, 300);
demoScreen.setVisible(true);
}
public FileSelectionDemo()
{
getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
getContentPane().add(btnSelectFile);
getContentPane().add(lblFilePath);
btnSelectFile.addActionListener(this);
}
private final JLabel lblFilePath = new JLabel("");
private final JButton btnSelectFile = new JButton("Choose File");
public void selectFile()
{
JFileChooser chooser = new JFileChooser();
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File selectedInFile = chooser.getSelectedFile();
String absolutePathOfFile = selectedInFile.getAbsolutePath();
lblFilePath.setText(absolutePathOfFile);
}
}
#Override
public void actionPerformed(ActionEvent arg0)
{
Object source = arg0.getSource();
if (source == btnSelectFile)
{
selectFile();
}
}
}
In my program I have a wizard based layout. Implemented by CardLayout. So there is a set of classes that extend JPanels. I want to have buttons in each panel to navigate to other panels. fro example, when the program is showing panel one, I want to have a button to show panel 2.
I tired to create a method in main cardlayout panel holder so any other class can change the showing panel by this method, but it does not works and a stackoverflow error come up.
Here are my classes
Base Frame:
public class Base {
JFrame frame = new JFrame("Panel");
BorderLayout bl = new BorderLayout();
public Base(){
frame.setLayout(bl);
frame.setSize(800, 600);
frame.add(new LeftBar(), BorderLayout.WEST);
frame.add(new MainPanel(), BorderLayout.CENTER);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new Base();
}
}
Main class that holds sub panels:
public class MainPanel extends JPanel {
private CardLayout cl = new CardLayout();
private JPanel panelHolder = new JPanel(cl);
public MainPanel() {
NewSession session = new NewSession();
ChooseSource chooseSource = new ChooseSource();
panelHolder.add(session, "Session");
panelHolder.add(chooseSource, "ChooseSource");
cl.show(panelHolder, "Session");
add(panelHolder);
}
public void showPanel(String panelIdentifier){
cl.show(panelHolder, panelIdentifier);
}
}
Sub panel 1
public class NewSession extends JPanel {
MainPanel ob2 = new MainPanel();
public NewSession(){
JButton newSessionBTN = new JButton("Create A New Session");
newSessionBTN.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
System.out.println("HI");
ob2.showPanel("ChooseSource");
}
});
add(newSessionBTN);
}
}
Sub panel 2
public class ChooseSource extends JPanel {
public ChooseSource(){
JLabel showMe = new JLabel("Show Me");
JButton back = new JButton("Back");
//MainPanel ob = new MainPanel();
back.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
//ob.showPanel("start");
}
});
add(back);
add(showMe);
}
}
As you can see I have button in each sub panel and those buttons must show the other panel after clicking. In later they will also transfer the data from one to another.
ERROR:
Exception in thread "main" java.lang.StackOverflowError
at java.awt.Component.setFont(Component.java:1899)
at java.awt.Container.setFont(Container.java:1748)
at javax.swing.JComponent.setFont(JComponent.java:2751)
at javax.swing.LookAndFeel.installColorsAndFont(LookAndFeel.java:208)
at javax.swing.plaf.basic.BasicPanelUI.installDefaults(BasicPanelUI.java:66)
at javax.swing.plaf.basic.BasicPanelUI.installUI(BasicPanelUI.java:56)
at javax.swing.JComponent.setUI(JComponent.java:663)
at javax.swing.JPanel.setUI(JPanel.java:153)
at javax.swing.JPanel.updateUI(JPanel.java:126)
at javax.swing.JPanel.<init>(JPanel.java:86)
at javax.swing.JPanel.<init>(JPanel.java:109)
at javax.swing.JPanel.<init>(JPanel.java:117)
at InnerPanels.NewSession.<init>(NewSession.java:21)
at StrongBaseLayout.MainPanel.<init>(MainPanel.java:22)
The error is longer than this, by repeating last two lines.
How can I make it working?
Also I had another idea to have a next and previous buttons at the bottom of the page to switch panels. But am not sure which one is optimal. Any idea?
Whenever you see an unexpected StackOverflowError always look for the presence of inadvertent recursion, and in fact, that's exactly what you have going on here since MainPanel creates a NewSession object which then creates a new MainPanel object which then creates a new NewSession object which then creates a new MainPanel object .... repeating ad infinitum or until stack memory (hence the stack overflow) runs out.
here:
public class NewSession extends JPanel {
MainPanel ob2 = new MainPanel(); // *****
and here:
public class MainPanel extends JPanel {
private CardLayout cl = new CardLayout();
private JPanel panelHolder = new JPanel(cl);
public MainPanel() {
NewSession session = new NewSession(); // *****
Don't do that. Instead take care to create one and only one of each object. Use setter methods or constructor parameters to help you do this.
For example, change to this:
public class NewSession extends JPanel {
MainPanel ob2;
NewSession(MainPanel mainPanel) {
this.ob2 = mainPanel;
and this:
public class MainPanel extends JPanel {
private CardLayout cl = new CardLayout();
private JPanel panelHolder = new JPanel(cl);
public MainPanel() {
NewSession session = new NewSession(this);
Regarding:
Also I had another idea to have a next and previous buttons at the bottom of the page to switch panels. But am not sure which one is optimal. Any idea?
I'm not sure what you mean here. Define "optimal".
I have a program utilizing JTabbedPane. On one pane I have a button that updates an arrayList of objects based on input from the same pane.
What I would like to happen is have the second pane update itself with the object information based on the arrayList in the first pane.
However, I am not sure how to pass the list between the panes. Is there some way to push the array to pane #2 when the update button on the first pane is pressed?
Here is the main file. Instantiating the two tabs
public class Assignment6 extends JApplet
{
private int APPLET_WIDTH = 650, APPLET_HEIGHT = 350;
private JTabbedPane tPane;
private StorePanel storePanel;
private PurchasePanel purchasePanel;
private ArrayList computerList;
public void init()
{
computerList = new ArrayList();
storePanel = new StorePanel(computerList, purchasePanel);
purchasePanel = new PurchasePanel(computerList);
tPane = new JTabbedPane();
tPane.addTab("Store Inventory", storePanel);
tPane.addTab("Customer Purchase", purchasePanel);
getContentPane().add(tPane);
setSize (APPLET_WIDTH, APPLET_HEIGHT); //set Applet size
}
}
The first panel instantiates a button listener that applies all of the logic to the array list "compList"
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
//Add Computer to list
Computer comp = new Computer();
comp.setBrandName(brandField.getText());
comp.setPrice(Double.parseDouble(priceField.getText()));
comp.setMemory(Integer.parseInt(memoryField.getText()));
comp.setCPU(typeField.getText(), Integer.parseInt(speedField.getText()));
compList.add(comp);
}
stringField.setText(listString);
alertLabel.setText("Computer Added");
}
}
Here is the other pane. The for loop at the end is what I need to push the arrayList to. After it receives the list, it populates a box with a checkbox for each object in the list
public PurchasePanel(ArrayList compList)
{
west = new JPanel();
east = new JPanel();
totalField = new JTextField();
this.compList = compList;
setLayout(new GridLayout(0,2));
add(west);
add(east);
east.setLayout(new BorderLayout());
east.add(currentTotalLabel, BorderLayout.NORTH);
east.add(totalField, BorderLayout.CENTER);
west.setLayout( new BoxLayout(west, BoxLayout.Y_AXIS));
for(Object c : compList){
System.out.println("Made it");
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String str = ("BrandName:" + (((Computer) c).getBrandName() +"CPU:" + (((Computer) c).getCPU() +"Memory:" + ((Computer) c).getMemory() + "M" +"Price:" + fmt.format(((Computer) c).getPrice()))));
JCheckBox chk = new JCheckBox(str);
west.add(chk);
}
}
}
You can use the same listener used to update the first ArrayList, to update the second pane. Something like:
jButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Update the first ArrayList
// Update the second pane
}
I have this method to print and set the material properties of a Solid Object in a class called MaterialProperties, which has printMaterial & setMaterial methods.
public void Btn3_callback ( ) throws Exception {
Model model = session.GetCurrentModel();
if (model == null) {
mesg = "No Model Selected!!";
//TextField.Area("No Model Selected!!");
System.exit(0);
}
else {
Solid solid= (Solid) model;
String newMaterial="copper";//user input for new Material name
printMaterial(solid);//printMaterial print the Material properties of the Solid object
setMaterial(solid,newMaterial);//setMaterial sets the Material properties of the Solid object to the material entered
}
}
I need to get the user input for newMaterial instead of hard coding it. What I need to do is to display all the Material types avaialable, so that the user can just select the material required. So I tried to do this using JFrame. Here's the code I have:
public class MaterialWindow {
JFrame frame = new JFrame("Material Selection");
public MaterialWindow(){
// Directory path here
String path = "W:\\materials";
JFrame frame = new JFrame("Material Selection");
JPanel panel = new JPanel(new GridLayout(0, 4));
ButtonGroup bg = new ButtonGroup();
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
JRadioButton button;
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".mtl") || files.endsWith(".MTL"))
{
button = new JRadioButton(files);
panel.add(first,BorderLayout.CENTER);
panel.revalidate();
bg.add(button);
first.addActionListener(new MyAction());
}
}
}
frame.add(panel, BorderLayout.NORTH);
frame.getContentPane().add(new JScrollPane(panel), BorderLayout.CENTER);
frame.setSize(1000, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction implements ActionListener{
public void actionPerformed(ActionEvent e){
String newMaterial =e.getActionCommand();
String[] split = newMaterial.split("\\.");
newMaterial = split[0];
newMaterial.trim();
//set the newMaterial for btn3_callback OR call the setMaterial method of MaterialPropeties class
frame.dispose();
}
}
}
Now the problem is how can I use the newMaterial string selected from the radio button to newMaterial in my Btn3_callback() function? When I create a getString() method for newMaterial in the class MyAction and use that it Btn3_callback it always returns null;
Is there any way I can do this? Or any different way I can implement the idea?
Thanks
Use a JOptionPane instead of the frame. Put a list (JList ..or JComboBox) of options in the option pane and query the component once returned (the pane is closed), for the selected object.
E.G. using JComboBox
The GUI should be created and altered on the EDT (batteries not included).
import java.io.File;
import javax.swing.*;
public class QuickTest {
public static void main(String[] args) throws Exception {
File[] files = new File(System.getProperty("user.home")).listFiles();
JFrame f = new JFrame("Faux J-Link");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JEditorPane jep = new JEditorPane();
f.add(new JScrollPane(jep));
f.setSize(600,400);
f.setLocationByPlatform(true);
f.setVisible(true);
JComboBox choices = new JComboBox(files);
int result = JOptionPane.showConfirmDialog(f, choices);
if (result==JOptionPane.OK_OPTION) {
System.out.println("OK");
File file = files[choices.getSelectedIndex()];
jep.setPage(file.toURI().toURL());
}
}
}