Buttons, JTextFields and JComboBox's are unclickable - java

The program consists of a tabbed view with a few JTextField's and JButtons in the first two and 2 JTables and JButton in the third. The buttons work fine in the first two tabs, but on the third it is un-clickable. I tried changing the button to something else like a JComboBox or JTextField but those are uneditable and unclickable also. Setting the setEnabled() and setEditable() functions to true doesn't seem to work. I have no idea what's going on.
The only thing i have done different from normal is this piece of code to forcefully repaint the tab when I click on a cell in the table. But even when this hasn't been called i still cant
ContentIWantToRepaint.this.paintImmediately(ContentIWantToRepaint.this.getVisibleRect());
Some other information about the layout:
The contents of the tab are held in a JPanel with a GridBagLayout
JTextField
Table Header
Table Contents
JTextField
Table Header
Table Contents
Button
Any suggestions?
checkOutPanel.java
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.table.DefaultTableModel;
public class checkOutPanel extends JPanel {
private JTable userTable;
private JTable bookTable;
private JScrollPane scrollUserTable, scrollBookTable;
private JLabel userLabel, bookLabel;
private DefaultTableModel userTableModel = new DefaultTableModel(){
public boolean isCellEditable(int row, int column){return false;}
};
private DefaultTableModel bookTableModel = new DefaultTableModel(){
public boolean isCellEditable(int row, int column){return false;}
};
private int selectedUser, selectedBook;
private JComboBox date_month, date_day, date_year;
public checkOutPanel(){
JPanel mainGrid = new JPanel();//panel that will hold all stuff in tab
JPanel buttonPanel = new JPanel();//panel for holding buttons
mainGrid.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx=0; c.gridy=0; //first row first column
c.anchor = GridBagConstraints.WEST;//align left
c.fill = GridBagConstraints.HORIZONTAL;
//1 row, 2 columns, 15 horizontal padding, 0 vertical padding
//buttonPanel.setLayout(new GridLayout(1,2,15,0));
//labels to describe what the user has to do
userLabel = new JLabel("User :");
bookLabel = new JLabel("Book :");
JLabel dateLabel = new JLabel("Date :");
JPanel datePanel = new JPanel();
bookTable = new JTable(bookTableModel);
bookTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
userTable = new JTable(userTableModel);
userTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Dimension d = new Dimension(500, 120);
scrollBookTable = new JScrollPane(bookTable);
scrollBookTable.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollBookTable.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollBookTable.setMaximumSize(d);
scrollBookTable.setMinimumSize(d);
scrollBookTable.setPreferredSize(d);
scrollUserTable = new JScrollPane(userTable);
scrollUserTable.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollUserTable.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollUserTable.setMaximumSize(d);
scrollUserTable.setMinimumSize(d);
scrollUserTable.setPreferredSize(d);
updateTables();
//String[] month = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
//Vector<Integer> days = new Vector<Integer>();
//for (int i=1 ; i<=31 ; i++) { days.add(i); }
//Vector<Integer> years = new Vector<Integer>();
//for (int i=2012 ; i>=1900 ; i--) { years.add(i); }
//date_month = new JComboBox(days);
JButton testButton = new JButton("WORK!!!!!!!");
//date_day = new JTextField(6);
//date_year = new JTextField(6);
//datePanel.add(dateLabel);
//datePanel.add(date_month);
//datePanel.add(date_day);
//datePanel.add(date_year);
mainGrid.add(userLabel, c); c.gridy++;
mainGrid.add(userTable.getTableHeader(), c); c.gridy++;
mainGrid.add(scrollUserTable, c); c.gridy++;
c.insets = new Insets(15, 0, 0, 0);//put some padding between users and books
mainGrid.add(bookLabel, c); c.gridy++;
c.insets= new Insets(0,0,0,0);//back to no padding
mainGrid.add(bookTable.getTableHeader(), c); c.gridy++;
mainGrid.add(scrollBookTable, c); c.gridy++;
c.insets = new Insets(15, 0, 0, 0);//put some padding between books and date
mainGrid.add(testButton, c); c.gridy++;
this.add(mainGrid);//add contents to tab
userTable.addMouseListener(new mouseListener());
bookTable.addMouseListener(new mouseListener());
}
public class mouseListener implements MouseListener{
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {
if(e.getSource()==userTable){
selectedUser=userTable.getSelectedRow();
userLabel.setText("User : "+ (selectedUser!=-1 ? selectedUser : ""));
//don't know why i should need to use this, but it makes it work
checkOutPanel.this.paintImmediately(checkOutPanel.this.getVisibleRect());
}else if(e.getSource()==bookTable){
selectedBook = bookTable.getSelectedRow();
System.out.println("Date Month : "+date_month.getSelectedItem().toString());
bookLabel.setText("Book : "+ (selectedBook!=-1 ? selectedBook : ""));
//don't know why i should need to use this, but it makes it work
checkOutPanel.this.paintImmediately(checkOutPanel.this.getVisibleRect());
}
}
}
private void updateTables(){
bookTableModel.setDataVector(fillBookData(SystemStart.getDbName()), fillBookColNames());
userTableModel.setDataVector(fillUserData(SystemStart.getDbName()), fillUserColNames());
}
private Vector<String> fillUserColNames(){
Vector<String> colNames = new Vector<String>();
colNames.add("ID");
colNames.add("First");
colNames.add("Last");
colNames.add("Phone");
colNames.add("Email");
colNames.add("Address");
colNames.add("City");
colNames.add("State");
colNames.add("Zip");
return colNames;
}
private Vector<String> fillBookColNames(){
Vector<String> colNames = new Vector<String>();
colNames.add("Title");
colNames.add("Format");
colNames.add("Author");
colNames.add("ISBN");
colNames.add("Year Pub.");
colNames.add("Publisher");
colNames.add("Call #");
colNames.add("Copy #");
return colNames;
}
private Vector<Vector<String>> fillUserData(String dbName){
Vector<Vector<String>> v = new Vector<Vector<String>>();
Vector<String> u;
for (int i=0; i<10; i++){
u = new Vector<String>(9);
u.add(""+i);
u.add("First");
u.add("Last");
u.add("Phone");
u.add("Email");
u.add("Address");
u.add("City");
u.add("State");
u.add("Zip");
v.add(u);
}
return v;
}
private Vector<Vector<String>> fillBookData(String dbName) {
Vector<Vector<String>> v = new Vector<Vector<String>>();
Vector<String> b;
for (int i=0; i<10; i++){//only include books that arent check out
b = new Vector<String>(8);
b.add("Title "+i);
b.add("Format");
b.add("Author");
b.add("ISBN");
b.add("Year Pub.");
b.add("Publisher");
b.add("Call #");
b.add("Copy #");
v.add(b);
}
return v;
}
}
Use this file to see how it doesn't work:
import javax.swing.JFrame;
public class SystemStart{
private static String dbName = "dbnamehere.db";
public static void main(String[] args) {
//new TabbedFrame("Libary System");
JFrame jf = new JFrame("WORK!");
jf.add(new checkOutPanel());
jf.pack();
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static String getDbName(){return dbName;}
}

You're adding to the panel a label, then the table's header and then the scrollpane which contains the table (...and the table header). Remove the two lines where you're adding to mainGrid the table headers (you should just add the scrollpanes):
mainGrid.add(userTable.getTableHeader(), c); c.gridy++;
mainGrid.add(bookTable.getTableHeader(), c); c.gridy++;
Your button will work now.

Related

ActionListener, List Issue

I am running into an issue with my program. The objective is to collect input (movie name, media type and the year) and append it to a list when "add movie" is clicked. Then when the "show movies" button is clicked the list will display in the text area. I'm not sure what I am missing or what I've done wrong.
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class MovieDatabase extends JFrame implements ActionListener{
//create LinkedList of Movie Objects
LinkedList<Movie> list = new LinkedList<Movie>();
//JPanel for input movie
private JPanel inputJPanel;
//JLable and JTextField for Movie Name
private JLabel movieJLabel;
private JTextField movieJTextField;
//JLable and JTextField for Media
private JLabel mediaJLabel;
private JTextField mediaJTextField;
//JLable and JTextField for Release Year
private JLabel yearJLabel;
private JTextField yearJTextField;
//JButton to add movie to a list
private JButton addJButton;
//JButton to show movie in text area
private JLabel showJLabel;
private JButton showJButton;
//JTextArea to display movies from list
private JTextArea showJTextArea;
private JPanel listJPanel;
//no argument constructor
public MovieDatabase(){
createUserInterface();
}
//create GUI window with components
private void createUserInterface(){
//get content pane window and set layout to null - no layout manager
Container contentPane = getContentPane();
contentPane.setLayout(null);
//set up input panel
inputJPanel = new JPanel();
inputJPanel.setLayout(null);
inputJPanel.setBorder(new TitledBorder("Input Movie")); //anonymous object
inputJPanel.setBounds(20,4,260,178);// (x,y,w,h)
contentPane.add(inputJPanel);
//set up input panel
showJLabel = new JLabel();
showJLabel.setLayout(null);
showJLabel.setText("Movies: ");
showJLabel.setBounds(300,0,260,25);// (x,y,w,h)
contentPane.add(showJLabel);
//set up payment JTextArea here
showJTextArea = new JTextArea();
showJTextArea.setBounds(300,30,300,145);// (x,y,w,h)
showJTextArea.setEditable(false);
contentPane.add(showJTextArea);
//show movies JButton
showJButton = new JButton();
showJButton.setBounds(480,175,110,30);
showJButton.setText("Show Movies");
contentPane.add(showJButton);
//movie name JLabel
movieJLabel = new JLabel();
movieJLabel.setBounds(10,24,100,21);// (x,y,w,h)
movieJLabel.setText("Movie Name:");
inputJPanel.add(movieJLabel);
//movie name JTextField
movieJTextField = new JTextField();
movieJTextField.setBounds(104,24,120,21);
movieJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputJPanel.add(movieJTextField);
//media name JLabel
mediaJLabel = new JLabel();
mediaJLabel.setBounds(10,54,100,21);// (x,y,w,h)
mediaJLabel.setText("Media:");
inputJPanel.add(mediaJLabel);
//media name JTextField
mediaJTextField = new JTextField();
mediaJTextField.setBounds(104,54,120,21);
mediaJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputJPanel.add(mediaJTextField);
//year name JLabel
yearJLabel = new JLabel();
yearJLabel.setBounds(10,84,100,21);// (x,y,w,h)
yearJLabel.setText("Release Year:");
inputJPanel.add(yearJLabel);
//year name JTextField
yearJTextField = new JTextField();
yearJTextField.setBounds(104,84,80,21);
yearJTextField.setHorizontalAlignment(JTextField.RIGHT);
inputJPanel.add(yearJTextField);
//add movie JButton
addJButton = new JButton();
addJButton.setBounds(92,138,94,24);
addJButton.setText("Add Movie");
inputJPanel.add(addJButton);
//set window properties
setTitle("Movie"); //set title bar
setSize(625, 250);//window size
setVisible(true); //display window
addJButton.addActionListener(this);
showJButton.addActionListener(this);
}
public void addButtonactionPerformed(ActionEvent e){
String movieName = movieJTextField.getText();
String media = mediaJTextField.getText();
int year = Integer.parseInt(yearJTextField.getText());
//create instance of Movie
Movie movie = new Movie(movieName, media, year);
list.add(movie);
movieJTextField.setText("");
mediaJTextField.setText("");
yearJTextField.setText("");
}
private void showButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
showJTextArea.setText("");
String str = String.format("%-20s%-20s%-20s\n", "Year", "Media", "Title");
showJTextArea.append(str);
for (Movie movie : list) {
str = String.format("%-20s%-19s%-22s\n", Integer.toString(movie.year), movie.media, movie.name);
showJTextArea.append(str);
}
}
}
class Movie{
String name;
String media;
int year;
public Movie(String n, String m, int y){
name = n;
media = m;
year = y;
}
public class MovieGUI {
public static void main(String[] args) {
MovieDatabase application = new MovieDatabase();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//close and stop application
}
}
null layouts are going to come back to haunt you. There is no such thing as "pixel perfect" layouts, there are just to many variables associated with the differences in the way things get rendered between different hardware and OSs to even consider making this choice.
Take the time to learn how to use the layout managers Laying Out Components Within a Container
You've not implemented the requirements for ActionListener (showButtonActionPerformed suggests that you're using something like Netbeans form editor).
Maybe you should take a look at How to Write an Action Listener and How to Use Buttons, Check Boxes, and Radio Buttons
You might also want to look at How to Use Tables
To my mind, you need to take a slightly different tact and focus on separating the areas of responsibility. Collecting the movie information has nothing with either storing the results or displaying them, so I'd have those separated into it's own container, so you can more easily manage it.
This leads to the question of, "how do you notify interested parties when a user 'adds' a movie?". Interestingly, you're somewhat already familiar with the concept.
Essentially, you use a "listener" or, as it's more commonly known, an "observer pattern". This allows you to notify interested parties that something has happened, in this case, a user has created a new movie.
For example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
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 MovieManagerPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Movie {
String name;
String media;
int year;
public Movie(String n, String m, int y) {
name = n;
media = m;
year = y;
}
public String getName() {
return name;
}
public String getMedia() {
return media;
}
public int getYear() {
return year;
}
}
public class MovieManagerPane extends JPanel {
private JTextArea moviesTextArea;
private List<Movie> movies = new ArrayList<>(32);
public MovieManagerPane() {
setLayout(new BorderLayout());
moviesTextArea = new JTextArea(20, 40);
String str = String.format("%-20s%-20s%-20s\n", "Year", "Media", "Title");
moviesTextArea.append(str);
MoviePane moviePane = new MoviePane();
moviePane.setBorder(new CompoundBorder(new TitledBorder("Input Movie"), new EmptyBorder(4, 4, 4, 4)));
moviePane.addMovieListener(new MoviePane.MovieListener() {
#Override
public void movieWasAdded(MoviePane source, Movie movie) {
movies.add(movie);
String str = String.format("%-20s%-20s%-20s\n", movie.getYear(), movie.getMedia(), movie.getName());
moviesTextArea.append(str);
}
});
add(moviePane, BorderLayout.LINE_START);
add(moviesTextArea);
}
}
public class MoviePane extends JPanel {
public static interface MovieListener extends EventListener {
public void movieWasAdded(MoviePane source, Movie movie);
}
//JLable and JTextField for Movie Name
private JLabel movieJLabel;
private JTextField movieJTextField;
//JLable and JTextField for Media
private JLabel mediaJLabel;
private JTextField mediaJTextField;
//JLable and JTextField for Release Year
private JLabel yearJLabel;
private JTextField yearJTextField;
//JButton to add movie to a list
private JButton addJButton;
public MoviePane() {
setLayout(new GridBagLayout());
movieJLabel = new JLabel("Movie Name:");
mediaJLabel = new JLabel("Media:");
yearJLabel = new JLabel("Release Year:");
movieJTextField = new JTextField(10);
mediaJTextField = new JTextField(10);
yearJTextField = new JTextField(10);
addJButton = new JButton("Add Movie");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = gbc.EAST;
gbc.insets = new Insets(4, 4, 4, 4);
add(movieJLabel, gbc);
gbc.gridy++;
add(mediaJLabel, gbc);
gbc.gridy++;
add(yearJLabel, gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = gbc.WEST;
add(movieJTextField, gbc);
gbc.gridy++;
add(mediaJTextField, gbc);
gbc.gridy++;
add(yearJTextField, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.NONE;
gbc.weighty = 1;
gbc.anchor = gbc.SOUTH;
add(addJButton, gbc);
addJButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
// Use a JSpinner or JFornattedTextField to avoid this
int year = Integer.parseInt(yearJTextField.getText());
Movie movie = new Movie(movieJTextField.getText(), mediaJTextField.getText(), year);
fireMovieWasAdded(movie);
} catch (NumberFormatException exp) {
JOptionPane.showMessageDialog(MoviePane.this, "Invalid year", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
}
public void addMovieListener(MovieListener listener) {
listenerList.add(MovieListener.class, listener);
}
public void removeMovieListener(MovieListener listener) {
listenerList.remove(MovieListener.class, listener);
}
protected void fireMovieWasAdded(Movie movie) {
MovieListener[] listeners = listenerList.getListeners(MovieListener.class);
if (listeners.length == 0) {
return;
}
for (MovieListener listener : listeners) {
listener.movieWasAdded(this, movie);
}
}
}
}
You may also want to take a look at How to Use Spinners and How to Use Formatted Text Fields for dealing with "non-string" input

Simple GUI guidance. Can I stick with BorderLayout or do I need something else?

I'm trying to create a GUI for a personal project. I have a file chooser, a console area, a text field (with label), a button panel(2 buttons) and finally a "drop zone" area.
The GUI is divided vertically in half with the console on the right.
On the UpperLeft I have FileChooser positioned at BorderLayout.CENTER, followed by the ButtonPanel at BorderLayout.SOUTH.
Below that is the "drop zone"
It currently looks something like this:
_________________
| file | console|
| chooser| |
| buttons| |
|--------| |
| drop | |
| zone | |
|________|________|
I want to add a new text field between the file chooser and the button panel, but when I change file chooser to NORTH, jtextfield to CENTER and buttons to SOUTH, the file chooser is weirdly small and the jtextfield is much to large. I think this is just due to the inherent properties of BorderLayout, but I am not sure. Should I use a different Layout and what kind of changes would I make?
I've included the code I'm working with below. Thank you for any help in advance!
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.io.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.text.*;
import java.util.*;
import java.nio.*;
public class ConsolidatorDemo extends JPanel implements ActionListener {
JFileChooser fc;
JButton clear;
JButton ok;
JTextArea console;
JList<File> dropZone;
DefaultListModel listModel;
JSplitPane childSplitPane, parentSplitPane;
PrintStream ps;
JTextField wordCount;
JLabel lblCount;
public ConsolidatorDemo() {
super(new BorderLayout());
fc = new JFileChooser();;
fc.setMultiSelectionEnabled(true);
fc.setDragEnabled(true);
fc.setControlButtonsAreShown(false);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
JPanel fcPanel = new JPanel(new BorderLayout());
fcPanel.add(fc, BorderLayout.CENTER);
clear = new JButton("Clear All");
clear.addActionListener(this);
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
buttonPanel.add(clear, BorderLayout.LINE_END);
ok = new JButton("OK");
ok.addActionListener(this);
buttonPanel.add(ok, BorderLayout.WEST);
JPanel sizePanel = new JPanel(new BorderLayout());
sizePanel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
wordCount = new JTextField();
sizePanel.add(wordCount, BorderLayout.LINE_END);
// lblCount = new JLabel("Word Counter");
// buttonPanel.add(lblCount, BorderLayout.CENTER);
JPanel leftUpperPanel = new JPanel(new BorderLayout());
leftUpperPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
leftUpperPanel.add(fcPanel, BorderLayout.NORTH);
leftUpperPanel.add(sizePanel, BorderLayout.CENTER);
leftUpperPanel.add(buttonPanel, BorderLayout.PAGE_END);
JScrollPane leftLowerPanel = new javax.swing.JScrollPane();
leftLowerPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
listModel = new DefaultListModel();
dropZone = new JList(listModel);
dropZone.setCellRenderer(new FileCellRenderer());
dropZone.setTransferHandler(new ListTransferHandler(dropZone));
dropZone.setDragEnabled(true);
dropZone.setDropMode(javax.swing.DropMode.INSERT);
dropZone.setBorder(new TitledBorder("Selected files/folders"));
leftLowerPanel.setViewportView(new JScrollPane(dropZone));
childSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
leftUpperPanel, leftLowerPanel);
childSplitPane.setDividerLocation(400);
childSplitPane.setPreferredSize(new Dimension(480, 650));
console = new JTextArea();
console.setColumns(40);
console.setLineWrap(true);
console.setBorder(new TitledBorder("Console"));
parentSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
childSplitPane, console);
parentSplitPane.setDividerLocation(480);
parentSplitPane.setPreferredSize(new Dimension(800, 650));
add(parentSplitPane, BorderLayout.CENTER);
this.redirectSystemStreams();
}
private void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
console.append(text);
}
});
}
private void redirectSystemStreams() {
OutputStream out = new OutputStream() {
#Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
public void setDefaultButton() {
getRootPane().setDefaultButton(ok);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clear) {
listModel.clear();
}
if(e.getSource() == ok){
try{
if(dropZone.isSelectionEmpty() == true){
int start = 0;
int end = dropZone.getModel().getSize() - 1;
if (end >= 0) {
dropZone.setSelectionInterval(start, end);
}
}
List<File> list = dropZone.getSelectedValuesList();
for (File file : list) {
//StringEditing.editDocument(file, Integer.parseInt(wordCount.getText()));
}
}
catch(NumberFormatException nfe){
System.out.println("You did not input a number");
}
catch(Exception ef){
System.out.println("Something is wrong!");
}
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
try {
//UIManager.setLookAndFeel("de.javasoft.plaf.synthetica.SyntheticaBlackStarLookAndFeel");
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}catch (Exception e){
e.printStackTrace();
}
//Create and set up the window.
JFrame frame = new JFrame("Consolidator!");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//Create and set up the menu bar and content pane.
ConsolidatorDemo demo = new ConsolidatorDemo();
demo.setOpaque(true); //content panes must be opaque
frame.setContentPane(demo);
//Display the window.
frame.pack();
frame.setVisible(true);
demo.setDefaultButton();
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class FileCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
Component c = super.getListCellRendererComponent(
list,value,index,isSelected,cellHasFocus);
if (c instanceof JLabel && value instanceof File) {
JLabel l = (JLabel)c;
File f = (File)value;
l.setIcon(FileSystemView.getFileSystemView().getSystemIcon(f));
l.setText(f.getName());
l.setToolTipText(f.getAbsolutePath());
}
return c;
}
}
class ListTransferHandler extends TransferHandler {
private JList list;
ListTransferHandler(JList list) {
this.list = list;
}
#Override
public boolean canImport(TransferHandler.TransferSupport info) {
// we only import FileList
if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}
return true;
}
#Override
public boolean importData(TransferHandler.TransferSupport info) {
if (!info.isDrop()) {
return false;
}
// Check for FileList flavor
if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
displayDropLocation("List doesn't accept a drop of this type.");
return false;
}
// Get the fileList that is being dropped.
Transferable t = info.getTransferable();
List<File> data;
try {
data = (List<File>)t.getTransferData(DataFlavor.javaFileListFlavor);
}
catch (Exception e) { return false; }
DefaultListModel model = (DefaultListModel) list.getModel();
for (Object file : data) {
model.addElement((File)file);
}
return true;
}
private void displayDropLocation(String string) {
System.out.println(string);
}
}
I ended up using GridBagLayout using the various answers here, thank you for your help!
I've got a ton of extra/ unused stuff in this example, mostly because I was starting to implement the functions I needed when I figured I'd post an update here. Should still compile and run fine though.
One problem I have is that the GUI spawns with the button panel / drop zone divider sort of eating into each other. On top of that, there is a text field which has no width despite it working perfectly fine before I used the split panes. If anyone had any knowledge of how to get around these bugs I'd appreciate it!
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.io.*;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.text.*;
import java.util.*;
import java.nio.*;
public class TestGridBagLayout {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
JButton clear;
JButton ok;
JLabel num;
JTextField input;
JSplitPane childSplitPane, parentSplitPane;
PrintStream ps;
JTextArea console;
JList<File> dropZone;
DefaultListModel listModel;
pane.setLayout(new GridBagLayout());
JPanel leftUpperPanel = new JPanel(new GridBagLayout());
leftUpperPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}
JFileChooser fc = new JFileChooser();;
fc.setMultiSelectionEnabled(true);
fc.setDragEnabled(true);
fc.setControlButtonsAreShown(false);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridwidth = 4;
c.gridx = 0;
c.gridy = 1;
leftUpperPanel.add(fc, c);
ok = new JButton("OK");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.weightx = 0.5;
c.gridx = 0; //aligned with button 2
c.gridwidth = 1;
c.gridy = 2; //third row
leftUpperPanel.add(ok, c);
num = new JLabel("Word Count:");
c.fill = GridBagConstraints.NONE;
c.anchor = GridBagConstraints.PAGE_END;
c.insets = new Insets(10,0,0,0); //top padding
c.weightx = 0.25;
c.gridx = 1;
c.gridy = 2;
leftUpperPanel.add(num, c);
input = new JTextField("", 50);
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_END;
c.insets = new Insets(10,0,0,0); //top padding
c.weightx = 0.25;
c.gridx = 2;
c.gridy = 2;
leftUpperPanel.add(input, c);
clear = new JButton("Clear All");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0;
c.anchor = GridBagConstraints.PAGE_END;
c.insets = new Insets(10,0,0,0); //top padding
c.weightx = 0.5;
c.gridx = 3;
c.gridy = 2;
leftUpperPanel.add(clear, c);
JScrollPane leftLowerPanel = new javax.swing.JScrollPane();
leftLowerPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
listModel = new DefaultListModel();
dropZone = new JList(listModel);
dropZone.setCellRenderer(new FileCellRenderer());
dropZone.setTransferHandler(new ListTransferHandler(dropZone));
dropZone.setDragEnabled(true);
dropZone.setDropMode(javax.swing.DropMode.INSERT);
dropZone.setBorder(new TitledBorder("Selected files/folders"));
leftLowerPanel.setViewportView(new JScrollPane(dropZone));
childSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
leftUpperPanel, leftLowerPanel);
childSplitPane.setDividerLocation(400);
childSplitPane.setPreferredSize(new Dimension(480, 650));
console = new JTextArea();
console.setColumns(40);
console.setLineWrap(true);
console.setBorder(new TitledBorder("Console"));
parentSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
childSplitPane, console);
parentSplitPane.setDividerLocation(480);
parentSplitPane.setPreferredSize(new Dimension(800, 650));
pane.add(parentSplitPane);
}
public static void initUI() {
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestGridBagLayout testMultiplePanels = new TestGridBagLayout();
testMultiplePanels.initUI();
}
});
}
}
You could start by using a GridLayout setup to display two columns and one row. This would start out as the primary display/container/panel for the vertical split. You would then need another JPanel, possibly with a GridLayout setup to display one column and two rows, this would display the file chooser and drop zone.
You would then add this panel and the text area to the primary panel.
You could also do this using a single GridBagLaout, but you might find using compound GridLayouts easier.
See How to Use GridLayout and How to Use GridBagLayout for more details
I would probably create a panel with BoxLayout with a y-axis orientation, and put my 'two halves' in that, and put it on the west end of the JFrame's default BoxLayout. Then I'd put the other panel in the center, assuming you want it to stretch and shrink in both directions as the user changes the window size.
For flexibility, you could use a JSplitPane having HORIZONTAL_SPLIT; put the console on the right and a nested JSplitPane having VERTICAL_SPLIT on the left to hold the fcPanel and dropZone.

