Affichage des articles dont le libellé est java. Afficher tous les articles
Affichage des articles dont le libellé est java. Afficher tous les articles

Java JTable With Custom Columns

How to Create a JTable with Custom Columns In Java Netbeans

Create JTable With RadioButton, CheckBox, ComboBox, Spinner, TextField and Button Columns In Java Netbeans


In this Java Tutorial we will see How To Create a JTable with custom components in each cell. The table has six columns: RadioButton, CheckBox, ComboBox, Spinner, TextField, and Button.
For each column in the table, custom renderers and editors are set using the setColumnRendererAndEditor method. 
This method associates a TableCellRenderer (for rendering cell content) and a TableCellEditor (for editing cell content) with a specific column in the table.
The getJobList Method: Returns an array of job titles. This array is used to populate the ComboBox in the third column.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.






Project Source Code:

RadioButtonRenderer Class:

public class RadioButtonRenderer extends JRadioButton implements TableCellRenderer{

    public RadioButtonRenderer(){
        setHorizontalAlignment(SwingConstants.CENTER);
        setOpaque(false);
    }
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
     
        // Set the selected state based on the value
        setSelected(value != null && (boolean)value);
        return this;
    
    }

}


RadioButtonEditor Class:

public class RadioButtonEditor extends AbstractCellEditor implements TableCellEditor{

    private final JRadioButton button;
    
    public RadioButtonEditor(){
        button = new JRadioButton();
        button.setHorizontalAlignment(SwingConstants.CENTER);
    }
    
    
    @Override
    public Object getCellEditorValue() {
    
        // retun the value of the radiobutton
        return button.isSelected();
        
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    
        // Set the selected state based on the value
        button.setSelected(value != null && (boolean)value);
        return button;
        
    }

    
}


JTable With RadioButton Column





CheckBoxRenderer Class:

public class CheckBoxRenderer extends DefaultTableCellRenderer{

    private final JCheckBox checkBox = new JCheckBox();
    
    public CheckBoxRenderer(){
        checkBox.setHorizontalAlignment(SwingConstants.CENTER);
    }
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
     
        // Set the selected state based on the value
        checkBox.setSelected(value != null && (boolean)value);
        return checkBox;
    
    }
    
}


CheckBoxEditor Class:

public class CheckBoxEditor extends AbstractCellEditor implements TableCellEditor{

    private final JCheckBox checkBox = new JCheckBox();
    
    public CheckBoxEditor(){
        checkBox.setHorizontalAlignment(SwingConstants.CENTER);
    }
    
    @Override
    public Object getCellEditorValue() {
    
        // retun the value of the checkbox
        return checkBox.isSelected();
        
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    
        // Set the selected state based on the value
        checkBox.setSelected((boolean)value);
        return checkBox;
        
    }
    
}


JTable With CheckBox Column





ComboboxRenderer Class:

public class ComboboxRenderer extends JComboBox<String> implements TableCellRenderer{

    public ComboboxRenderer(String[] items){ super(items); }
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
     
        // Set the selected item in the JComboBox based on the cell value
        setSelectedItem(value);
        
        // Ensure the JComboBox is focused before rendering
        if(hasFocus){ requestFocusInWindow(); } 
        
        return this;
    }

}



ComboboxEditor Class:

public class ComboboxEditor extends DefaultCellEditor{

    public ComboboxEditor(String[] items){ 
        super(new JComboBox<>(items)); 
        // Set the number of clicks needed to start editing
        setClickCountToStart(0);
    }
    
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
     
         // Set the selected item in the JComboBox based on the cell value
         ((JComboBox<?>) editorComponent).setSelectedItem(value);
         
         // Ensure the JComboBox is focused before editing
         SwingUtilities.invokeLater(() -> {
             ((JComboBox<?>) editorComponent).requestFocusInWindow();
         });
        
         return editorComponent;
    }
    
    
    @Override
    public Object getCellEditorValue(){
        // Return the selected item from the JComboBox
        return ((JComboBox<?>) editorComponent).getSelectedItem();
    }
  
}


