I have a JTable with 7 column. I want to add at the seven one column a JButton with Icon.
So I have this:
mappa= modelManager.getContoBancarioManager().getContiBancari(null,WFConst.CONTO_BANCARIO_PUBBLICO);
//fontTable = new Font("Century Gothic", Font.PLAIN, 15);
tableModelContiBancari = new MyTableModelContiBancari();
tableContiBancari= new JTable(tableModelContiBancari);
tableModelContiBancari.stampaTabella(mappa);
tableContiBancari.addMouseListener(new MyMouseAdapterTableConti());
jScrollPane = new JScrollPane();
jScrollPane.setViewportView(tableContiBancari);
jScrollPane.setPreferredSize(dTabella);
Toolkit t = Toolkit.getDefaultToolkit();
Dimension screenSize = t.getScreenSize();
Double larghezza =screenSize.getWidth()*0.95;
// System.out.println(larghezza);
int lar = (int) (larghezza /90);
int lar2 = (int)(larghezza /5);
tableContiBancari.getColumnModel().getColumn(0).setPreferredWidth(10);
tableContiBancari.getColumnModel().getColumn(1).setPreferredWidth(lar2);
tableContiBancari.getColumnModel().getColumn(2).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(3).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(4).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(5).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(6).setPreferredWidth(lar);
Action delete = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
//to do
System.out.println("pp");
}
};
ButtonColumn buttonColumn = new ButtonColumn(tableContiBancari, delete, 7);
buttonColumn.setMnemonic(KeyEvent.VK_D);
This is ButtonColumn class:
public void daiProprietaJTableContiBancari(){
mappa= modelManager.getContoBancarioManager().getContiBancari(null,WFConst.CONTO_BANCARIO_PUBBLICO);
//fontTable = new Font("Century Gothic", Font.PLAIN, 15);
tableModelContiBancari = new MyTableModelContiBancari();
tableContiBancari= new JTable(tableModelContiBancari);
tableContiBancari.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_F5)
cambiaTipologiaConti();
}
});
tableModelContiBancari.stampaTabella(mappa);
//tableContiBancari.setFont(fontTable);
tableContiBancari.addMouseListener(new MyMouseAdapterTableConti());
jScrollPane = new JScrollPane();
jScrollPane.setViewportView(tableContiBancari);
jScrollPane.setPreferredSize(dTabella);
tableContiBancari.setRowHeight(25);
Toolkit t = Toolkit.getDefaultToolkit();
Dimension screenSize = t.getScreenSize();
Double larghezza =screenSize.getWidth()*0.95;
// System.out.println(larghezza);
int lar = (int) (larghezza /90);
int lar2 = (int)(larghezza /5);
tableContiBancari.getColumnModel().getColumn(0).setPreferredWidth(10);
tableContiBancari.getColumnModel().getColumn(1).setPreferredWidth(lar2);
tableContiBancari.getColumnModel().getColumn(2).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(3).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(4).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(5).setPreferredWidth(lar);
tableContiBancari.getColumnModel().getColumn(6).setPreferredWidth(lar);
DefaultTableCellRenderer renderer_archivi = new DefaultTableCellRenderer();
renderer_archivi.setHorizontalAlignment(SwingConstants.RIGHT);
tableContiBancari.getColumnModel().getColumn(4).setCellRenderer(renderer_archivi);
tableContiBancari.getColumnModel().getColumn(5).setCellRenderer(renderer_archivi);
tableContiBancari.getColumnModel().getColumn(6).setCellRenderer(renderer_archivi);
Action delete = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
//to do
System.out.println("pp");
}
};
ButtonColumn buttonColumn = new ButtonColumn(tableContiBancari, delete, 7);
buttonColumn.setMnemonic(KeyEvent.VK_D);
//tableContiBancari.getColumnModel().getColumn(7).setCellRenderer(new ButtonRenderer());
//tableContiBancari.getColumnModel().getColumn(7).setCellEditor(new ButtonEditor(new JCheckBox()));
//setUpColumnButton(tableContiBancari, tableContiBancari.getColumnModel().getColumn(7));
}
If I try to run the code, I have a JTable with a JButton at the last column but if I try to click on one JButton the action is not execute.
You need to implement your own TableCellRenderer and make its method getTableCellRendererComponent return a JButton for your column. See the Tutorial.
Check out Table Button Column for one approach.
You add text to the column the same way you do for any other column and then the ButtonColumn class is used as a:
renderer - so that the text is displayed on a button
editor - so you can click on the button to invoke an Action.
You must also provide an Action to the ButtonColumn class. The Action will have access to the row the clicked button. You can easily use the row number to delete the row for example, or use the row to get data from the table and do other processing.
Related
I am writing a program where I need to open a JFrame if a button is clicked. I set the default close operation to Dispose_on_close so that when I close the window the program doesn't shutdown completely.
In the frame that will be opened, i want to put a JTable, so I wrote two methods, a createFrame() method and a mechanicListTableProperties() which is the method that creates the JTable and adds elements to it. I then call the mechanicListTableProperties inside the createFrame() and the createFrame inside the actionPerformed() method. When I open the frame 1 time, the table is shown inside the window, but if I close and reopen the frame, the table is also readded and I see 2 tables, when I am trying to just see the one table again. Here is my source code:
public class SeeMechanicsButtonHandler implements ActionListener {
JFrame mechanicListFrame;
boolean isOpen = false;
JTable mechanicListTable;
JPanel tablePanel = new JPanel(new GridLayout());
JScrollPane sp;
List<String> names = new ArrayList<String>();
String[] namesArray;
public void createFrame() {
mechanicListFrame = new JFrame();
mechanicListFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
mechanicListFrame.setSize(new Dimension(500,500));
mechanicListFrame.add(tablePanel);
mechanicListFrame.setVisible(true);
//Prevents the window from being opened multiple times
mechanicListFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
isOpen = false;
}
});
}
public void mechanicListTableProperties(){
mechanicListTable = new JTable(){
public boolean isCellEditable(int row, int column) {
return false;
}
};
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Nome", namesArray);
//Creates a column with title as Nome and lines as the array
mechanicListTable.setModel(model); //adds column to the the table
mechanicListTable.setBounds(30, 40, 200, 300); //table size
mechanicListTable.setFont(new Font("Arial Rounded MT", Font.BOLD, 15));
// adding it to JScrollPane
sp = new JScrollPane(mechanicListTable);
tablePanel.add(sp);
}
public void actionPerformed(ActionEvent e) {
if(!isOpen) {
try {
//SQL code to get the data from mechanics table
ResultSet rs = ServerConnection.createQueryStatement("SELECT * FROM mechanics");
while (rs.next()){
//loop to add each entry in the table to an array list
names.add(rs.getString("nome"));
}
//creates an array to put the values from the arraylist
namesArray = new String[names.size()];
for (int iterate = 0; iterate < names.size(); iterate++){
//loop that iterates through the arraylist and puts the values in the array
namesArray[iterate] = names.get(iterate);
System.out.println(namesArray[iterate]);
//prints to the console for testing purposes
}
} catch (SQLException e1) {
e1.printStackTrace();
}
createFrame();
isOpen = true;
}
}
}
I have a custom made (excel like) table headers. Each header includes 2 labels, a column name and and an icon that when pressed opens a filter panel. each filter panel should have a table with two column. one a Boolean type and other one holds all the values from the column to be filtered. Hhow the filter looks:
When the program runs it creates 13 layered filtering panels. the table in the panels should be populate each with their table model but only the last table gets populated. The first 12 table have the right number of rows but the are empty. Can anyone help me understand what is it that i am doing wrong?
How the panels are displayed:
public CustomTable(String sQLTableName,int sqlColumnCount, String[] sQLColumns,String[] sqlLabelNames,String whereClause) {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1600, 800);
this.setVisible(true);
mainPanel = new JLayeredPane();
this.setContentPane(mainPanel);
totalPanel= new JPanel();totalPanel.setLayout(new FlowLayout(FlowLayout.CENTER,30,5));
mainPanel.setLayout(new BorderLayout());
//setContentPane(mainPanel);
scroll= new JScrollPane();scroll.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
obtainMetadataInfo(sQLTableName,sqlColumnCount, sQLColumns, sqlLabelNames, whereClause);
setMaintable(createInternalTable());
getMaintable().getColumnModel().addColumnModelListener(this);
panelFilter = createFilterPanel();
scroll.setViewportView(getMaintable());
mainPanel.add(scroll);
columnMarginChanged(new ChangeEvent(getMaintable().getColumnModel()));
mainPanel.add(panelFilter, BorderLayout.NORTH);mainPanel.add(totalPanel,BorderLayout.SOUTH);
totalMinsTxt = new JTextField("£ 10000.00");totalLabourCostTxt= new JTextField("£ 10000.00"); totalMaterialCostTxt = new JTextField("£ 10000.00"); totalCostTxt = new JTextField("£ 10000.00");
totalMinsLb=new JLabel("Total Minutes");totalLabourCostLb= new JLabel("Total Labour Cost");totalMaterialCostLb= new JLabel("Total Material Cost");totalCostLb = new JLabel("Total Cost");
totalPanel.add(totalMinsLb);totalPanel.add(totalMinsTxt);
totalPanel.add(totalLabourCostLb);totalPanel.add(totalLabourCostTxt);
totalPanel.add(totalMaterialCostLb);totalPanel.add(totalMaterialCostTxt);
totalPanel.add(totalCostLb);totalPanel.add(totalCostTxt);
}
public JPanel createFilterPanel(){
JPanel panel = new JPanel(); // Panel to hold all the Column Header labels
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
Font font = new Font("New Times Romen", Font.BOLD, 12);
filterPanels =new Box[SQLTableImport.getColumnCount()];// containers to hold the name of the column and the filter icon
filterText = new JLabel[SQLTableImport.getColumnCount()];// an array to hold the column header labels
filterIcons =new JLabel[SQLTableImport.getColumnCount()]; //an array to hold the filter icons
models =new DefaultTableModel[SQLTableImport.getColumnCount()];// an array to hold the table models to be added to each table in the filter panel
allFilterPanels = new FilterPanel[SQLTableImport.getColumnCount()]; // an array to hold the object of the FilterPanel class
for(int i = 0;i<SQLTableImport.getColumnCount();i++){
filterPanels[i] = Box.createHorizontalBox(); // create one container for each number of SQL columns
filterText[i] = new JLabel(SQLTableImport.getColumnNames()[i]); // create a label for each number of SQL columns to hold the column name
filterText[i].setHorizontalAlignment(SwingConstants.RIGHT);
filterIcons[i] = new JLabel(new ImageIcon(Icons.EXPAND));// create a label for each number of SQL columns to hold the expand icons
setColumnIndex(i);
SQLTableImport.setSqlSelectedType(SQLTableImport.getSqlColumnType()[getColumnIndex()]); // set the SQL object type
SQLTableImport.setSqlColumnName(SQLTableImport.getSqlColumnNames()[CustomTable.getColumnIndex()]); // set the SQL column name
FilterPanel.setTableColumnName(SQLTableImport.getColumnNames()[getColumnIndex()]);// set the SQL lable column name
String iconDescriptionColumn ="CASE WHEN non_conformances.Status='Complete' THEN (select Name from `icons` where ID='1' )WHEN `Deadline`> DATE(NOW()) and `Status`<>'Complete' THEN (select Name from `icons`"
+ " where ID='3')ELSE (select Name from `icons` where ID='2')END ";
model = new SQLTableImport(iconDescriptionColumn).getFilterModelFromSqlTable(); // model to be added in the filter table
models[i] = model; //add all the model in an array
allFilterPanels[i]= new FilterPanel(SQLTableImport.getSqlColumnType()[i]);
//((AbstractTableModel) allFilterPanels[i].getTableSearch().getModel()).fireTableDataChanged();
mainPanel.add(allFilterPanels[i]);
mainPanel.setLayer(allFilterPanels[i],new Integer(i),0);
allFilterPanels[i].setVisible(false);
filterIcons[i].setBorder(new LineBorder(new Color(0, 0, 0)));filterIcons[i].setOpaque(true);filterIcons[i].setBackground(SystemColor.menu);
final int index=i;
filterPanels[i].addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent arg0) {
filterPanels[index].setOpaque(true);
filterPanels[index].setBackground(new Color(51,98,140));
filterText[index].setForeground(Color.WHITE);
}
#Override
public void mouseExited(MouseEvent arg0) {
filterPanels[index].setOpaque(true);
filterPanels[index].setBackground(new Color(214,217,223));
filterText[index].setForeground(Color.BLACK);
}
#Override
public void mouseClicked(MouseEvent arg0) {
setFiltersInvisible(allFilterPanels);
filterIcons[index].setOpaque(true);
if(isSort){ //**************************************** create a map with index and true/false values to change the icons properly*******************
getMaintable().setModel(getMainModel().sortMainTable("ASC"));
filterIcons[index].setIcon(new ImageIcon(Icons.SELECTED_EXPAND));
isSort = false;
}
else{
getMaintable().setModel(getMainModel().sortMainTable("DESC"));
filterIcons[index].setIcon(new ImageIcon(Icons.EXPAND));
isSort = true;
}
}
});
filterIcons[i].addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
filterIcons[index].setOpaque(true);
filterIcons[index].setBackground(new Color(51,98,140));
setxCoordonateOnScreen(filterPanels[index].getX()+filterPanels[index].getWidth()-250); //set the x coordinate where the filter frame will be positioned
setyCoordonateOnScreen(filterPanels[index].getY()+(filterPanels[index].getHeight()*2)-2);
setTableWidth(panel.getWidth());
allFilterPanels[index].setVisible(true);
allFilterPanels[index].setLocation(getxCoordonateOnScreen(), getyCoordonateOnScreen());
}
#Override
public void mouseReleased(MouseEvent arg0) {
filterIcons[index].setOpaque(true);
filterIcons[index].setBackground(SystemColor.menu);
}
});
filterText[i].setFont(font);
filterPanels[i].add(filterText[i]);
filterPanels[i].add(Box.createHorizontalGlue());
filterPanels[i].add(filterIcons[i]);
panel.add(filterPanels[i]);
}
return panel;
}
public class FilterPanel extends JPanel{
public FilterPanel(String sqlType) {
if(sqlType.equals("DATE")){ // if the column type is date it creates a specific panel for filtering dates
createBasicFrame(); //create the frame, set the Content Pane,set the background colour, set the GridBagLayout, sets the close button
addDatePanelComponents(); // create the panel and add all the components for date frame
addBasicComponents();
adjustBasicComponents();
adjustDatePanel();
}
else if(sqlType.equals("BLOB")|| sqlType.equals("TINYINT")){// creates a specific panel for filtering icons and check boxes
createBasicFrame();
addBasicComponents();
addSearchTable();
adjustBasicComponents();
adjustSearchTable();
}
else{// the default filter panel
createBasicFrame();
addBasicComponents();
adjustBasicComponents();
addSearchTable();
addSearchPanel();
adjustTheSearchPanel();
adjustSearchTable();
}
}
public void addSearchTable( ){
setTableSearch(new JTable());
getTableSearch().setModel(CustomTable.models[CustomTable.getColumnIndex()]);// set the model to the search table from the array of models which is obtain from SQLTableImport class
adjustTable();
searchScroll = new JScrollPane();
searchScroll.setViewportView(getTableSearch());
}
public void adjustSearchTable(){
/////////Third Row////////
addComp(this, searchScroll, 0, 3, 5,1, 0, 4.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH);
}
public void adjustBasicComponents(){
//////First Row//////
addComp(this, title, 0, 0, 5,1, 1, 0.1, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE);
addComp(this, closeLabel, 1, 0, 1,1, 1, 0.1, GridBagConstraints.FIRST_LINE_END, GridBagConstraints.NONE);
//////////Second Row//////////
addComp(this, cleareIcon, 0, 1, 1,1, 1, 0.1, GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE);
addComp(this, clearTxt, 1, 1, 1,1, 2, 0.1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL);
/////Last Row//////
addComp(this, cancelBt, 0, 4, 2,1, 1, 0.1, GridBagConstraints.EAST, GridBagConstraints.NONE);
addComp(this, okBt, 1, 4, 1,1, 1, 0.1, GridBagConstraints.CENTER, GridBagConstraints.NONE);
}
private void addComp(JPanel thePanel, JComponent comp, int xPos, int yPos, int gridW, int gridH,double compWidth,double compHeight, int place, int stretch){
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = xPos;// Define the x position of the component
gridConstraints.gridy = yPos;// Define the y position of the component
gridConstraints.gridwidth = gridW;// Number of columns the component takes up
gridConstraints.gridheight = gridH;// Number of rows the component takes up
gridConstraints.weightx = compWidth;// Gives the layout manager a hint on how to adjust component width (0 equals fixed)
gridConstraints.weighty = compHeight;// Gives the layout manager a hint on how to adjust component height (0 equals fixed)
gridConstraints.insets = new Insets(5,5,5,5);// Defines padding top, left, bottom, right
gridConstraints.anchor = place;// Defines where to place components if they don't fill the space: CENTER, NORTH, SOUTH, EAST, WEST NORTHEAST, etc.
gridConstraints.fill = stretch;// How should the component be stretched to fill the space: NONE, HORIZONTAL, VERTICAL, BOTH
thePanel.add(comp, gridConstraints);
}
}
public class SQLTableImport {
//***********Constructor for Filter Table export (2 columns Check box and string)**********
public SQLTableImport(String descriptionColumn){
if(getSqlSelectedType().equals("BLOB")){
setSql("SELECT DISTINCT "+getSqlColumnName()+" , "+descriptionColumn+" FROM `"+ getTableName() +"`"+whereClause+"");
}
else{
setSql("SELECT DISTINCT "+getSqlColumnName()+" FROM `"+ getTableName() +"`"+whereClause+"");
}
}
//***********METHOD FOR RETURNING THE MODEL FOR A FILTER FRAME 1 COLUMN AND 1 CHECKBOX COLUMN
public DefaultTableModel getFilterModelFromSqlTable(){
if(getSqlSelectedType().equals("BLOB")){emptyHeaders= new Object[][]{null,null,null};}
DefaultTableModel dFilterTableModel = new DefaultTableModel(emptyrows, emptyHeaders){
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
return column == 0;
}
public Class <?> getColumnClass(int column) {
if(column==0){
return Boolean.class;
}
if(column==2){
return String.class;
}
switch (getSqlColumnType()[CustomTable.getColumnIndex()]) {
case "VARCHAR":
return String.class;
case "INT":
return Integer.class;
case "DECIMAL":
return Double.class;
case "DATE":
return Date.class;
case "TINYINT":
return String.class;
case "BLOB":
return Icon.class;
default:
return Object.class;
}
}
};
try {
setPst(Utilities.sqlConnnect().prepareStatement(getSql()));
setRs(getPst().executeQuery(getSql()));
java.sql.ResultSetMetaData tempResult = getPst().getMetaData();
int tempColumnCount = tempResult.getColumnCount();
Object[] tempRow= new Object[tempColumnCount+1];
while(getRs().next()){
// Gets the column values based on class type expected
tempRow[0]= false;
if(getSqlColumnType()[CustomTable.getColumnIndex()].equals("VARCHAR")){
tempRow[tempColumnCount]= getRs().getString(tempColumnCount);
}
if(getSqlColumnType()[CustomTable.getColumnIndex()].equals("INT")){
tempRow[tempColumnCount]= getRs().getInt(tempColumnCount);
}
if(getSqlColumnType()[CustomTable.getColumnIndex()].equals("DECIMAL")){
tempRow[tempColumnCount]= getRs().getDouble(tempColumnCount);
}
if(getSqlColumnType()[CustomTable.getColumnIndex()].toString().equals("DATE")){
}
if(getSqlColumnType()[CustomTable.getColumnIndex()].equals("TINYINT")){
tempRow[tempColumnCount]= getRs().getBoolean(tempColumnCount);
}
if(getSqlColumnType()[CustomTable.getColumnIndex()].equals("BLOB")){
Blob blob = getRs().getBlob(tempColumnCount-1);
ImageIcon icon = null;
try (InputStream is = blob.getBinaryStream()) {
BufferedImage img = ImageIO.read(is);
icon = new ImageIcon(img.getScaledInstance(17, 17, Image.SCALE_SMOOTH));
}
tempRow[tempColumnCount-1] =icon;
tempRow[tempColumnCount]= getRs().getString(tempColumnCount);
}
// Adds the row of data to the end of the model
dFilterTableModel.addRow(tempRow);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,e);
}
finally {
try {
getPst().close();
getRs().close();
} catch (SQLException e1) {
JOptionPane.showMessageDialog(null,e1);
}
}
return dFilterTableModel;}
}
When the program runs it creates 13 layered filtering panels. the table in the panels should be populate each with their table model but only the last table gets populated.
searchScroll = new JScrollPane();
searchScroll.setViewportView(getTableSearch());
I don't see where you ever add the scroll pane to a panel.
You can't just create 13 scroll panes without adding each one individually to a panel.
The "searchScroll" variable can only reference the last one created which would my guess why you only see the last table.
I was wondering in someone could point me in the right direction for this. I have this simple calculator, where the user enters two numbers and then has to select an action (+, -, *, *) from a drop down menu.
After they select an option, it gives them an answer, but I was trying to add a check box to allow the result to be displayed as a float if the box was checked. I was confused on how to have the actionPreformed handle both the JCheckBox and the JComboBox. I tried just adding newCheckBox, but that causes casting errors, between JCheckBox and JComboBox.
public class Calculator2 implements ActionListener {
private JFrame frame;
private JTextField xfield, yfield;
private JLabel result;
private JPanel xpanel;
String[] mathStrings = { "Multiply", "Subtraction", "Division", "Addition"}; //Options for drop down menu
JComboBox mathList = new JComboBox(mathStrings); //Create drop down menu and fill it
public Calculator2() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
xpanel = new JPanel();
xpanel.setLayout(new GridLayout(3,2));
xpanel.add(new JLabel("x:", SwingConstants.RIGHT));
xfield = new JTextField("0", 5);
xpanel.add(xfield);
xpanel.add(new JLabel("y:", SwingConstants.RIGHT));
yfield = new JTextField("0", 5);
xpanel.add(yfield);
xpanel.add(new JLabel("Result:"));
result = new JLabel("0");
xpanel.add(result);
frame.add(xpanel, BorderLayout.NORTH);
JPanel southPanel = new JPanel(); //New panel for the drop down menu
southPanel.setBorder(BorderFactory.createEtchedBorder());
JCheckBox newCheckBox = new JCheckBox("Show My Answer In Floating Point Format"); //Check box to allow user to view answer in floating point
southPanel.add(newCheckBox);
//newCheckBox.addActionListener(this);
southPanel.add(mathList);
mathList.addActionListener(this);
frame.add(southPanel , BorderLayout.SOUTH);
Font thisFont = result.getFont(); //Get current font
result.setFont(thisFont.deriveFont(thisFont.getStyle() ^ Font.BOLD)); //Make the result bold
result.setForeground(Color.red); //Male the result answer red in color
result.setBackground(Color.yellow); //Make result background yellow
result.setOpaque(true);
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent event) {
String xText = xfield.getText(); //Get the JLabel fiels and set them to strings
String yText = yfield.getText();
int xVal;
int yVal;
try {
xVal = Integer.parseInt(xText); //Set global var xVal to incoming string
yVal = Integer.parseInt(yText); //Set global var yVal to incoming string
}
catch (NumberFormatException e) { //xVal or yVal werent valid integers, print message and don't continue
result.setText("ERROR");
//clear();
return ;
}
JComboBox comboSource = (JComboBox)event.getSource(); //Get the item picked from the drop down menu
String selectedItem = (String)comboSource.getSelectedItem();
if(selectedItem.equalsIgnoreCase("Multiply")) { //multiply selected
result.setText(Integer.toString(xVal*yVal));
}
else if(selectedItem.equalsIgnoreCase("Division")) { //division selected
if(yVal == 0) { //Is the yVal (bottom number) 0?
result.setForeground(Color.red); //Yes it is, print message
result.setText("CAN'T DIVIDE BY ZERO!");
//clear();
}
else
result.setText(Integer.toString(xVal/yVal)); //No it's not, do the math
}
else if(selectedItem.equalsIgnoreCase("Subtraction")) { //subtraction selected
result.setText(Integer.toString(xVal-yVal));
}
else if(selectedItem.equalsIgnoreCase("Addition")) { //addition selected
result.setText(Integer.toString(xVal+yVal));
}
}
}
What I would recommend is that you keep a reference to the JCheckBox in the Calculator2 class. So something along the lines of
public class Calculator implements ActionListener {
...
JComboBox mathList = ...
JCheckBox useFloatCheckBox = ...
...
}
then in your actionPerformed mehtod, instead of getting the reference to the widget from event.getSource() get it directly from the reference in the class. So actionPerformed would look like this
public void actionPerformed(ActionEvent e) {
String operator = (String)this.mathList.getSelected();
boolean useFloat = this.useFloatCheckBox.isSelected();
...
}
This way you can use the same listener on both objects without having to worry about casting the widget.
The casting errors are because event.getSource() changes depending on which object fired the event. You can check the source of the event and process based on that:
if (event.getSource() instanceof JCheckBox) { ... act accordingly ... } else
Instead you could add a different ActionListener implementation to the JCheckBox so that the event it creates goes to a different place. An anonymous listener that sets a flag or calls a different method would work too.
There are other ways you could approach the problem, do you want the checkbox to affect an existing calculation, or only a new one? If only a new calculation you don't need an action listener on the checkbox, you can find out whether it is checked when you do the calculation:
if (myCheckbox.isSelected()) {
// do float calculation...
} else {
// do int calculation
}
I'm creating a matching style game in java that displays a group of thumbnails which expand into picture with 3 radio buttons, 1 correct and 2 incorrect. Currently I have the 1st rb displaying the correct answer, it should be able to display on the second or 3rd but I can't figure out how to get it there.
So the possibilities would be (CII, ICI, or IIC)
(the rb text gets pulled from the filenames of the pictures)
final JTextArea textArea = new JTextArea();
add(textArea);
JRadioButton rb1 = new JRadioButton(rb1Text);
add(rb1);
rb1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
textArea.setText("Correct");
}
});
JRadioButton rb2 = new JRadioButton(rb2Text);
add(rb2);
rb2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
textArea.setText("Guess Again");
}
});
JRadioButton rb3 = new JRadioButton(rb3Text);
add(rb3);
rb3.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
textArea.setText("Guess Again");
}
});
ButtonGroup group = new ButtonGroup();
group.add(rb1);
group.add(rb2);
group.add(rb3);
Figured it out: I changed the setBounds to include a one of the 3 desired y values pulled from a shuffled collection.
ArrayList<String> obj = new ArrayList<String>();
obj.add("250");
obj.add("300");
obj.add("350");
Collections.shuffle(obj);
int rand1 = Integer.parseInt(obj.get(0));
int rand2 = Integer.parseInt(obj.get(1));
int rand3 = Integer.parseInt(obj.get(2));
rb1.setBounds(400, rand1, 200, 15);
rb2.setBounds(400, rand2, 200, 15);
rb3.setBounds(400, rand3, 200, 15);
So every time the next or previous button is pressed it puts the correct answer in a different spot.
Thanks for the ideas Hovercraft Full Of Eels!
Okay so I am making a 2d array of JToggleButtons. I got the action listener up and going, but I have no way to tell which button is which.
If I click one, all it returns is something like
javax.swing.JToggleButton[,59,58,19x14,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource#53343ed0,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=]
Is there anyway to stick some sort of item or number in the button object to associate each button?
And then when the button is clicked I can retrieve that item or number that was given to it?
Here is my button generator code. (How could I make "int l" associate (and count) to each button made, when it is called, it will return that number, or something along those lines.
JToggleButton buttons[][] = new JToggleButton[row][col];
int l = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
buttons[i][j] = new JToggleButton("");
buttons[i][j].setSize(15,15);
buttons[i][j].addActionListener(new e());
panel.add(buttons[i][j]);
l++;
}
}
ActionListner
public class e implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
System.out.println(source);
}
}
variable "source" is what I use to get my data, so how can int l, be returned through "source" (as its unique value for the unique button clicked) as a button is clicked?
Thanks,
-Austin
very simple way is add ClientProperty to the JComponent, add to your definition into loop e.g.
buttons[i][j].putClientProperty("column", i);
buttons[i][j].putClientProperty("row", j);
buttons[i][j].addActionListener(new MyActionListener());
rename e to the MyActionListener and change its contents
public class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JToggleButton btn = (JToggleButton) e.getSource();
System.out.println("clicked column " + btn.getClientProperty("column")
+ ", row " + btn.getClientProperty("row"));
}
EDIT:
for MinerCraft clone isn't required to implements ony of Listeners, there is only about Icon, find out that in this code (don't implement any of Listeners anf remove used ItemListener)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonsIcon extends JFrame {
private static final long serialVersionUID = 1L;
private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon");
private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ButtonsIcon t = new ButtonsIcon();
}
});
}
public ButtonsIcon() {
setLayout(new GridLayout(2, 2, 4, 4));
JButton button = new JButton();
button.setBorderPainted(false);
button.setBorder(null);
button.setFocusable(false);
button.setMargin(new Insets(0, 0, 0, 0));
button.setContentAreaFilled(false);
button.setIcon((errorIcon));
button.setRolloverIcon((infoIcon));
button.setPressedIcon(warnIcon);
button.setDisabledIcon(warnIcon);
add(button);
JButton button1 = new JButton();
button1.setBorderPainted(false);
button1.setBorder(null);
button1.setFocusable(false);
button1.setMargin(new Insets(0, 0, 0, 0));
button1.setContentAreaFilled(false);
button1.setIcon((errorIcon));
button1.setRolloverIcon((infoIcon));
button1.setPressedIcon(warnIcon);
button1.setDisabledIcon(warnIcon);
add(button1);
button1.setEnabled(false);
final JToggleButton toggleButton = new JToggleButton();
toggleButton.setIcon((errorIcon));
toggleButton.setRolloverIcon((infoIcon));
toggleButton.setPressedIcon(warnIcon);
toggleButton.setDisabledIcon(warnIcon);
toggleButton.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (toggleButton.isSelected()) {
} else {
}
}
});
add(toggleButton);
final JToggleButton toggleButton1 = new JToggleButton();
toggleButton1.setIcon((errorIcon));
toggleButton1.setRolloverIcon((infoIcon));
toggleButton1.setPressedIcon(warnIcon);
toggleButton1.setDisabledIcon(warnIcon);
toggleButton1.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (toggleButton1.isSelected()) {
} else {
}
}
});
add(toggleButton1);
toggleButton1.setEnabled(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
}
Just add the row and column data to each listener. You could add an explicit constructor, but I suggest adding a little method (which may have more added to it later).
buttons[i][j].addActionListener(e(i, j));
...
private ActionListener e(final int i, final int j) {
return new ActionListener() {
// i and j available here
...
(In JDK8 you should be able to use a lambda to reduce the syntax clutter.)
And then renaming it with a better name.
I made a minesweeper game and ran into a similar problem. One of the only ways you can do it, is to get the absolute location of the clicked button, then divide that by the x and y between buttons, so for me it was
if ((e.getComponent().getX() != (randx) * 25 && e.getComponent().getY() != (randy) * 25) &&bomb[randx][randy] == false) {
This code was to check if the area had bombs. So I had 25 x and y difference between location of bombs. That will just give you a general idea on how to do this.
I believe: (x - x spacing on left side) / buffer - 1 would work.
Instead of 'e.getSource()' you can always call 'e.getActionCommand()'. For each button you can specify this by:
JButton button = new JButton("Specify your parameters here"); /*you get these from getActionCommand*/
button.setText("title here"); /*as far as I remember*/