JTable multiple Row header

The SSSCE for the problem i face is posted below
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
public class TableTest extends JFrame{
private static final long serialVersionUID = 1L;
private JPanel panel;
private JPanel buttonPanel;
private JTable table;
private JTable headerTable;
JButton cancelButton;
private DefaultTableModel tableModel;
private DefaultTableModel headerTableModel;
String fileName = null;
public TableTest() {
init();
}
public void init() {
setTitle("Table");
//Panel
panel = new JPanel();
panel.setLayout(new GridBagLayout());
this.getContentPane().add(panel);
buttonPanel = new JPanel();
//cancel button
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
buttonPanel.add(cancelButton);
String[] headerNames = {"", "Col 1", "Col 2", "Col 1", "Col 2"};
String[] mainHeaderNames = {"Header 1", "Header2"};
headerTableModel = new DefaultTableModel();
for (int i = 0; i < mainHeaderNames.length; i++) {
headerTableModel.addColumn(mainHeaderNames[i]);
}
//table model
tableModel = new DefaultTableModel() {
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column) {
if(column == 0){
return true;
} else {
return false;
}
}
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return Boolean.class;
}
return null;
}
};
//set default model to the table
table = new JTable(tableModel);
headerTable = new JTable(headerTableModel);
// set table header
for (int col = 0; col < headerNames.length; col++) {
tableModel.addColumn(headerNames[col]);
}
//set table dimensions
int height = 0;
int width = 1000;
if(tableModel.getRowCount() < 20) {
height = tableModel.getRowCount()*16;
} else {
height = 350;
}
table.setPreferredScrollableViewportSize(new Dimension(width, height));
//table header column width and height
table.getTableHeader().setPreferredSize(new Dimension(100,28));
headerTable.getTableHeader().setPreferredSize(new Dimension(100,28));
//Set the width for column
DefaultTableColumnModel colModel = (DefaultTableColumnModel)table.getColumnModel();
colModel.setColumnSelectionAllowed(false);
colModel.getColumn(0).setPreferredWidth(5);
colModel.getColumn(1).setPreferredWidth(300);
colModel.getColumn(2).setPreferredWidth(200);
colModel.getColumn(3).setPreferredWidth(300);
colModel.getColumn(4).setPreferredWidth(200);
//table setting
table.setFillsViewportHeight(true);
headerTable.setFillsViewportHeight(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
headerTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
//The header of column should be fixed.If set to true - columns can be re-arranged
table.getTableHeader().setReorderingAllowed(false);
headerTable.getTableHeader().setReorderingAllowed(false);
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JScrollPane headerScrollPane = new JScrollPane(headerTable);
headerScrollPane.setPreferredSize(new Dimension(100,28));
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
//Add the scroll pane to this panel.
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
panel.add(headerScrollPane, c);
c.anchor = GridBagConstraints.CENTER;
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
panel.add(scrollPane, c);
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 2;
c.weightx = 0;
c.weighty = 0;
panel.add(buttonPanel, c);
addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
int option = JOptionPane.showConfirmDialog(panel, "Do you want to close this window?", " Confirm" , JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if (option == JOptionPane.YES_OPTION) {
dispose();
} else {
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
}
}
});
//Display the window.
if(tableModel.getRowCount() >= 0){
pack();
setAlwaysOnTop(true);
setLocationRelativeTo(this);
setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run(){
new TableTest();
}
});
}
}
Am using two JTables here ,
I am tryin to implement like , if i move split between header 1 and header 2 the respective split line in below table also should be moved.
Since am using two jTables i am not sure how can i achieve this. Or is there any other way to this am new to java please help.
Your layout is wrong. Try to make a layout like this:

Cant add JTable to a GUI

I have a problem creating a JTable in my GUI. The GUI is created in the main thread and enables a file to be opened. The file is then used to create a table model and add info to it. A JTable is then created with the table model and added to the GUI. My problem is that the GUI doesn't show. Code:
package example;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class Example extends JFrame{
private JButton button;
private JTable table;
private DefaultTableModel model;
private String path = "C:/Users/gilbert/Documents/11111.xls";
public Example(){
super("Example");
setLayout(new BorderLayout());
button = new JButton("Start");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
createTableModel_Three_By_Six(path);
}
});
add(button,BorderLayout.NORTH);
setSize(400, 400);
}
public void createTableModel_Three_By_Six(String fpath){
model = new DefaultTableModel();
ExcelParser exPareser = new ExcelParser(fpath);
int rows = exPareser.getRowNumber();
String rowToAdd[] = new String[3];
int i, j = 0;
while(j < rows){
i= 0;
while(i < 3){
rowToAdd[i] = exPareser.accessRow(j);
i++;
j++;
if(j == rows){
if(i==1){
rowToAdd[1] = "";
rowToAdd[2] = "";
}
else if(i==2){
rowToAdd[2] = "";
}
}
}
model.addRow(rowToAdd);
}
table = new JTable(model);
add(new JScrollPane(table));
}
public static void main(String[] args) {
Example app = new Example();
app.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
app.setVisible(true);
}
}
The problem, with your example, is the fact that there are no columns for the table, which means when you add the table to the frame, it doesn't know how to display the table contents.
So, by doing something as simple as...
model = new DefaultTableModel(new Object[]{"A", "B", "C"}, 0);
//...
table = new JTable(model);
add(new JScrollPane(table));
revalidate();
I was able to get the table to appear properly, with it's contents
Beware though, each time you call this method, a new JTable will be created. Instead, you should construct the JScrollPane and JTable at an earlier stage and simply update the TableModel