JTable With ComboBox Column





SpinnerRenderer Class:

public class SpinnerRenderer extends JSpinner implements TableCellRenderer{
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    
        // set value of the spinner
        setValue(value);
        return this;
    
    }

}



SpinnerEditor Class:

public class SpinnerEditor extends DefaultCellEditor{

    public SpinnerEditor(JSpinner spinner) {
        // Initialize the spinner editor
        super(new JCheckBox());
        editorComponent = spinner;
        delegate = new EditorDelegate() {
            
            // Set the value of the spinner
            @Override
            public void setValue(Object value){spinner.setValue(value);}
            
            // Get the value of the spinner
            @Override
            public Object getCellEditorValue(){ return spinner.getValue(); }
            
        };
    }
 
}



JTable With Spinner Column





TextFieldRenderer Class:

public class TextFieldRenderer extends JTextField implements TableCellRenderer{

    public TextFieldRenderer(){setHorizontalAlignment(JTextField.CENTER);}

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      
        // Set the text of the text field
        setText(value != null ? value.toString() : "");
        return this;
        
    }
    
}



JTable With TextField Column





ButtonRenderer Class:

public class ButtonRenderer extends JButton implements TableCellRenderer{

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    
        // Set the text of the button
        setText(value != null ? value.toString() : "");
        return this;
        
    }

}




ButtonEditor Class:

public class ButtonEditor extends DefaultCellEditor{

    private JButton button;
    
    public ButtonEditor(JCheckBox checkBox) {
        // Initialize the button editor and add action listener for button click
        super(checkBox);
        button = new JButton();
        button.addActionListener((e) -> {
            JOptionPane.showMessageDialog(button, button.getText() + " Clicked");
        });
        
    }
    
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        // Set the text of the button
        button.setText(value != null ? value.toString() : "");
        return button;        
    }
    
    // Get the text of the button
    @Override
    public Object getCellEditorValue(){ return button.getText(); }

}



JTable With Button Column





CustomTableModel Class:

public class CustomTableModel extends AbstractTableModel{
    private final Object[][] data;
    private final String[] columnNames;
    
    public CustomTableModel(Object[][] data, String[] columnNames){
        this.data = data;
        this.columnNames = columnNames;
    }
    

    @Override
    public int getRowCount() { return data.length; }

    @Override
    public int getColumnCount() { return columnNames.length; }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
    
        return data[rowIndex][columnIndex];
        
    }

    @Override
    public String getColumnName(int column){ return columnNames[column]; }
    
    @Override
    public Class<?> getColumnClass(int column){ return data[0][column].getClass(); }
    
    @Override
    public boolean isCellEditable(int row, int column){ return true; }
    
    @Override
    public void setValueAt(Object value, int row, int column){
        // Update the data and notify listeners of the change
        data[row][column] = value;
        fireTableCellUpdated(row, column);
    }
    
    
}






The MainClass Class:

public class MainClass extends JFrame{

