I'm making a GUI and having trouble with a JPanel.
First of all here is my JPanel:
public class ExperimentPanel extends JPanel{
private static File file1,file2=null;
private static DefaultListModel model = new DefaultListModel();
private static JList list = new JList(model);
private static JPanel mainpanel = new JPanel();
private static JPanel leftpanel = new JPanel();
private static JPanel rightpanel = new JPanel();
private static JPanel twoFiles = new SelectTwoFiles();
private static JPanel folderOrFile = new SelectFolderOrFile();
private static JPanel foldersOrFiles = new SelectTwoFoldersOrFiles();
public ExperimentPanel(int selectID){
this.setBorder(new EmptyBorder(10, 10, 10, 10));
if(selectID==Constants.SelectTwoFiles){
this.add(twoFiles, BorderLayout.NORTH);
}
else if(selectID==Constants.SelectFolderOrFile){
this.add(folderOrFile, BorderLayout.NORTH);
}
else if(selectID==Constants.SelectTwoFoldersOrFiles){
this.add(foldersOrFiles,BorderLayout.NORTH);
}
JButton remove =new JButton("Remove Method");
JButton add = new JButton("Add Method");
JButton save = new JButton("Save list");
JButton load = new JButton("Load list");
leftpanel.add(new JScrollPane(list));
Box listOptions = Box.createVerticalBox();
listOptions.add(add);
listOptions.add(remove);
listOptions.add(save);
listOptions.add(load);
rightpanel.add(listOptions);
Box mainBox = Box.createHorizontalBox();
mainBox.add(leftpanel);
mainBox.add(rightpanel);
//mainBox.add(leftleft);
this.add(mainBox, BorderLayout.CENTER);
//start jobs
JButton start = new JButton("Launch experiment");
this.add(start,BorderLayout.PAGE_END);
start.addActionListener(launch);
add.addActionListener(adding);
remove.addActionListener(delete);
}
public static ActionListener launch = new ActionListener(){
public void actionPerformed(ActionEvent event){
//check the files
if((file1==null)||(file2==null)){
JOptionPane.showMessageDialog(null,
"A graph file is missing",
"Wrong files",
JOptionPane.ERROR_MESSAGE);
}
//checks the list
}
};
public static ActionListener delete = new ActionListener() {
public void actionPerformed(ActionEvent event) {
ListSelectionModel selmodel = list.getSelectionModel();
int index = selmodel.getMinSelectionIndex();
if (index >= 0)
model.remove(index);
}
};
public static ActionListener adding = new ActionListener(){
public void actionPerformed(ActionEvent event){
JComboBox combo = new JComboBox();
final JPanel cards = new JPanel(new CardLayout());
JPanel form = new JPanel();
JPanel methode1 = new JPanel();
methode1.add(new JLabel("meth1"));
methode1.setBackground(Color.BLUE);
methode1.setName("meth1");
JPanel methode2 = new JPanel();
methode2.add(new JLabel("meth2"));
methode2.setBackground(Color.GREEN);
methode1.setName("meth2");
combo.addItem("meth1");
combo.addItem("meth2");
cards.add(methode1,"meth1");
cards.add(methode2,"meth2");
JPanel control = new JPanel();
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox jcb = (JComboBox) e.getSource();
CardLayout cl = (CardLayout) cards.getLayout();
cl.show(cards, jcb.getSelectedItem().toString());
}
});
control.add(combo);
form.add(cards, BorderLayout.CENTER);
form.add(control, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null,form,"Select a method",JOptionPane.PLAIN_MESSAGE);
}
};
}
The problem is that if i create several instances of that panel they won't show like intended.
I tried creating 2 simple JFrames in my main with a new ExperimentPanel for each so the problem is not from the caller.
It works well with one JFrame calling one experiementPanel.
here is the display for one and 2 calls:
http://imgur.com/a/4DHJn
And how i call them:
JFrame test = new JFrame();
test.add(new ExperimentPanel(3));
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
test.setLocation(dim.width/3 - test.getWidth()/3, dim.height/3 - test.getHeight()/3);
test.setSize(550,300);
test.setVisible(true);
JFrame test2 = new JFrame();
test2.add(new ExperimentPanel(3));
test2.setLocation(dim.width/3 - test.getWidth()/3, dim.height/3 - test.getHeight()/3);
test2.setSize(550,300);
test2.setVisible(true);
You create a Panel class ExperimentPanel which itself consists of several components which are stored in class fields of ExperimentPanel.
Since you declare these class fields as static there is only one instance of them. When you instantiate several ExperimentPanel objects they all want to share these fields, which leads to the effects you have seen.
Therefore remove the static modifier from these fields:
public class ExperimentPanel extends JPanel{
private File file1,file2=null;
private DefaultListModel model = new DefaultListModel();
private JList list = new JList(model);
private JPanel mainpanel = new JPanel();
private JPanel leftpanel = new JPanel();
...
So this is my runner that runs my entire game. CharacterGame, CharacterChoice and CharacterHead are all classes that contain graphics and paint. I was hoping to be able to call separate parts from these classes into the graphics by the remove and repaint located in one of my button's code. Right now its just updating the Frame with more and more panels instead of removing the old panels and adding these panels into the old panels place. I hope this makes sense as I am a bit new to graphics and may not have thought of the best way to do this. If anyone can shed some light into how to do this, I will be very grateful. Thanks! I've tried everything I can think of... from removeAll methods to repaint. I can't think of anything else to do.
The part not working is located in the ShowButtonDemo() in the choice1Button listener.
public class GraphicsRunner extends JFrame
{
private static final int WIDTH = 1280;
private static final int HEIGHT = 980;
private JFrame mainframe;
private JPanel controlPanel;
private JPanel headPanel;
private JPanel gamePanel;
private JPanel choicePanel;
private int gameInt = 0;
private int choiceInt = 0;
private int endGame = 0;
public GraphicsRunner()
{
super("Stranded...");
mainframe = new JFrame();
mainframe.setBackground(Color.BLACK);
mainframe.setSize(WIDTH,HEIGHT);
mainframe.setLayout(new GridLayout(4, 0));
mainframe.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headPanel = new JPanel();
gamePanel = new JPanel();
choicePanel = new JPanel();
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
headPanel = new CharacterHeading();
gamePanel = new CharacterGame(gameInt);
choicePanel = new CharacterChoice(choiceInt);
mainframe.add(headPanel);
mainframe.add(gamePanel);
mainframe.add(choicePanel);
mainframe.add(controlPanel);
mainframe.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainframe.setVisible(true);
}
public static void main( String args[] )
{
GraphicsRunner run = new GraphicsRunner();
run.showButtonDemo();
}
private void showButtonDemo(){
JButton choice1Button = new JButton("Choice #1");
JButton choice2Button = new JButton("Choice #2");
JButton choice3Button = new JButton("Choice #3");
choice3Button.setHorizontalTextPosition(SwingConstants.LEFT);
choice1Button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gameInt = gameInt + 1;
choiceInt = choiceInt + 1;
gamePanel = new CharacterGame(gameInt);
//This is the part I am currently working on and I was hoping
//it would remove the panel instead of just removing the
//content on the panel...
mainframe.remove(headPanel);
mainframe.remove(gamePanel);
mainframe.remove(choicePanel);
mainframe.remove(controlPanel);
mainframe.add(headPanel, 0);
mainframe.add(gamePanel, 1);
mainframe.add(choicePanel, 2);
mainframe.add(controlPanel, 3);
mainframe.revalidate();
mainframe.repaint();
System.out.println(gameInt);
}
});
controlPanel.setBackground(Color.BLACK);
controlPanel.add(choice1Button);
controlPanel.add(choice2Button);
controlPanel.add(choice3Button);
mainframe.setVisible(true);
}
}
At the moment I'm trying to implement a GUI. Unfortunately I'm only getting a frame with a menuBar. The Panel and its content I defined do not show up.
I would appreciate any advice about why the panel and its content are not shown and what I did wrong (most likely in the initialiseLeftPanel() method).
What I have tried so far:
changed the position of setVisible(true);
included some revalidate()'s;
public class Codebreakerz {
private static GameRenderer renderer;
public static void main(String[] args) {
renderer = new GameRenderer();
}
public class GameRenderer extends JFrame {
private final String TITLE = "Codebreakerz";
private Image ICON = getToolkit().getImage("res/confused.png");
private final int WIDTH = 900;
private final int HEIGHT = 800;
private final int ROUNDS = 12;
private final Color BACKGROUND = Color.lightGray;
private JPanel left;
private JPanel right;
private JLabel attemptsLabel;
private JLabel correctLabel;
private JLabel rightNumbLabel;
private JLabel[] roundLabels;
public GameRenderer() {
initialiseWindow();
initialiseMenu()
initialiseLabels();
initialiseLeftPanel();
}
private void initialiseWindow() {
setTitle(TITLE);
setIconImage(ICON);
setSize(WIDTH, HEIGHT);
setLocationRelativeTo(null);
setResizable(false);
setLayout(null);
setVisible(true);
}
private void initialiseMenu() {
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("Menu");
JMenuItem newGame = new JMenuItem("Neues Spiel");
JMenuItem close = new JMenuItem("Schließen");
file.add(newGame);
file.add(close);
menuBar.add(file);
setJMenuBar(menuBar);
}
private void initialiseLabels() {
attemptsLabel = new JLabel("0");
correctLabel = new JLabel("0");
rightNumbLabel = new JLabel("0");
roundLabels = new JLabel[ROUNDS];
for(int i=0; i<ROUNDS; i++) {
roundLabels[i] = new JLabel();
}
}
private void initialiseLeftPanel() {
left = new JPanel();
left.setLayout(null); // Tried other stuff aswell
JLabel heading = new JLabel("Codebreakerz");
JLabel tryNr = new JLabel("Anzahl Versuche: ");
JLabel correct = new JLabel("Richtig: ");
JLabel correctNumb = new JLabel("Richtige Nummer an falscher Stelle: ");
left.add(heading);
left.add(tryNr);
left.add(correct);
left.add(correctNumb);
add(left);
}
}
If you supress the line left.setLayout(null); in your method initialiseLeftPanel() and setLayout(null); in your method initialiseWindow() it will work.
You are obliged to have a Layout if you want display your panels. By default it uses a FlowLayout, but here you replaced it by null.
In this program, i have to create a GUI that saves objects of Contacts onto an array which then is turned into an array to be passed into the constructor of the default table model.
I know i'm doing an extra step here.
The back up button actually saves whatever is in the Vector of contacts onto a binary file.
The load button will load whatever file name you put in the username back into the vector.
The view all contacts should display everything that is in the vector(well technically the contactListArray).
I'm having this problem where i can't get the JTable on the view card to update. If I load the contacts, and then click load contacts it shows, so i know the data is being written into the .dat file correctly. The problem seems to be that once i click on the view button the JTable is creating and won't change, even though i have it set to change in the method.
The problem, i think, is down at the where is says if(source == viewBut)
that entire block i think may be the problem.
Thank you for your help in advance, i really appreciate it.
/*
* Lab number: Final Project
* Robert Lopez
* Section number: 4
*/
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.event.*;
import javax.swing.table.TableModel;
class Contact implements Serializable{ String firstName, lastName, eAddress, address, phoneNum; }
public class finalLab implements ActionListener{
static CardLayout layout;
static private JFrame frame = new JFrame("Address Book");
static private JButton[] topMenuButton = new JButton[5];
static private Vector<Contact> contactList = new Vector<Contact>();
static private int contactSize = 0;
static private String[] columnNames = {"First Name", "Last Name","E-Mail Address", "Address", "Phone Number"};
static private String[][] contactListArray;
//START--------------------------Menu Card----------------------------------------------
static JPanel menuCard = new JPanel(new BorderLayout());
static JPanel menuTop = new JPanel( new GridLayout(2,1) );
static private JLabel firstLabel = new JLabel("Use The Buttons Below To Manage Contacts");
static JPanel menuMid = new JPanel(new FlowLayout());
static private JLabel userName = new JLabel("User Name:");
static private JTextField userNameField = new JTextField("", 15);
static private JLabel numContacts = new JLabel("Number of Contacts:");
static private JTextField numContactsField= new JTextField("", 15);
static private JPanel menuLower = new JPanel(new GridLayout(2,8));
static private JButton loadBut = new JButton("Load Contacts");
static private JButton addBut = new JButton("Add New Contacts");
static private JButton searchBut = new JButton("Search Contacts");
static private JButton sortBut = new JButton("Sort Contacts");
static private JButton deleteBut = new JButton("Delete Contacts");
static private JButton viewBut = new JButton("View All Contacts");
static private JButton backupBut = new JButton("Backup Contacts");
static private JButton blankBut = new JButton("");
//END---------------------------------Menu Card------------------------------------
//START---------------------------------View Card------------------------------------
//View Panel
static private JPanel viewCard = new JPanel(new BorderLayout());
static private JPanel viewCardLower = new JPanel();
static private JLabel viewLabel = new JLabel("Contact List");
static private JTable viewContacts;
static private JPanel viewCardMid = new JPanel(new BorderLayout());
static private JTableHeader header;
static private JScrollPane scrollPane = new JScrollPane();
//END---------------------------------View Card------------------------------------
//START-----------------------------------Delete Card------------------------------------
//Delete Panel
static private JPanel deleteCard = new JPanel(new GridLayout (3,1));
static private JPanel deleteMid = new JPanel();
static private JPanel deleteLower = new JPanel();
static private JLabel deleteLabel = new JLabel("Delete Contacts");
static private JLabel contactInfoLabel = new JLabel("Contact Phone #");
static private JTextField contactInfoField = new JTextField("", 15);
//END-----------------------------------Delete Card---------------------------------
//START-----------------------------------Add Contact-------------------------------
static private JPanel addCard = new JPanel(new GridLayout(6,2));
static private JLabel firstNameLabel = new JLabel("First Name");
static private JLabel lastNameLabel = new JLabel("Last Name");
static private JLabel eAddressLabel = new JLabel(" E-Mail Address");
static private JLabel addressLabel = new JLabel("Address");
static private JLabel phoneNumLabel = new JLabel("Phone No.");
static private JTextField firstNameField = new JTextField("", 10);
static private JTextField lastNameField = new JTextField("", 10);
static private JTextField eAddressField = new JTextField("", 10);
static private JTextField addressField = new JTextField("", 10);
static private JTextField phoneNumField = new JTextField("", 10);
static private JButton saveContactBut = new JButton("Save New Contact");
static private JPanel addLowerLeft = new JPanel();
static private JPanel addLowerRight = new JPanel();
//END------------------------------------Add Contact-----------------------------
//****************************** MAIN METHOD *******************************
static JPanel contentPane = (JPanel)frame.getContentPane();
static private JPanel mainPanel = new JPanel();
public static void main(String[] args){
ActionListener AL = new finalLab();
mainPanel.setLayout(layout = new CardLayout() );
contentPane.setLayout(new BorderLayout());
//Buttons, Labels
loadBut.addActionListener(AL);
for(int i = 0; i < 5; i++){
topMenuButton[i] = new JButton("Top Menu");
topMenuButton[i].addActionListener(AL);
}
backupBut.addActionListener(AL);
viewBut.addActionListener(AL);
addBut.addActionListener(AL);
deleteBut.addActionListener(AL);
saveContactBut.addActionListener(AL);
//-------------------------------------------------------
//Top Menu
firstLabel.setHorizontalAlignment(JTextField.CENTER);
firstLabel.setFont(new Font( "serif", Font.BOLD, 25 ));
menuTop.add(firstLabel);
numContactsField.setEditable(false);
numContactsField.setText("" + contactSize);
//Adding Middle Content
menuMid.add(userName);
menuMid.add(userNameField);
menuMid.add(numContacts);
menuMid.add(numContactsField);
//Adding Lower Content
menuLower.add(loadBut);
menuLower.add(addBut);
menuLower.add(searchBut);
menuLower.add(sortBut);
menuLower.add(deleteBut);
menuLower.add(viewBut);
menuLower.add(backupBut);
menuLower.add(blankBut);
menuCard.add(menuTop, BorderLayout.NORTH);
menuCard.add(menuMid, BorderLayout.CENTER);
menuCard.add(menuLower, BorderLayout.SOUTH);
//-------------------------------------------------------
//Delete Card
deleteLabel.setHorizontalAlignment(JTextField.CENTER);
deleteLabel.setFont(new Font( "serif", Font.BOLD, 25 ));
deleteCard.add(deleteLabel);
deleteMid.add(contactInfoLabel);
deleteMid.add(contactInfoField);
deleteCard.add(deleteMid);
deleteLower.add(topMenuButton[0]);
deleteCard.add(deleteLower);
//-------------------------------------------------------
//Add Card
firstNameLabel.setHorizontalAlignment(JTextField.RIGHT);
lastNameLabel.setHorizontalAlignment(JTextField.RIGHT);
eAddressLabel.setHorizontalAlignment(JTextField.RIGHT);
addressLabel.setHorizontalAlignment(JTextField.RIGHT);
phoneNumLabel.setHorizontalAlignment(JTextField.RIGHT);
addCard.add(firstNameLabel);
addCard.add(firstNameField);
addCard.add(lastNameLabel);
addCard.add(lastNameField);
addCard.add(eAddressLabel);
addCard.add(eAddressField);
addCard.add(addressLabel);
addCard.add(addressField);
addCard.add(phoneNumLabel);
addCard.add(phoneNumField);
addLowerLeft.add(saveContactBut);
addLowerRight.add(topMenuButton[1]);
addCard.add(addLowerLeft);
addCard.add(addLowerRight);
//----------------------------------------------------------
//View Card
viewLabel.setHorizontalAlignment(JTextField.CENTER);
viewLabel.setFont(new Font( "serif", Font.BOLD, 25 ));
viewCard.add(viewLabel, BorderLayout.NORTH);
viewCardLower.add(topMenuButton[2]);
viewCard.add(viewCardLower, BorderLayout.SOUTH);
//Adding to frame
mainPanel.add("Menu Card", menuCard);
mainPanel.add("Delete Card", deleteCard);
mainPanel.add("Add Card", addCard);
//mainPanel.add("View Card", viewCard);
contentPane.add(mainPanel);
layout.show(mainPanel, "Menu Card");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 275);
frame.setResizable(false);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e){
Object source =e.getSource();
if(source == loadBut){
try {
FileInputStream fis = new FileInputStream (userNameField.getText());
ObjectInputStream ois = new ObjectInputStream(fis);
contactList.clear();
contactSize = 0;
for(; true; contactSize++){
contactList.add( (Contact) ois.readObject() );
numContactsField.setText("" + (contactSize+1) );
}
} catch(EOFException e2){
} catch(Exception e2){
e2.printStackTrace();
}
}
if(source == addBut)
layout.show(mainPanel, "Add Card");
if(source == viewBut){
contactListArray = new String[contactSize][5];
for(int i = 0; i < contactSize; i++){
contactListArray[i][0] = contactList.get(i).firstName;
contactListArray[i][1] = contactList.get(i).lastName;
contactListArray[i][2] = contactList.get(i).eAddress;
contactListArray[i][3] = contactList.get(i).address;
contactListArray[i][4] = contactList.get(i).phoneNum;
}
DefaultTableModel model = new DefaultTableModel(contactListArray,columnNames);
viewContacts = new JTable(model);
header = viewContacts.getTableHeader();
viewContacts.setFillsViewportHeight(true);
viewContacts.revalidate();
viewCardMid.add(header, BorderLayout.NORTH);
viewCardMid.add(viewContacts, BorderLayout.CENTER);
viewCard.add(viewCardMid, BorderLayout.CENTER);
mainPanel.add("View Card", viewCard);
layout.show(mainPanel, "View Card");
}
if(source == deleteBut)
layout.show(mainPanel, "Delete Card");
if(source == saveContactBut){
contactList.add(new Contact());
contactList.get(contactSize).firstName = firstNameField.getText();
contactList.get(contactSize).lastName = lastNameField.getText();
contactList.get(contactSize).eAddress = eAddressField.getText();
contactList.get(contactSize).address = addressField.getText();
contactList.get(contactSize).phoneNum = phoneNumField.getText();
contactSize++;
firstNameField.setText("");
lastNameField.setText("");
eAddressField.setText("");
addressField.setText("");
phoneNumField.setText("");
}
if(source == backupBut){
try{
FileOutputStream fos = new FileOutputStream (userNameField.getText(), false);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for(int i = 0; i < contactSize; i++)
oos.writeObject(contactList.get(i));
oos.close();
}
catch (IOException e2){
System.out.println("IO Exception " + e2);
}
}
for(int i = 0; i < 5; i++)
if(source == topMenuButton[i]){
layout.show(mainPanel, "Menu Card");
numContactsField.setText("" + contactSize);
}
}
}
The problem revolves around you lack of understanding in how tables and the CardLayout works..
// This is good...
DefaultTableModel model = new DefaultTableModel(contactListArray, columnNames);
// This is bad...
viewContacts = new JTable(model);
// This is bad...and raises some eyebrows
header = viewContacts.getTableHeader();
// This okay, but doesn't belong here, and is pointless given the following code...
viewContacts.setFillsViewportHeight(true);
// Pointless, you've not added the component to anything yet..
viewContacts.revalidate();
// ?? What ??
viewCardMid.add(header, BorderLayout.NORTH);
// Not good. The table should be added to a JScrollPane first and the scroll
// pane added to the card
viewCardMid.add(viewContacts, BorderLayout.CENTER);
// Okay, but wrong place...
viewCard.add(viewCardMid, BorderLayout.CENTER);
// Here is your main problem. The card layout only allows one component to exist
// for a given name. If you try and add another card, it is discarded and the first
// component with that name remains
mainPanel.add("View Card", viewCard);
// Not bad...
layout.show(mainPanel, "View Card");
Instead of creating the table view when the view button is pressed, you should initalise and the view when you first create the UI and replace/update the table model when you click the view button...
In your constructor you should add...
viewContacts = new JTable(); // Don't need the model at this stage
viewContacts.setFillsViewportHeight(true);
viewCardMid.add(new JScrollPane(viewContacts), BorderLayout.CENTER);
mainPanel.add("View Card", viewCard);
And in your view button action code...
DefaultTableModel model = new DefaultTableModel(contactListArray, columnNames);
viewContacts.setModel(model);
mainPanel.add("View Card", viewCard);
Also, as has begin pointed about, you should not be using static class fields, it's not required in your case and will cause you issues as the complexity of your program grows.
You should be using if-else statements in you action performed method, this will reduce the possibility of logic errors and help improve performance
You should also investigate moving the logic for each view into it's own class, so as to reduce the clutter in your main class
Take the time to read through Creating a GUI With JFC/Swing, in particular, I'd looking into How to use Tables and How to use CardLayout
You make your variables static. The memory for static variables is not allocated on the stack but in regular memory. I didnt look at your code in detail but i would try to remove all static variables in your class and try again from there.
So I have a simple GUI that can only open text files and should just display them in a text area to be edited. I know my string contains the files contents since I can print it out, but when I try and add it to my text area, it does not show up. I was wondering if this was a problem of overlapping text areas but I can't seem to find the error.
The first part of my code just creates the GUI. The other part should open a file and fill the text area with it. Where exactly is the problem and how do I fix it? Any help would be appreciated.
Here is part of my code which deals with creating the frames and panels:
public class MenuView extends JFrame {
private JPanel centerPanel;
private JPanel bottomPanel;
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenuItem openItem;
private JMenuItem closeItem;
private JButton setButton;
private JTextField text;
private JTextArea label;
private JMenuItem fileNew;
public MenuView(){
super();
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setTitle("Menu Demo");
//The center panel that will contain text
centerPanel = new JPanel();
centerPanel.setLayout(new FlowLayout());
label = new JTextArea(400,500);
centerPanel.add(label);
add(centerPanel, BorderLayout.CENTER);
//The bottom panel with the text field and button
bottomPanel = new JPanel();
bottomPanel.setLayout(new GridLayout(1, 2));
setButton = new JButton("Set Text");
text = new JTextField();
bottomPanel.add(setButton);
bottomPanel.add(text);
add(bottomPanel, BorderLayout.SOUTH);
//Setting up the menu
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
fileNew = new JMenu("New");
openItem = new JMenuItem("Open");
closeItem = new JMenuItem("Exit");
fileMenu.add(openItem);
fileMenu.add(closeItem);
fileMenu.add(fileNew);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
setButton.addActionListener(new ButtonCommand(label, text));
closeItem.addActionListener(new QuitMenuCommand());
openItem.addActionListener(new OpenMenuCommand(label));
}
public static void main(String [] args){
MenuView v = new MenuView();
v.setVisible(true);
}
}
Here is the code that deals with opening the files:
public class OpenMenuCommand implements ActionListener {
private JTextArea theLabel;
private JFileChooser fc;
private String k = "";
public OpenMenuCommand(JTextArea l){
theLabel = l;
theLabel.getParent();
fc = new JFileChooser();
fc.setFileFilter(new FileNameExtensionFilter("Text file", "txt"));
}
public void actionPerformed(ActionEvent e) {
StringBuffer text = new StringBuffer();
int returnValue = fc.showOpenDialog(null);
if(returnValue == fc.APPROVE_OPTION){
theLabel.removeAll();
File f = fc.getSelectedFile();
try{
BufferedReader inFile = new BufferedReader(new FileReader(f));
String in = inFile.readLine();
while(in != null){
k = k + in;
in = inFile.readLine();
}
System.out.println(k);
theLabel.setText(k);
inFile.close();
theLabel.setVisible(true);
}catch(FileNotFoundException exc){
//Should never trigger
}catch(IOException exc){
theLabel.setText("Error reading in file.");
}
}
}
}
Your stuff is being added to the JTextArea but you're not seeing due the size of the JTextArea. It's actually a friggin' big JTextArea:
label = new JTextArea(400, 500);
And by adding the huge JTextArea to a FlowLayout-using JPanel much of it is off the screen.
To see what I mean, add this to your actionPerformed method:
System.out.println(theLabel.getBounds());
You'll see that the width and height are tremendous, and what's more, the left side is a large negative number.
Solution: Make your JTextArea more reasonable size (see in the API what these numbers mean -- row and column, not points) and add it to a JScrollPane and then add that BorderLayout.CENTER to a BorderLayout using container.
For example, the small GUI SSCCE shows your JTextArea in a FlowLayout using JPanel on the left and my JTextArea inside of a JScrollPane on the right:
import java.awt.*;
import javax.swing.*;
public class MenuViewSSCCE {
private static final Dimension APP_SIZE = new Dimension(500, 400);
private static void createAndShowUI() {
JTextArea label = new JTextArea(400, 500); // friggin big!
JTextArea label2 = new JTextArea(400, 500); // friggin big!
label.setText("Look at how big this JTextArea is!");
label2.setText("Look at how big this JTextArea is!");
JPanel centerPanel = new JPanel();
centerPanel.setPreferredSize(APP_SIZE);
centerPanel.setLayout(new FlowLayout()); // this line is redundant
centerPanel.add(label);
JScrollPane myScrollpane = new JScrollPane(label2);
myScrollpane.setPreferredSize(APP_SIZE);
JPanel gridPanel = new JPanel(new GridLayout(1, 0));
gridPanel.add(centerPanel);
gridPanel.add(myScrollpane);
JFrame frame = new JFrame("Your code on left, mine on right");
frame.getContentPane().add(gridPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}