JButton + radiobox + checkbox

I'd like this program I have to have some kind of "sum" button which will add in the column "Description" summarised information about the movie. Lets say I have "die hard" as a title, age 7 from radiobutton, and horror selected from the checkbox. Pressin the button would put "Die hard, 7, horror" under the column. I have no idea how to aproach this case.
package naplety.Swing;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.JCheckBox;
public class SamodzielnaListaOsob extends JFrame implements ActionListener {
JButton dodaj, erease;
JTextField film;
DefaultListModel<String> listFilm;
DefaultTableModel tableFilm;
public SamodzielnaListaOsob(String title) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JTextField film = new JTextField("Wpisz tytul filmu", 10);
film.setBorder(BorderFactory.createTitledBorder("Film"));
JPanel p1 = new JPanel();
p1.add(film);
JButton dodaj = new JButton("Add to list");
dodaj.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String nowyFilm = film.getText();
if (nowyFilm != "") {
listFilm.addElement(nowyFilm);
film.setText("");
}
}
});
JButton erease = new JButton("Clear");
erease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
film.setText("");
}
});
JButton dodajDoTabeli = new JButton("Add to table");
dodajDoTabeli.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String nowyFilm = film.getText();
if (nowyFilm != "") {
int ile = tableFilm.getRowCount();
tableFilm.addRow(new Object[] { ile + 1, nowyFilm });
}
}
});
JRadioButton sevenbutton = new JRadioButton("7");
JRadioButton twbutton = new JRadioButton("12");
JRadioButton sixbutton = new JRadioButton("16");
JRadioButton eightbutton = new JRadioButton("18");
ButtonGroup bg1 = new ButtonGroup();
bg1.add(sevenbutton);
bg1.add(twbutton);
bg1.add(sixbutton);
bg1.add(eightbutton);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(4, 0));
radioPanel.add(sevenbutton);
radioPanel.add(twbutton);
radioPanel.add(sixbutton);
radioPanel.add(eightbutton);
radioPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Age"));
radioPanel.setSize(200, 200);
JCheckBox Horror = new JCheckBox("Horror");
JCheckBox Komedia = new JCheckBox("Comedy");
JCheckBox Thriller = new JCheckBox("Thriller");
JCheckBoxMenuItem listac = new JCheckBoxMenuItem();
listac.add(Horror);
listac.add(Komedia);
listac.add(Thriller);
JPanel listaChceck = new JPanel();
listaChceck.add(Horror);
listaChceck.add(Komedia);
listaChceck.add(Thriller);
listaChceck.setLayout(new GridLayout(3, 0));
JPanel p2 = new JPanel();
p2.add(dodaj);
p2.add(erease);
p2.add(dodajDoTabeli);
p2.add(radioPanel);
p2.add(listaChceck);
listFilm = new DefaultListModel<String>();
listFilm.addElement("Achacy");
listFilm.addElement("Bonifacy");
listFilm.addElement("Cezary");
JList<String> lista = new JList<String>(listFilm);
JScrollPane sl = new JScrollPane(lista);
sl.setPreferredSize(new Dimension(150, 150));
sl.setBorder(BorderFactory.createTitledBorder("List"));
String[] kolumnyTabeli = { "Nr", "Movie", "Description" };
tableFilm = new DefaultTableModel(kolumnyTabeli, 0) {
};
JTable tabela = new JTable(tableFilm);
JScrollPane st = new JScrollPane(tabela);
st.setPreferredSize(new Dimension(300, 150));
st.setBorder(BorderFactory.createTitledBorder("Table"));
JPanel p3 = new JPanel();
p3.add(sl);
p3.add(st);
setPreferredSize(new Dimension(900, 900));
setVisible(true);
p1.add(p2);
p2.add(p3);
setContentPane(p1);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SamodzielnaListaOsob("List of movies");
}
});
}
}
You need to declare your variables either before you try to access them, or declare them global, which I did. I prefer this way.
Use .pack() on your frame to when you start the program, something actually shows.
Learn to use LayoutManagers for a better look.
Use arrays of RadioButtons and CheckBoxes so its easier to loop through them. I has to manually write a bunch of if statements, which would not be necessary if I could loop through them.
To get is a RadioButton or CheckBox is selected, use .isSelected()
.setVisible(true) after you add all your components.
Here's is your refactored code. I did nothing else to it, but fix the issue posted in your question. It now adds the info the desciption, when you hit the Add Film button.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class SamodzielnaListaOsob extends JFrame {
JButton dodaj, erease;
JTextField film;
DefaultListModel<String> listFilm;
DefaultTableModel tableFilm;
JList<String> lista = null;
JRadioButton sevenbutton = new JRadioButton("7");
JRadioButton twbutton = new JRadioButton("12");
JRadioButton sixbutton = new JRadioButton("16");
JRadioButton eightbutton = new JRadioButton("18");
JCheckBox Horror = new JCheckBox("Horror");
JCheckBox Komedia = new JCheckBox("Comedy");
JCheckBox Thriller = new JCheckBox("Thriller");
ButtonGroup bg1 = new ButtonGroup();
public SamodzielnaListaOsob(String title) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JTextField film = new JTextField("Wpisz tytul filmu", 10);
film.setBorder(BorderFactory.createTitledBorder("Film"));
JPanel p1 = new JPanel();
p1.add(film);
JButton dodaj = new JButton("Add to list");
dodaj.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String nowyFilm = film.getText();
if (nowyFilm != "") {
listFilm.addElement(nowyFilm);
film.setText("");
}
}
});
JButton erease = new JButton("Clear");
erease.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
film.setText("");
}
});
JButton dodajDoTabeli = new JButton("Add to table");
dodajDoTabeli.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String nowyFilm = film.getText();
if (nowyFilm != "") {
int ile = tableFilm.getRowCount();
String title = lista.getSelectedValue();
int age;
if (sixbutton.isSelected()) {
age = 16;
} else if (sevenbutton.isSelected()) {
age = 7;
} else if (eightbutton.isSelected()) {
age = 18;
} else {
age = 12;
}
String genres = "";
if (Horror.isSelected()) {
genres += "Horror, ";
}
if (Komedia.isSelected()) {
genres += "Komedia, ";
}
if (Thriller.isSelected()) {
genres += "Thriller";
}
String desc = title + ", " + age + ", " + genres;
tableFilm.addRow(new Object[]{ile + 1, nowyFilm, desc});
}
}
});
bg1.add(sevenbutton);
bg1.add(twbutton);
bg1.add(sixbutton);
bg1.add(eightbutton);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(4, 0));
radioPanel.add(sevenbutton);
radioPanel.add(twbutton);
radioPanel.add(sixbutton);
radioPanel.add(eightbutton);
radioPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Age"));
radioPanel.setSize(200, 200);
JCheckBoxMenuItem listac = new JCheckBoxMenuItem();
listac.add(Horror);
listac.add(Komedia);
listac.add(Thriller);
JPanel listaChceck = new JPanel();
listaChceck.add(Horror);
listaChceck.add(Komedia);
listaChceck.add(Thriller);
listaChceck.setLayout(new GridLayout(3, 0));
JPanel p2 = new JPanel();
p2.add(dodaj);
p2.add(erease);
p2.add(dodajDoTabeli);
p2.add(radioPanel);
p2.add(listaChceck);
listFilm = new DefaultListModel<String>();
listFilm.addElement("Achacy");
listFilm.addElement("Bonifacy");
listFilm.addElement("Cezary");
lista = new JList<String>(listFilm);
JScrollPane sl = new JScrollPane(lista);
sl.setPreferredSize(new Dimension(150, 150));
sl.setBorder(BorderFactory.createTitledBorder("List"));
String[] kolumnyTabeli = {"Nr", "Movie", "Description"};
tableFilm = new DefaultTableModel(kolumnyTabeli, 0) {
};
JTable tabela = new JTable(tableFilm);
JScrollPane st = new JScrollPane(tabela);
st.setPreferredSize(new Dimension(300, 150));
st.setBorder(BorderFactory.createTitledBorder("Table"));
JPanel p3 = new JPanel();
p3.add(sl);
p3.add(st);
p1.add(p2);
p2.add(p3);
setContentPane(p1);
pack();
setPreferredSize(new Dimension(900, 900));
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SamodzielnaListaOsob("List of movies");
}
});
}
}
Radio buttons and Check Buttons don't work like textfields. In a textfield, the useful values are picked up from the "text" member (example: getText()). A radioButton instead defines a set of fixed choices (well, you can make them dynamic, but it doesn't worth it, there are better components for that kind of work) like "yes" and "no". Usually, when you pickup some rabiobutton, you use the isChecked() method (returns boolean, it may be isChecked(), I don't remember) to react in one way or another. Example:
String age = 0;
if(sevenbutton.isSelected()){
age = 7;
}
Nonetheless, I think you can get the value from the text in the sevenbutton using getText(), but you're gonna need to check which radiobutton is checked anyway. A checkButton works in a pretty similar way, but for non-exclusive choices, so you need to use the isSelected() method, or similar, anyway.
Your method should look like:
private void addMovie(){
String age = "0";
String gender = "";
//Evaluate radioButtons
if(sevenbutton.isSelected()){
age = 7;
}
//Evaluate checkbuttons
if(Horror.isSelected()){
gender = gender+" horror";
}
String movie = film+" "+age+" "+gender;
//do anything else
}

Categories

Resources