    public MainClass(){
        setTitle("Table Custom Component");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        CustomTableModel model = new CustomTableModel(
                new Object[][]{
                        {false, false, "Developer", 1, "Text 1", "Button 1"},
                        {false, true, "Designer", 2, "Text 2", "Button 2"},
                        {true, false, "Manager", 3, "Text 3", "Button 3"},
                        {true, false, "Engineer", 4, "Text 4", "Button 4"}
                },
                new String[]{"RadioButton", "CheckBox", "ComboBox", "Spinner", "TextField", "Button"}
        );
        
        
        JTable table = new JTable(model);
        table.setRowHeight(40);
        
        setColumnRendererAndEditor(table, 0, new RadioButtonRenderer(), new RadioButtonEditor());
        setColumnRendererAndEditor(table, 1, new CheckBoxRenderer(), new CheckBoxEditor());
        setColumnRendererAndEditor(table, 2, new ComboboxRenderer(getJobList()), new ComboboxEditor(getJobList()));
        setColumnRendererAndEditor(table, 3, new SpinnerRenderer(), new SpinnerEditor(new JSpinner()));
        setColumnRendererAndEditor(table, 4, new TextFieldRenderer(), new DefaultCellEditor(new JTextField()));
        setColumnRendererAndEditor(table, 5, new ButtonRenderer(), new ButtonEditor(new JCheckBox()));
        
        
        JScrollPane scrollPanel = new JScrollPane(table);
        add(scrollPanel);
        setSize(600, 400);
        setLocationRelativeTo(null);
        
    }
    
    
    private void setColumnRendererAndEditor(JTable table, int columnIndex, TableCellRenderer renderer, TableCellEditor editor){
        // Set the renderer and editor for a specific column
        table.getColumnModel().getColumn(columnIndex).setCellRenderer(renderer);
        table.getColumnModel().getColumn(columnIndex).setCellEditor(editor);
    }
    
    
    private String[] getJobList(){
        // Return an array of job titles
        // we will use it to populate the combobox
        return new String[]{"Engineer", "Designer", "Manager", "Developer", "Analyst"};
        
    }
    
    
    public static void main(String[] args) {
        MainClass app = new MainClass();
        app.setVisible(true);
    }
    
}



The Final Result:

Java JTable With Custom Columns


if you want the full source code click on the download button below




disclaimer: you will get the source code, and to make it work in your machine is your responsibility and to debug any error/exception is your responsibility this project is for the students who want to see an example and read the code not to get and run.








Java Colors Code Extractor From Image

How to Extract Colors From an Image in Java Netbeans

How to Extract Colors From an Image in Java Netbeans


In this Java Tutorial we will see How To load an image and extract unique colors from it, and display those colors along with their codes using java netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.






Load Image Functionality:
The chooseAndDisplayImage() method is triggered when the "Load Image" button is clicked. 
It uses JFileChooser to let the user select an image file. 
If an image is selected, it's loaded using loadImage() and displayed in imageLabel. 
Unique colors are then extracted and displayed using the extractUniqueColors() method.

Color Extraction:
The extractUniqueColors() method iterates through the image pixels, sampling every 10 pixels in both dimensions, and unique colors are stored in a HashSet.

Displaying Unique Colors:
The displayUniqueColors() method populates the colorsPanel with panels representing unique colors. Each color is displayed in a small square, and its corresponding code is shown below.

Components:
- JLabel (imageLabel): Displays the loaded image. 
- JPanel (colorsPanel): Displays unique colors extracted from the image. 
- JButton (loadImageButton): Initiates the process of loading an image. 
- JFileChooser (fileChooser): Allows the user to choose an image file.



Java Colors Code Extractor From Image 1

Java Colors Code Extractor From Image 2





Project Source Code:


/**
 *
 * @author 1BestCsharp
 */
// Main class representing the application window
public class ColorsCodeExtractorApp extends JFrame{
   
    // Label for displaying the loaded image
    private final JLabel imageLabel;
    // Panel for displaying unique colors
    private final JPanel colorsPanel;
    // Button for loading images
    private JButton loadImageButton;
    
    // Constructor for initializing the main application window
    public ColorsCodeExtractorApp(){
        // set up the frame
        setTitle("Colors Code Extractor App");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800,700);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());
        
        // Create a label for displaying the image
        imageLabel = new JLabel();
        imageLabel.setSize(getWidth(),getHeight());
        imageLabel.setHorizontalAlignment(JLabel.CENTER);
        imageLabel.setVerticalAlignment(JLabel.CENTER);
        imageLabel.setOpaque(true);
        imageLabel.setBackground(Color.WHITE);
        
        // Create a panel for displaying unique colors
        colorsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        colorsPanel.setBackground(Color.GRAY);
        
        // Create a scrollable panel for the color display
        JScrollPane colorsScrollPane = new JScrollPane(colorsPanel);
        colorsScrollPane.setPreferredSize(new Dimension(colorsScrollPane.getPreferredSize().width, 100));
        
        // Add components to the main frame
        add(new JScrollPane(imageLabel), BorderLayout.CENTER);
        add(colorsScrollPane, BorderLayout.SOUTH);
        
        addLoadImageButton();
        
    }
    
    
    // Function to add the "Load Image" button
    private void addLoadImageButton(){
        loadImageButton = new JButton("Load Image");
        loadImageButton.setPreferredSize(new Dimension(150,40));
        loadImageButton.setFont(new Font("Arial",Font.BOLD,17));
        loadImageButton.setBackground(new Color(30,144,255));
        loadImageButton.setForeground(Color.WHITE);
        loadImageButton.setBorderPainted(false);
        loadImageButton.setFocusPainted(false);
        loadImageButton.setContentAreaFilled(true);
        loadImageButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        loadImageButton.addActionListener((e) -> {
            // select and display image
            chooseAndDisplayImage();
        });
        
        JPanel buttonPanel = new JPanel();
        buttonPanel.setBackground(Color.DARK_GRAY);
        buttonPanel.add(loadImageButton);
        add(buttonPanel, BorderLayout.NORTH);
        
    }
    
    
    // Function to handle choosing and displaying an image
    private void chooseAndDisplayImage(){
        
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showOpenDialog(this);
        
        if(result == JFileChooser.APPROVE_OPTION){
            // User selected a file
            File selectedFile = fileChooser.getSelectedFile();
            BufferedImage image = loadImage(selectedFile);
            
            if(image != null){
                // Display the selected image
                imageLabel.setIcon(new ImageIcon(image));
                extractUniqueColors(image);
            }
            else{
                JOptionPane.showMessageDialog(this, "Failed to load the image");
            }
        }
        
    }
    
    
    // Function to load an image from a file
    private BufferedImage loadImage(File file){
        
        try{ return ImageIO.read(file); }
        
        catch(IOException ex){
            
            System.out.println(ex.getMessage());
            return null;
            
        }
    }
    
    
    // Function to display unique colors in the UI
    private void displayUniqueColors(HashSet<Integer> uniqueColors){
        
        // clear the panel
        colorsPanel.removeAll();
        
        // Create color panels and labels for each unique color
        for(Integer rgb : uniqueColors){
            
            Color color = new Color(rgb);
            String colorCode = String.format("#%02X%02X%02X", color.getRed(), color.getGreen(),color.getBlue());
            
            JPanel colorPanel = new JPanel();
            colorPanel.setPreferredSize(new Dimension(60, 50));
            colorPanel.setBackground(color);
            
            JLabel colorLabel = new JLabel(colorCode);
            colorLabel.setOpaque(true);
            colorLabel.setBackground(Color.WHITE);
            colorLabel.setHorizontalAlignment(JLabel.CENTER);
            
            JPanel colorInfoPanel = new JPanel(new BorderLayout());
            colorInfoPanel.add(colorPanel,BorderLayout.CENTER);
            colorInfoPanel.add(colorLabel,BorderLayout.SOUTH);
            
            colorsPanel.add(colorInfoPanel);
            
        }
        
        // Refresh the color display panel
        colorsPanel.revalidate();
        colorsPanel.repaint();
        
    }
    
    
    // Function to extract unique colors from the image
    private void extractUniqueColors(BufferedImage image){
        
        // Extract unique colors from the image
        HashSet<Integer> uniqueColors = new HashSet<>();
        
        int width = image.getWidth();
        int height = image.getHeight();
        
        for(int x = 0; x < width; x += 10){
            for(int y = 0; y < height; y += 10){
                int rgb = image.getRGB(x, y);
                uniqueColors.add(rgb);
            }
        }
        
        // Display the unique colors
        displayUniqueColors(uniqueColors);
        
    }
    
    

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        ColorsCodeExtractorApp app = new ColorsCodeExtractorApp();
        app.setVisible(true);
        
    }

}



The Final Result:

Java Colors Code Extractor From Image 3

Java Colors Code Extractor From Image 4

Java Colors Code Extractor From Image 5


if you want the source code click on the download button below